1. 创建图
在 tensorflow 中, 一个程序默认是建立一个图的, 除了系统自动建立图以外, 我们还可以手动建立图, 并做一些其他的操作.
下面我们使用 tf.Graph 函数建立图, 使用 tf.get_default_graph 函数来获取图, 使用 reset_default_graph 对图进行重置.
- import tensorflow as tf
- import numpy as np
- c = tf.constant(1.5)
- g = tf.Graph()
- with g.as_default():
- c1 = tf.constant(2.0)
- print(c1.graph)
- print(g)
- print(c.graph)
- g2 = tf.get_default_graph()
- print(g2)
- tf.reset_default_graph()
- g3 = tf.get_default_graph()
- print(g3)
上述的代码运行结果如下所示:
根据上述的运行结果, c 是在刚开始的默认图中建立的, 所以打印的结果就是 13376A1FE10, 和 g2 获取的默认图的值是一样的, 然后使用 tf.Graph 建立了一个新的图, 并添加了变量 c1, 最后又对图进行了重置, 替代了原来的默认图.
在使用 reset_default_graph() 函数的时候, 要保证当前图中资源都已经全部进行了释放, 否则将会报错.
2. 获取张量
我们可以在图中通过名字得到其对应的元素, 比如获取图中的变量和 OP 等元素.
- import tensorflow as tf
- import numpy as np
- g = tf.Graph()
- with g.as_default():
- c1 = tf.constant(2.5, name='c1_constant')
- c2 = tf.Variable(1.5, dtype=tf.float32, name='c2_constant')
- add = tf.multiply(c1, c2, name='op_add')
- c_1 = g.get_tensor_by_name(name='c1_constant:0')
- c_2 = g.get_tensor_by_name(name='c2_constant:0')
- c_3 = g.get_tensor_by_name(name='op_add:0')
- print(c_1)
- print(c_2)
- print(c_3)
在进行测试时, 我们为元素添加了变量名, 在设置变量名的时候, 设置好的名字会自动添加后面的: 0 字符. 一般我们可以将名字打印出来, 在将打印好的名字进行回填.
3. 获取节点操作
获取节点操作 OP 的方法和获取张量的方法非常类似, 使用 get_operation_by_name. 下面是运行实例:
- import tensorflow as tf
- import numpy as np
- a = tf.constant([[1.0, 2.0]])
- b = tf.constant([[1.0], [3.0]])
- tensor_1 = tf.matmul(a, b, name='matmul_1')
- with tf.Session() as sess:
- sess.run(tf.global_variables_initializer())
- t1 = tf.get_default_graph().get_operation_by_name(name='matmul_1')
- t2 = tf.get_default_graph().get_tensor_by_name(name='matmul_1:0')
- print(t1)
- print('t1:', sess.run(t1))
- print('t2:', sess.run(t2))
在上述的代码中, 定义了一个 OP 操作, 命名为 matmul_1, 在运行时我们将 op 打印出来, 在使用名字后面加上: 0 我们就能得到 OP 运算的结果的 tensor, 注意这两者的区别.
我们还可以通过 get_opreations 函数获取图中的所有信息. 此外, 我们还可以使用 tf.Grapg.as_graph_element 函数将传入的对象返回为张量或者 op. 该函数具有验证和转换功能.
来源: https://www.cnblogs.com/baby-lily/p/10960054.html