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 addtrainingandmaskif the layer need them.*argsand**kwargsis 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
Operationand evaluate everyTensorinfetches, substituting the values infeed_dictfor the corresponding input values.The
fetchesargument 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_handleop. The corresponding fetched value will be a numpy ndarray containing the handle of that tensor.- A
stringwhich is the name of a tensor or operation in the graph.The value returned by
run()has the same shape as thefetchesargument, where the leaves are replaced by the corresponding values returned by TensorFlow.# session.run第一个参数必须对应特定的数据类型。
The optional
feed_dictargument allows the caller to override the value of tensors in the graph. Each key infeed_dictcan 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
dtypeas 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 orSparseTensors, 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_dictmust be convertible to a numpy array of the dtype of the corresponding key.The optional
optionsargument expects a [RunOptions] proto. The options allow controlling the behavior of this particular step (e.g. turning tracing on).The optional
run_metadataargument 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
fetchesis a single graph element, or a list of values iffetchesis a list, or a dictionary with the same keys asfetchesif that is a dictionary (described above). Order in whichfetchesoperations are evaluated inside the call is undefined.Raises:
RuntimeError: If thisSessionis in an invalid state (e.g. has been closed).TypeError: Iffetchesorfeed_dictkeys are of an inappropriate type.ValueError: Iffetchesorfeed_dictkeys are invalid or refer to aTensorthat 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内容请搜索靠谱客的其他文章。
发表评论 取消回复