"人工智障 机器瞎学 数据掩埋" 入门笔记

Tensorflow之计算图的使用

2018-01-28  本文已影响3人  HeoLis

Tensorflow是一个通过计算图的形式来表述计算的编程系统。Tensorflow中的每一个计算都是计算图上的一个节点,而节点之间的边描述了计算之间的依赖关系吗。可通过Tensorboard可视化这一关系。

计算图

一下代码演示了如何在不同计算图上定义和使用变量,以及指定运行计算的设备

import tensorflow as tf

g1 = tf.Graph()
with g1.as_default():
    # 在计算图g1中定义变量“v”,并设置初始值0.
    v = tf.get_variable("v",initializer=tf.zeros([1]))

g2 = tf.Graph()
with g2.as_default():
    # 在计算图g2中定义变量“v”,并设置初始值为1。
    v = tf.get_variable("v",initializer=tf.ones([1]))

# 在计算图g1中读取变量“v”的取值。
with tf.Session(graph=g1) as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    with tf.variable_scope("",reuse=True):
        # 在计算图g1中,变量“v”的取值应该为0,所以下面这行会输出[0.]。
        print(sess.run(tf.get_variable("v")))

# 在计算图g2中读取变量“v”的取值
with tf.Session(graph=g2) as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    with tf.variable_scope("",reuse=True):
        # 在计算图g2中,变量“v”的取值应该为1,所以下面这行会输出[1.]。
        print(sess.run(tf.get_variable("v")))


### 使用 tf.Graph.device 函数指定运行计算
g = tf.Graph()
with tf.Session(graph=g) as sess:
    a = tf.constant([1.0,2.0],name="a")
    b = tf.constant([2.0,3.0],name="b")
    with g.device('/cpu:0'):
        result = a + b
        init = tf.global_variables_initializer()
        sess.run(init)
        print(sess.run(result))
        print(result)

运行后依次会输出:

[ 0.]
[ 1.]
[ 3.  5.]
Tensor("add:0", shape=(2,), dtype=float32, device=/device:CPU:0)

如果没有特殊指定,运算会自动加载到默认的计算图中

上一篇 下一篇

猜你喜欢

热点阅读