替换python for运算_python – Tensorflow:如何替换计算图中的节点?

TL; DR:如果你可以将两个计算定义为Python函数,那么你应该这样做。如果不能,TensorFlow中有更多高级功能可以序列化和导入图形,这使您可以组合来自不同来源的图形。

在TensorFlow中执行此操作的一种方法是将不相交的计算构建为单独的tf.Graph对象,然后使用Graph.as_graph_def()将它们转换为序列化协议缓冲区:

with tf.Graph().as_default() as g_1:

input = tf.placeholder(tf.float32, name="input")

y = f(input)

# NOTE: using identity to get a known name for the output tensor.

output = tf.identity(y, name="output")

gdef_1 = g_1.as_graph_def()

with tf.Graph().as_default() as g_2: # NOTE: g_2 not g_1

input = tf.placeholder(tf.float32, name="input")

z = g(input)

output = tf.identity(y, name="output")

gdef_2 = g_2.as_graph_def()

然后你可以使用tf.import_graph_def()将gdef_1和gdef_2组成第三个图:

with tf.Graph().as_default() as g_combined:

x = tf.placeholder(tf.float32, name="")

# Import gdef_1, which performs f(x).

# "input:0" and "output:0" are the names of tensors in gdef_1.

y, = tf.import_graph_def(gdef_1, input_map={"input:0": x},

return_elements=["output:0"])

# Import gdef_2, which performs g(y)

z, = tf.import_graph_def(gdef_2, input_map={"input:0": y},

return_elements=["output:0"]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值