tensorflow图的基本操作

TensorFlow 会默认建立一个图, 还可以手动建立图图的三个基本操作: 
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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值