除了@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
0
TensorFlow图通常从输入到输出逐渐构建,然后执行。查看Python代码,操作的输入列表是不可变的,这表明不应修改输入。这是否意味着无法更新/修改现有图形?