一 实例描述
本例演示了使用3种方式来建立图,并演示获取图相关内容的操作。
一个TensorFlow程序默认是建立一个图,除了系统自动建图外,还可以手动建立,并做一些其他操作。
二 代码
import numpy as np import tensorflow as tf # 1 创建图的方法 ''' 下面代码演示了使用tf.Graph函数建立图,使用tf.get_default_graph函数获得图,以及使用reset_default_graph来重置图的过程 ''' c = tf.constant(0.0) g = tf.Graph() with g.as_default(): c1 = tf.constant(0.0) print(c1.graph) #<tensorflow.python.framework.ops.Graph object at 0x000001DAEDB25908> 通过.graph获得所在图 print(g) #<tensorflow.python.framework.ops.Graph object at 0x000001DAEDB25908> tf.Graph建立的图 print(c.graph) #<tensorflow.python.framework.ops.Graph object at 0x000001DAEDB25160>,刚开始默认图中建立的 g2 = tf.get_default_graph() print(g2) #<tensorflow.python.framework.ops.Graph object at 0x000001DAEDB25160>,获得刚开始默认图 tf.reset_default_graph() g3 = tf.get_default_graph() print(g3) #<tensorflow.python.framework.ops.Graph object at 0x000001DAEDB25668> 重新建立以张图替换原来默认图 # 2. 获取tensor ''' 在图里面可以通过名字得到对应的元素,例如get_tensor_by_name可以获得图里面的张量 ''' print(c1.name) #Const:0 c1是在子图g中建立的 t = g.get_tensor_by_name(name = "Const:0") #访问图中的张量,将c1的名字放到get_tensor_by_name里面反向得到其张量 print(t) #Tensor("Const:0", shape=(), dtype=float32) # 3 获取op ''' 获取节点操作op的方法和获取张量的方法非常类似,使用的方法是get_operation_by_name ''' a = tf.constant([[1.0, 2.0]]) b = tf.constant([[1.0], [3.0]]) tensor1 = tf.matmul(a, b, name='exampleop') #不是OP,而是张量。OP其实是描述张量中的运算关系 print(tensor1.name,tensor1) #将张量的名字和张量打印出来 test = g3.get_tensor_by_name("exampleop:0") #test和tensor1是一样的 print(test) print(tensor1.op.name) testop = g3.get_operation_by_name("exampleop") print(testop) with tf.Session() as sess: test = sess.run(test) print(test) test = tf.get_default_graph().get_tensor_by_name("exampleop:0") print (test) #4 获取所有列表 #返回图中的操作节点列表 tt2 = g.get_operations() print(tt2) #[<tf.Operation 'Const' type=Const>] 由于g中只有一个常量,所有打印一条信息 #5 获取对象 ''' 使用as_graph_element函数,即传入一个对象,返回一个张量或一个OP。该函数具有验证和转换功能,在多线程方面会偶尔用到。 ''' tt3 = g.as_graph_element(c1) print(tt3) print("________________________\n")
三 运行结果
<tensorflow.python.framework.ops.Graph object at 0x000001DAEDB25908>
<tensorflow.python.framework.ops.Graph object at 0x000001DAEDB25908>
<tensorflow.python.framework.ops.Graph object at 0x000001DAEDB25160>
<tensorflow.python.framework.ops.Graph object at 0x000001DAEDB25160>
<tensorflow.python.framework.ops.Graph object at 0x000001DAEDB25668>
Const:0
Tensor("Const:0", shape=(), dtype=float32)
exampleop:0 Tensor("exampleop:0", shape=(1, 1), dtype=float32)
Tensor("exampleop:0", shape=(1, 1), dtype=float32)
exampleop
name: "exampleop"
op: "MatMul"
input: "Const"
input: "Const_1"
attr {
key: "T"
value {
type: DT_FLOAT
}
}
attr {
key: "transpose_a"
value {
b: false
}
}
attr {
key: "transpose_b"
value {
b: false
}
}
[[ 7.]]
Tensor("exampleop:0", shape=(1, 1), dtype=float32)
[<tf.Operation 'Const' type=Const>]
Tensor("Const:0", shape=(), dtype=float32)
四 说明
本例体现了建立图、获取张量、获取节点操作、获取元素列表、获取对象等操作