Tensorflow中Graph的概念

一、英文文档深入解读

class tf.Graph

A TensorFlow computation, represented as a dataflow graph.

Graph实际上是一个由数据流图表示的计算过程

Graph contains a set of Operation objects, which represent units of computation; and Tensorobjects, which represent the units of data that flow between operations.

Graph表示了数据流图中的操作流水,而Tensor表示的是其中流动的数据

底下这几段讲述了系统默认的Graph获取方式,以及他的“线程不安全”特性。

A default Graph is always registered, and accessible by calling tf.get_default_graph(). To add an operation to the default graph, simply call one of the functions that defines a new Operation:

c = tf.constant(4.0)
assert c.graph is tf.get_default_graph()

Another typical usage involves the Graph.as_default() context manager, which overrides the current default graph for the lifetime of the context:

g = tf.Graph()
with g.as_default():
  # Define operations and tensors in `g`.
  c = tf.constant(30.0)
  assert c.graph is g

Important note: This class is not thread-safe for graph construction. All operations should be created from a single thread, or external synchronization must be provided. Unless otherwise specified, all methods are not thread-safe.


二、关于Tensorflow的图计算过程

我们通过下面的代码来看一下Tensorflow的图计算过程:

import tensorflow as tf
a = tf.constant(1)
b = tf.constant(2)
c = tf.constant(3)
d = tf.constant(4)
add1 = tf.add(a, b)
mul1 = tf.mul(b, c)
add2 = tf.add(c, d)
output = tf.add(add1, mul1)
with tf.Session() as sess:
    print sess.run(output)

# result: 9

上面的代码构成的Graph如下图所示,

 

当Session加载Graph的时候,Graph里面的计算节点都不会被触发执行。当运行sess.run(output)的时候,会沿着指定的Tensor output来进图路径往回触发相对应的节点进行计算(图中红色线表示的那部分)。当我们需要output的值时,触发Operation tf.add(add1, mul1)被执行,而该节点则需要Tensor add1和Tensor mul1的值,则往回触发Operation tf.add(a, b)和Operation tf.mul(b, c)。以此类推。

所以在计算Graph时,并不一定是Graph中的所有节点都被计算了,而是指定的计算节点或者该节点的输出结果被需要时。




  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
TensorFlow是一个开源的人工智能框架,由Google开发和维护。它支持各种机器学习算法,包括神经网络、深度学习等,并提供了一系列的API和工具,使得开发者能够方便地构建和训练自己的模型。 TensorFlow的基本概念包括: 1. Tensor:一个TensorFlow的Tensor是一个多维数组。可以将它看作是一个n维的矩阵,其n可以是任意整数。 2. GraphTensorFlowGraph是指一组Tensor的计算图。它定义了Tensor之间的运算关系,以及数据在这些运算的流动方式。 3. Session:TensorFlow的Session是指一个计算图的执行环境。通过Session可以对计算图进行计算和优化。 4. Variable:TensorFlow的Variable是指一个可变的Tensor。它可以在计算图保持一个可持久化的状态,并且在不同的计算图之间共享。 TensorFlow的使用方法包括: 1. 安装TensorFlow库。可以从TensorFlow官网下载适合你的操作系统和版本的TensorFlow安装包,并按照安装说明进行安装。 2. 构建计算图。在TensorFlow,可以通过一系列的API来定义计算图,包括Tensor和运算符等。 3. 创建Session。在计算图构建好之后,可以创建一个Session对象,并对计算图进行计算和优化。 4. 运行计算图。可以通过Session的run方法来运行计算图,并获取计算结果。 5. 保存和加载模型。可以使用TensorFlow提供的API来保存和加载训练好的模型,以方便后续的使用和部署。 需要注意的是,在使用TensorFlow之前,需要先了解TensorFlow的基本概念和使用方法,并进行相应的安装和配置。此外,TensorFlow的使用需要一定的编程基础和数学基础,建议先学习相关知识再进行实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值