keras 和 tensorflow的结合

tensorflow keras详细的api

https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer

keras内部的核心函数

  • build(self, input_shape): This method can be used to create weights that depend on the shape(s) of the input(s), using add_weight()__call__() will automatically build the layer (if it has not been built yet) by calling build().
  • # 主要定义模型的构成(各层及其参数)
  • call(self, inputs, *args, **kwargs): Called in __call__ after making sure build() has been called. call() performs the logic of applying the layer to the input tensors (which should be passed in as argument). Two reserved keyword arguments you can optionally use in call() are:
    • training (boolean, whether the call is in inference mode or training mode). See more details in the layer/model subclassing guide
    • mask (boolean tensor encoding masked timesteps in the input, used in RNN layers). See more details in the layer/model subclassing guide A typical signature for this method is call(self, inputs), and user could optionally add training and mask if the layer need them. *args and **kwargs is only useful for future extension when more input parameters are planned to be added.
    • #call主要定义层的计算逻辑

tensorflow session.run函数的api

​​​​​​https://github.com/tensorflow/docs/blob/r1.14/site/en/api_docs/python/tf/Session.md#run

run(
    fetches,
    feed_dict=None,
    options=None,
    run_metadata=None
)

Runs operations and evaluates tensors in fetches.

This method runs one "step" of TensorFlow computation, by running the necessary graph fragment to execute every Operation and evaluate every Tensor in fetches, substituting the values in feed_dict for the corresponding input values.

The fetches argument may be a single graph element, or an arbitrarily nested list, tuple, namedtuple, dict, or OrderedDict containing graph elements at its leaves. A graph element can be one of the following types:

  • tf.Operation. The corresponding fetched value will be None.
  • tf.Tensor. The corresponding fetched value will be a numpy ndarray containing the value of that tensor.
  • tf.SparseTensor. The corresponding fetched value will be a tf.compat.v1.SparseTensorValue containing the value of that sparse tensor.
  • get_tensor_handle op. The corresponding fetched value will be a numpy ndarray containing the handle of that tensor.
  • string which is the name of a tensor or operation in the graph.

The value returned by run() has the same shape as the fetches argument, where the leaves are replaced by the corresponding values returned by TensorFlow.

# session.run第一个参数必须对应特定的数据类型。

The optional feed_dict argument allows the caller to override the value of tensors in the graph. Each key in feed_dict can be one of the following types:

  • If the key is a tf.Tensor, the value may be a Python scalar, string, list, or numpy ndarray that can be converted to the same dtype as that tensor. Additionally, if the key is a tf.compat.v1.placeholder, the shape of the value will be checked for compatibility with the placeholder.
  • If the key is a tf.SparseTensor, the value should be a tf.compat.v1.SparseTensorValue.
  • If the key is a nested tuple of Tensors or SparseTensors, the value should be a nested tuple with the same structure that maps to their corresponding values as above.
  • #feed_dict格式为dict,key必须对应特定的数据类型

Each value in feed_dict must be convertible to a numpy array of the dtype of the corresponding key.

The optional options argument expects a [RunOptions] proto. The options allow controlling the behavior of this particular step (e.g. turning tracing on).

The optional run_metadata argument expects a [RunMetadata] proto. When appropriate, the non-Tensor output of this step will be collected there. For example, when users turn on tracing in options, the profiled info will be collected into this argument and passed back.

Args:

  • fetches: A single graph element, a list of graph elements, or a dictionary whose values are graph elements or lists of graph elements (described above).
  • feed_dict: A dictionary that maps graph elements to values (described above).
  • options: A [RunOptions] protocol buffer
  • run_metadata: A [RunMetadata] protocol buffer

Returns:

Either a single value if fetches is a single graph element, or a list of values if fetches is a list, or a dictionary with the same keys as fetches if that is a dictionary (described above). Order in which fetches operations are evaluated inside the call is undefined.

Raises:

  • RuntimeError: If this Session is in an invalid state (e.g. has been closed).
  • TypeError: If fetches or feed_dict keys are of an inappropriate type.
  • ValueError: If fetches or feed_dict keys are invalid or refer to a Tensor that doesn't exist.

分析 

由以上内容可知,基于keras定义的模型对应的数据类型通常为tf.Module,tf.layers.Layer或tf.models.Model,并非session允许的数据类型。

因此,如要基于session运行模型,我们需要从keras中获取session要求的数据;

经分析发现,keras内部的call函数在定义完整的计算逻辑后会返回模型的output,该output对应的数据类型为tf.Tensor;故我们将该output作为session.run的fetches参数。

example:

Class KerasModel(tf.models.Model)

def __init__(self):
    self._build()
def _build(self):
    # 定义model的核心层
    self.layera = tf.layer.A
    self.layerb = tf.layer.B

def call(input,training):
    # 定义各层的计算逻辑
    x = inputs
    x = self.layera(x)
    x = self.layerb(x)
    return x

==============run the KerasModel========
input_shape = [1,2,3]
inputs = tf.placeholder(shape=input_shape,dtype=y)
inputs_data = np.random.rand(*input_shape)
model = KerasModel()
outputs = model.call(inputs,False)
with tf.Session(tf.ConfigProto()) as sess:
    sess.run(outputs,inputs:input_data)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值