参考文章:TensorFlow-sess.run()
当我们构建完图(可能是我们pre_process后生成的图片?NoNoNo,它只是指tensorflow框架的一种设计理念——计算流图)后,需要在一个会话中启动图,启动的第一步是创建一个Session对象。
为了取回(Fetch)操作的输出内容, 可以在使用 Session 对象的 run()调用执行图时,传入一些 tensor, 这些 tensor 会帮助你取回结果。
在python语言中,返回的tensor是numpy ndarray对象。
在执行sess.run()时,tensorflow并不是计算了整个图,只是计算了与想要fetch 的值相关的部分。
def run(self, fetches, feed_dict=None, options=None, run_metadata=None):
"""Runs operations and evaluates tensors in `fetches`.
运行操作并评估“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.
此方法运行TensorFlow计算的一个“步骤”,
方法是运行必要的图形片段以执行每个“操作”并评估“fetches”中的每个“ Tensor”,
然后将“ feed_dict”中的值替换为相应的输入值。
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:
“ fetches”参数可以是单个图形元素,
也可以是在其叶子处包含图形元素的任意嵌套的列表,元组,namedtuple,dict或OrderedDict。
图元素可以是以下类型之一:
* An `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.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.
*`tf.Operation`。
相应的获取值将为“无”。
*`tf.Tensor`。
相应的获取值将是一个numpy ndarray,其中包含张量的值。
*`tf.SparseTensor`。
相应的获取值将是tf.SparseTensorValue包含那个稀疏张量的值。
*`get_tensor_handle`操作。 相应的获取值将是包含该张量的句柄的numpy ndarray。
*字符串,是图中张量或操作的名称。
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.
run()返回的值与fetches参数具有相同的形状,其中叶子被TensorFlow返回的相应值替换。
Example:
```python
a = tf.constant([10, 20])
b = tf.constant([1.0, 2.0])
# 'fetches' can be a singleton “fetches”可以是单例
v = session.run(a)
# v is the numpy array [10, 20] v是numpy数组[10,20]
# 'fetches' can be a list. “fetches”可以是一个列表。
v = session.run([a, b])
# v is a Python list with 2 numpy arrays: the 1-D array [10, 20] and the
# 1-D array [1.0, 2.0]
# v是具有2个numpy数组的Python列表:一维数组[10,20]和一维数组[1.0,2.0]
# 'fetches' can be arbitrary lists, tuples, namedtuple, dicts:
# “fetches”可以是任意列表,元组,namedtuple,字典:
MyData = collections.namedtuple('MyData', ['a', 'b'])
v = session.run({'k1': MyData(a, b), 'k2': [b, a]})
# v is a dict with
# v['k1'] is a MyData namedtuple with 'a' (the numpy array [10, 20]) and
# 'b' (the numpy array [1.0, 2.0])
# v['k2'] is a list with the numpy array [1.0, 2.0] and the numpy array
# [10, 20].
```
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:
可选的feed_dict参数允许调用者覆盖图中的张量值。
feed_dict中的每个键可以是以下类型之一:
* 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.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.SparseTensorValue`.
* If the key is a nested tuple of `Tensor`s or `SparseTensor`s, the value
should be a nested tuple with the same structure that maps to their
corresponding values as above.
*如果键是`tf.Tensor`,则值可以是Python标量,字符串,列表或numpy ndarray,
可以将其转换为与该张量相同的`dtype`。
此外,如果键是`tf.placeholder`,则将检查值的形状与占位符的兼容性。
*如果密钥是`tf.SparseTensor`,则该值应为`tf.SparseTensorValue`。
*如果键是`Tensor`或`SparseTensor`的嵌套元组,
则该值应是具有与上述对应值对应的结构相同的嵌套元组。
Each value in `feed_dict` must be convertible to a numpy array of the dtype
of the corresponding key.
feed_dict中的每个值都必须可转换为对应键dtype的numpy数组。
The optional `options` argument expects a [`RunOptions`] proto. The options
allow controlling the behavior of this particular step (e.g. turning tracing
on).
可选的`options`参数需要一个[`RunOptions`]原型。
这些选项允许控制此特定步骤的行为(例如,打开跟踪)。
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.
可选的`run_metadata`参数需要一个[`RunMetadata`]原型。
适当时,将在此收集此步骤的非Tensor输出。
例如,当用户打开“选项”中的跟踪时,配置文件信息将收集到此参数中并传递回去。
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
一个[`RunOptions`]协议缓冲区
run_metadata: A [`RunMetadata`] protocol buffer
一个[`RunMetadata`]协议缓冲区
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.
如果fetches是单个图形元素,则为单个值;
如果fetches为列表,则为值列表;
如果字典是具有与fetches相同键的字典,则为字典(如上所述)。
在调用内部评估“fetches”操作的顺序是不确定的。
Raises:
RuntimeError: If this `Session` is in an invalid state (e.g. has been
closed).
RuntimeError:如果此“会话”处于无效状态(例如已关闭)。
TypeError: If `fetches` or `feed_dict` keys are of an inappropriate type.
TypeError:如果`fetches`或`feed_dict`键的类型不合适。
ValueError: If `fetches` or `feed_dict` keys are invalid or refer to a
`Tensor` that doesn't exist.
ValueError:如果“fetches”或“ feed_dict”键无效或引用了不存在的“张量”。
"""
options_ptr = tf_session.TF_NewBufferFromString(
compat.as_bytes(options.SerializeToString())) if options else None
run_metadata_ptr = tf_session.TF_NewBuffer() if run_metadata else None
try:
result = self._run(None, fetches, feed_dict, options_ptr,
run_metadata_ptr)
if run_metadata:
proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
run_metadata.ParseFromString(compat.as_bytes(proto_data))
finally:
if run_metadata_ptr:
tf_session.TF_DeleteBuffer(run_metadata_ptr)
if options:
tf_session.TF_DeleteBuffer(options_ptr)
return result
参考文章:对比tensorflow查看向量Tensor的两种方法(急切执行tf.enable_eager_execution()和tf.Session.run())