参考文章:TensorFlow-sess.run()

当我们构建完图(可能是我们pre_process后生成的图片?NoNoNo,它只是指tensorflow框架的一种设计理念——计算流图)后,需要在一个会话中启动图,启动的第一步是创建一个Session对象。

为了取回(Fetch)操作的输出内容, 可以在使用 Session 对象的 run()调用执行图时,传入一些 tensor, 这些 tensor 会帮助你取回结果。

在python语言中,返回的tensor是numpy ndarray对象。

在执行sess.run()时,tensorflow并不是计算了整个图,只是计算了与想要fetch 的值相关的部分。

from tensorflow\python\client\session.py

  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, byrunning 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 arbitrarilynested list, tuple, namedtuple, dict, or OrderedDict containing graphelements 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 thevalue 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 anumpy 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 byTensorFlow.run()返回的值与fetches参数具有相同的形状,其中叶子被TensorFlow返回的相应值替换。Example:```pythona = 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 overridethe value of tensors in the graph. Each key in `feed_dict` can beone of the following types:可选的feed_dict参数允许调用者覆盖图中的张量值。 feed_dict中的每个键可以是以下类型之一:* If the key is a `tf.Tensor`, thevalue may be a Python scalar, string, list, or numpy ndarraythat can be converted to the same `dtype` as thattensor. Additionally, if the key is a`tf.placeholder`, the shape ofthe 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 valueshould be a nested tuple with the same structure that maps to theircorresponding 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 dtypeof the corresponding key.feed_dict中的每个值都必须可转换为对应键dtype的numpy数组。The optional `options` argument expects a [`RunOptions`] proto. The optionsallow controlling the behavior of this particular step (e.g. turning tracingon).可选的`options`参数需要一个[`RunOptions`]原型。 这些选项允许控制此特定步骤的行为(例如,打开跟踪)。The optional `run_metadata` argument expects a [`RunMetadata`] proto. Whenappropriate, the non-Tensor output of this step will be collected there. Forexample, when users turn on tracing in `options`, the profiled info will becollected 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 graphelements (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, ora list of values if `fetches` is a list, or a dictionary with thesame keys as `fetches` if that is a dictionary (described above).Order in which `fetches` operations are evaluated inside the callis undefined.如果fetches是单个图形元素,则为单个值;如果fetches为列表,则为值列表;如果字典是具有与fetches相同键的字典,则为字典(如上所述)。 在调用内部评估“fetches”操作的顺序是不确定的。Raises:RuntimeError: If this `Session` is in an invalid state (e.g. has beenclosed).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 Nonerun_metadata_ptr = tf_session.TF_NewBuffer() if run_metadata else Nonetry: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())

python tensorflow tf.Session().run()函数(运行操作并评估“fetches”中的张量)相关推荐

  1. python tensorflow tf.session类

    @tf_export('Session') class Session(BaseSession):"""A class for running TensorFlow op ...

  2. 对比tensorflow查看打印输出张量Tensor的两种方法(急切执行tf.enable_eager_execution()和tf.Session.run())

    第一种:tf.enable_eager_execution() # -*- coding: utf-8 -*- """ @File : 111.py @Time : 20 ...

  3. 【深度学习框架】Tensorflow Session.run()函数的进一步理解

    在tensorflow中session.run()用来将数据传入计算图,计算并返回出给定变量/placeholder的结果. 在看论文代码的时候遇到一段复杂的feed_dict, 本文记录了对sess ...

  4. Tensorflow 学习二 tf.Session().run

    以下为tf.Session().run 说明,其接受的fetches参数可以有多种类型. def run(self, fetches, feed_dict=None, options=None, ru ...

  5. TensorFlow 学习(二)—— tf.Graph、tf.Session() 与 tf.Session().run()

    session: with tf.Session() as sess:/ tf.InteractiveSession() 初始化: tf.global_variables_initializer() ...

  6. tensorflow tf.enable_eager_execution()(立即执行操作,不添加到稍后在“ tf.Session”中执行的图)

    @tf_export("enable_eager_execution") def enable_eager_execution(config=None,device_policy= ...

  7. [转载] python 语言基础 - 字符串常用函数及操作

    参考链接: Python字符串| ljust rjust center python为字符串操作提供了很多常用的内建函数,让我们在操作字符串时能够更加简单方便. 下面以某个字符串为例来一一介绍一下 现 ...

  8. python tensorflow tf.layers.max_pooling2d() 2维输入(例如图像)的最大池化层

    from tensorflow\python\layers\pooling.py @tf_export('layers.max_pooling2d') def max_pooling2d(inputs ...

  9. python 调用class不指定函数_python调用另一个.py中的类或函数

    同一文件夹下的调用 1.调用函数 A.py文件如下: def add(x,y): print('和为:%d'%(x+y)) 在B.py文件中调用A.py的add函数如下: import A A.add ...

最新文章

  1. FPGA之道(53)状态机的模型
  2. 压缩文件拷到服务器损坏,压缩文件导致无法拷贝共享
  3. [hdu3549]Flow Problem(最大流模板题)
  4. org.activiti.engine.ActivitiOptimisticLockingException updated by another transaction concurrently
  5. C# 使用数据库SQLite
  6. 今天写了个商品采购入得存储过程,使用游标实现的,实现了多个商品库存的增加...
  7. Java分层架构的使用规则
  8. 时序图(Sequence Diagram)—UML图(六)
  9. pycharm添加python注释头_pycharm使用教程——py文件自动添加文件头注释
  10. java 万年历_改进java万年历,前几天看到别人写的java万年历,其中不足之处多多...
  11. linux下1060显卡驱动安装,ubuntu16.04 联想拯救者y7000笔记本电脑安装1060显卡驱动,及ubuntu16.04更新内核...
  12. 海康威视监控插件使用步骤
  13. .NET定位CPU使用率过高问题
  14. python俗称_python中文叫什么
  15. Python学习之绕圈圈题
  16. Csharp零基础:第一天学Csharp要会的基础知识
  17. SiI9136 -3 HDMI Transmitter 寄存器配置
  18. office中为何还要保留Access数据库? 【3500人回复】知乎
  19. 速卖通重点国家市场俄罗斯市场分析平台热销产品推荐
  20. 蓝桥杯试题 Python3

热门文章

  1. wps大纲栏显示在右边_miui12通知栏在哪
  2. 大神TP_英雄联盟:男枪瞬秒大龙,佐伊遍地TP,新版本BUG谁来监管?
  3. 【MM配置】评估和账户确定(Valuation Account Determination) - 1
  4. 合并报表调整、抵销分录的编制顺序
  5. 删除已使用过且无法删除的替代
  6. SAP发布S4/HANA 意义超过R3
  7. ABAP数据库—更新数据
  8. NBA部署SAP HANA内存数据库
  9. 企业实施SAP项目的得与失
  10. SAP业务测评之库存预留