tensorflow graph(图)和session(会话)

以下运行环境: Ubuntu 18.04 LTS, tensorflow 1.8, python 3.6.5

tensorflow的tf.Graph是静态的图(对比eager execution),它表示模型的骨架,定义图不需要输入数据也不会执行运算

图的创建和使用

# 创建图
g_1 = tf.Graph()

# 在命名空间中构建图
with g_1.as_default():
    pass

一个图对应一个模型,尽量不要出现子图。训练模型时,整理代码的一种常用方法是使用一个图训练模型,然后使用另一个图对受训模型进行评估或推理。在通常情况下,推理图与训练图不同。

通过添加tf.Operationtf.Tensor来构建tf.Graph

a = tf.constant(42.0, name='const1')
b = tf.constant(2.0, name='cosnt2')
c = tf.add(a, b, name='add1')

tf.constant(42.0, name='const1')创建名为const1的Operation并将该const1的结果作为返回值返回,其中const1用于生成值为42的scalar Tensor

tf.add(a, b, name='add1')创建名为add1的Operation并返回其结果,其中add1接收2个Tensor作为输入

TensorFlow 使用tf.Session类来表示客户端程序(通常为 Python 程序,但也提供了其他语言的类似接口)与 C++ 运行时之间的连接。

通过session执行图

with tf.Session(graph=g_1) as sess:
    x = tf.placeholder(tf.float32, shape=[3])
    y = tf.square(x)
    fetch = [y]
    feed_dict = {
        x: [1.0, 2.0, 3.0]
    }
    print(sess.run(fetch, feed_dict))  # => "[1.0, 4.0, 9.0]"

使用tensorboard显示图

with tf.Session() as sess:
  writer = tf.summary.FileWriter("/tmp/log/...", sess.graph)

  # Perform your computation...
  for i in range(1000):
    sess.run(train_op)
    # ...

  writer.close()

在终端中输入tensorboard --logdir='path'以启动tensorboard

使用多个图进行编程

g_1 = tf.Graph()
with g_1.as_default():
  # Operations created in this scope will be added to `g_1`.
  c = tf.constant("Node in g_1")

  # Sessions created in this scope will run operations from `g_1`.
  sess_1 = tf.Session()

g_2 = tf.Graph()
with g_2.as_default():
  # Operations created in this scope will be added to `g_2`.
  d = tf.constant("Node in g_2")

# Alternatively, you can pass a graph when constructing a session
# `sess_2` will run operations from `g_2`.
sess_2 = tf.Session(graph=g_2)

# Get the default graph.
g = tf.get_default_graph()

猜你喜欢

转载自www.cnblogs.com/esoteric/p/9317628.html