创建操作后添加控件依赖?

Add control dependency after operations are created?

是否可以在创建两个操作之后在它们之间创建控制依赖关系?我意识到使用 tf.control_dependencies 可以让一个操作在执行之前等待另一个操作,但是必须在 tf.control_dependencies 上下文中创建依赖操作。我想先独立构建两个ops,然后再添加依赖。

这可能是一个令人失望的答案,但是在创建 TensorFlow Operation 之后不可能将控件依赖项(或任何其他输入)添加到它。张量和运算一旦创建就不可变

一种可能性是克隆应该运行第二个的操作,在适当的控制依赖上下文中。假设您有两个 Operation 对象,op_firstop_second,并且您希望 op_first 到 运行 在 op_second 之前:

def first_before_second(op_first, op_second):
    """Sequence `op_first` before `op_second`.

    Given two operations, returns a pair of operations with the same behavior
    except that the first returned operation will execute before the second
    returned operation.
    """
    with tf.control_dependencies([op_first]):
        g = tf.get_default_graph()
        op_second_clone = g.create_op(op_second.type,
                                      [in_t for in_t in op_second.inputs],
                                      [out_t.dtype for out_t in op_second.outputs],
                                      attrs=op_second.node_def.attr,
                                      op_def=op_second.op_def)

    return op_first, op_second_clone

类似的修改也可以处理 Tensor 对象,但这留作 reader.

的练习。

虽然通常不可能,但您可以稍微修改现有的 op 以加强依赖性。例如,您可以将零添加到张量: def first_before_second_num(op_first, op_second): with tf.control_dependencies([op_first]): op_second += 0 return op_second

如果您的 NoOptrain_step 相似,那么您可能希望将其与另一个 NoOp 分组: def first_before_second_noop(op_first, op_second): with tf.control_dependencies([op_first]): op_second tf.group(op_second, tf.no_op()) return op_second