Tensorflow计算模型 —— 计算图

来源:互联网 发布:centos没有桌面文件夹 编辑:程序博客网 时间:2024/05/22 05:03

Tensorflow计算模型 —— 计算图

Tensorflow是一个通过计算图的形式来表述计算的编程系统,计算图也叫数据流图,可以把计算图看做是一种有向图,Tensorflow中的每一个计算都是计算图上的一个节点,而节点之间的边描述了计算之间的依赖关系。

计算图的使用

在tensorflow程序中,系统会维护一个默认的计算图,通过tf.get_default_graph()函数可以获取当前默认的计算图,为了向默认的计算图中添加一个操作,我们只需要简单的调用一个函数:


c = tf.constant(3.0)
assert c.graph == tf.get_default_graph()
ule
词除了使用默认的计算图,Tensorflow支持通过tf.Graph()函数来生成新的计算图,不同计算图的张量和运算都不会共享,使用tf.Graph.as_default()覆盖当前的默认图。

g = tf.Graph()with g.as_default():    c = tf.constant(3.0)    assert c.graph is g
#coding:utf-8import tensorflow as tfg1 = tf.Graph()with g1.as_default():    # 在图g1中定义初始变量c, 并设置初始值为0    v = tf.get_variable("v", shape=[1], initializer = tf.zeros_initializer(dtype=tf.float32))g2 = tf.Graph()with g2.as_default():    # 在图g1中定义初始变量c, 并设置初始值为1    v = tf.get_variable("v", shape=[1], initializer = tf.ones_initializer(dtype=tf.float32))with tf.Session(graph=g1) as sess:    sess.run(tf.global_variables_initializer())    with tf.variable_scope('', reuse=True):        # 输出值为0        print sess.run(tf.get_variable("v"))with tf.Session(graph=g2) as sess:    sess.run(tf.global_variables_initializer())    with tf.variable_scope('', reuse=True):       # 输出值为1       print sess.run(tf.get_variable('v'))

上面的代码产生了两个计算图,当运行不同的计算图时,变量v的值是不一样的。同时,计算图Graph通过tf.Graph.device函数来制定运行计算图的设备, 下图定义的程序可以将加法计算跑在GPU上

g = tf.Graph()# 指定计算运行的设备with g.device('/gpu:0'):    result = a + b

在一个计算图中,可以通过collection来管理不同类别的资源,一个计算图Graph实例支持任意数量的 name定义的collection, 当构建一个计算图时,collections可以存储一组相关的对象。例如:tf.Variables使用一个clooection(named tf.GraphKeys.GLOBAL_VARIABLES)存储所有的变量,当构建计算图的时候。可以通过tf.add_to_collection()函数将资源加入一个collection中,然后通过tf.get_collection获取一个集合里面的所有资源

计算图的方法

add_to_collection(name, value)
使用给定的名称往collection添加值。
as_default()
返回一个使此Graph成为默认的计算图。
get_collection(name, scope=None)
使用给定的名称返回collection中的值列表。

关于更多的计算图的方法,见https://www.tensorflow.org/versions/master/api_docs/python/tf/Graph#name_scope

0 0
原创粉丝点击