And*_*bis 21 python tensorflow
TensorFlow图通常从输入到输出逐步构建,然后执行.查看Python代码,操作的输入列表是不可变的,这表明不应修改输入.这是否意味着无法更新/修改现有图表?
mrr*_*rry 22
TensorFlow tf.Graph类是仅附加数据结构,这意味着您可以在执行图形的一部分后将节点添加到图形中,但不能删除或修改现有节点.由于TensorFlow在您调用时仅执行必要的子图Session.run(),因此在图中具有冗余节点没有执行时间成本(尽管它们将继续消耗内存).
要删除图表中的所有节点,您可以使用新图表创建会话:
with tf.Graph().as_default(): # Create a new graph, and make it the default.
with tf.Session() as sess: # `sess` will use the new, currently empty, graph.
# Build graph and execute nodes in here.
Run Code Online (Sandbox Code Playgroud)
zax*_*liu 10
是的,tf.Graph正如@mrry所说的那样构建了一种仅限附加的方式.
但有解决方法:
从概念上讲,您可以通过克隆现有图表来修改现有图表并执行所需的修改.从r1.1开始,Tensorflow提供了一个名为的模块,它将tf.contrib.graph_editor上述想法实现为一组方便的功能.
除了@zaxily 和@mrry 所说的之外,我还想提供一个示例,说明如何实际修改图表。简而言之:
编码:
import tensorflow
import copy
import tensorflow.contrib.graph_editor as ge
from copy import deepcopy
a = tf.constant(1)
b = tf.constant(2)
c = a+b
def modify(t):
# illustrate operation copy&modification
new_t = deepcopy(t.op.node_def)
new_t.name = new_t.name+"_but_awesome"
new_t = tf.Operation(new_t, tf.get_default_graph())
# we got a tensor, let's return a tensor
return new_t.outputs[0]
def update_existing(target, updated):
# illustrate how to use new op
related_ops = ge.get_backward_walk_ops(target, stop_at_ts=updated.keys(), inclusive=True)
new_ops, mapping = ge.copy_with_input_replacements(related_ops, updated)
new_op = mapping._transformed_ops[target.op]
return new_op.outputs[0]
new_a = modify(a)
new_b = modify(b)
injection = new_a+39 # illustrate how to add another op to the graph
new_c = update_existing(c, {a:injection, b:new_b})
with tf.Session():
print(c.eval()) # -> 3
print(new_c.eval()) # -> 42
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9299 次 |
| 最近记录: |