概述
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), usingadd_weight()
.__call__()
will automatically build the layer (if it has not been built yet) by callingbuild()
.- # 主要定义模型的构成(各层及其参数)
call(self, inputs, *args, **kwargs)
: Called in__call__
after making surebuild()
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 incall()
are:
training
(boolean, whether the call is in inference mode or training mode). See more details in the layer/model subclassing guidemask
(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 iscall(self, inputs)
, and user could optionally addtraining
andmask
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 everyTensor
infetches
, substituting the values infeed_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:
- A tf.Operation. The corresponding fetched value will be
None
.- A tf.Tensor. The corresponding fetched value will be a numpy ndarray containing the value of that tensor.
- A tf.SparseTensor. The corresponding fetched value will be a tf.compat.v1.SparseTensorValue containing the value of that sparse tensor.
- A
get_tensor_handle
op. The corresponding fetched value will be a numpy ndarray containing the handle of that tensor.- A
string
which is the name of a tensor or operation in the graph.The value returned by
run()
has the same shape as thefetches
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 infeed_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
Tensor
s orSparseTensor
s, 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 inoptions
, 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 bufferrun_metadata
: A [RunMetadata
] protocol bufferReturns:
Either a single value if
fetches
is a single graph element, or a list of values iffetches
is a list, or a dictionary with the same keys asfetches
if that is a dictionary (described above). Order in whichfetches
operations are evaluated inside the call is undefined.Raises:
RuntimeError
: If thisSession
is in an invalid state (e.g. has been closed).TypeError
: Iffetches
orfeed_dict
keys are of an inappropriate type.ValueError
: Iffetches
orfeed_dict
keys are invalid or refer to aTensor
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)
最后
以上就是粗暴大象为你收集整理的keras 和 tensorflow的结合keras内部的核心函数分析 的全部内容,希望文章能够帮你解决keras 和 tensorflow的结合keras内部的核心函数分析 所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复