4-14 图的基本操作
程序 :
import numpy as np
import tensorflow as tf
# 1 创建图的方法
c = tf.constant(0.0)
g = tf.Graph()
with g.as_default():
c1 = tf.constant(0.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)
# 2. 获取tensor
print(c1.name)
t = g.get_tensor_by_name(name="Const:0")
print(t)
# 3 获取op
a = tf.constant([[1.0, 2.0]])
b = tf.constant([[1.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")
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)
# 5
tt3 = g.as_graph_element(c1)
print(tt3)
print("________________________\n")
结果:
<tensorflow.python.framework.ops.Graph object at 0x000000000ACE8748>
<tensorflow.python.framework.ops.Graph object at 0x000000000ACE8748>
<tensorflow.python.framework.ops.Graph object at 0x0000000003A03B70>
<tensorflow.python.framework.ops.Graph object at 0x0000000003A03B70>
<tensorflow.python.framework.ops.Graph object at 0x000000000AEA1978>
Const:0
Tensor("Const:0", shape=(), dtype=float32)
eop: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)
________________________