建立图
概述:可以在一个tensorflow中手动建立其他的图,也可以根据图中的变量获得当前的图。下面代码演示了tf.Graph函数建立图,使用tf.get_default_graph函数获得图,以及使用tf.reset_default_graph的过程来重置图。
实例:
import numpy as np
import tensorflow as tf
c = tf.constant(0.0)
print("c.graph =",c.graph)
g = tf.Graph()
with g.as_default():
c1 = tf.constant(0.0)
print("c1.graph =",c1.graph)
print("g =",g)
#获取默认图
g2 = tf.get_default_graph()
print("g2 =",g2)
#重置默认图
tf.reset_default_graph()
g3 = tf.get_default_graph()
print("g3 =",g3)
结果:
c.graph = <tensorflow.python.framework.ops.Graph object at 0x00000189ED63AE48>
c1.graph = <tensorflow.python.framework.ops.Graph object at 0x00000189FFF44F60>
g = <tensorflow.python.framework.ops.Graph object at 0x00000189FFF44F60>
g2 = <tensorflow.python.framework.ops.Graph object at 0x00000189ED63AE48>
g3 = <tensorflow.python.framework.ops.Graph object at 0x00000189FFF44B70>
分析:
观察结果我们知道,c和g2的图是一样的,c1和g是一样的,而g3由于重置了图,相当于新建了图,所以不一样。
获取张量
在图里面可以通过名字得到其对应的元素,例如,通过get_tensor_by_name可以获得图里面对应名字的张量。
print(c1.name)
t = g.get_tensor_by_name(name="Const:0")
print(t)
结果:
Const:0
Tensor(“Const:0”, shape=(), dtype=float32)
获取节点操作
API:get_operation_by_name
a = tf.constant([[1.0,2.0]])
b = tf.constant([[2.0],[3.0]])
#矩阵乘法运算
tensor1 = tf.matmul(a,b,name="exampleop")
print(tensor1.name,tensor1)
test = g3.get_tensor_by_name("exampleop:0")
print(test)
print(tensor1.op.name)
testop = g3.get_operation_by_name("exampleop")
with tf.Session() as sess:
print(sess.run(test))
结果:
exampleop:0 Tensor(“exampleop:0”, shape=(1, 1), dtype=float32)
Tensor(“exampleop:0”, shape=(1, 1), dtype=float32)
exampleop
[[8.]]
分析:
tensor1 = tf.matmul(a,b,name=“exampleop”)并不是OP,而是张量。OP其实是描述张量中的运算关系,是通过访问张量的属性找到的。
获取元素列表
API:get_operations
print(g3.get_operations())
结果:
[<tf.Operation ‘const1’ type=Const>,
<tf.Operation ‘const2’ type=Const>,
<tf.Operation ‘exampleop’ type=MatMul>]