TensorFlow 会默认建立一个图, 还可以手动建立图图的三个基本操作:
# 传入一个对象返回一个张量或是一个OP
tf.Graph() # 建立图 tf.get_default_graph() # 获取图 tf.reset_default_graph() # 重置图
下面是一个简单的例子:
import tensorflow as tf
# 默认图中的常量
default_const = tf.constant(1.)# 新建一个图
new_graph = tf.Graph() with new_graph.as_default(): # 在新建的图中设置常量 in_new_graph = tf.constant(2., name='in_new_graph') print(in_new_graph.graph) # 新建图 print(new_graph) print(default_const.graph) # 默认的图# 获得默认的图
default_graph = tf.get_default_graph() print(default_graph)# 重置图
tf.reset_default_graph() new_graph1 = tf.get_default_graph() print(new_graph1)# 上面测试代码的输出结果
# <tensorflow.python.framework.ops.Graph object at 0x112ce3eb8> # <tensorflow.python.framework.ops.Graph object at 0x112ce3eb8> # <tensorflow.python.framework.ops.Graph object at 0x103bfb048> # <tensorflow.python.framework.ops.Graph object at 0x103bfb048> # <tensorflow.python.framework.ops.Graph object at 0x112ce3fd0>
从上面的结果中可以看出,默认图,新建图,和重置后的图的id是不同的。
# 获取张量 get_tensor_by_name()
print(in_new_graph.name) tensor = new_graph.get_tensor_by_name('in_new_graph:0') print(tensor)# 获取操作节点 get_operation_by_name()
op_ = new_graph.get_operation_by_name('in_new_graph') print(op_)
# name: "in_new_graph" # op: "Const" # attr { # key: "dtype" # value { # type: DT_FLOAT # } # } # attr { # key: "value" # value { # tensor { # dtype: DT_FLOAT # tensor_shape { # } # float_val: 2.0 # } # } # }# 获取元素列表 get_operations()
ng = new_graph.get_operations() print(ng) # [<tf.Operation 'in_new_graph' type=Const>]# 获取对象 tf.Graph.as_graph_element(obj, allow_tensor=True, allow_operation=True)
# 传入一个对象返回一个张量或是一个OP
age = new_graph.as_graph_element(in_new_graph) print(age) # Tensor("in_new_graph:0", shape=(), dtype=float32)