【问题标题】:Add control dependency after operations are created?创建操作后添加控件依赖项?
【发布时间】:2016-02-04 16:32:11
【问题描述】:

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

【问题讨论】:

  • 你能解释一下为什么你需要这样做吗? (我想知道是否有另一种方法可以在没有事后依赖设置的情况下完成你想要做的事情。)
  • 纯粹是审美。如果我稍后必须创建一个操作,我的代码流程会更加混乱,但该选项似乎是两害相权取其轻。
  • 唷,很好。 (正如下面 mrry 所指出的,我能想到的唯一方法包括,例如,写出图表,修改 pbtxt,然后将其读回,我很高兴不必去那里。: )

标签: tensorflow


【解决方案1】:

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

一种可能性是在适当的控制依赖关系上下文中克隆应该运行的操作。假设您有两个 Operation 对象,op_firstop_second,并且您希望 op_firstop_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 对象,但这留给读者作为练习。

【讨论】:

    【解决方案2】:

    虽然通常不可能,但您可以稍微修改现有的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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 2019-05-19
      • 2019-10-15
      • 2017-05-29
      • 1970-01-01
      • 2017-03-27
      • 1970-01-01
      相关资源
      最近更新 更多