如何向Tensorflow op添加控件依赖项 [英] How to add control dependency to Tensorflow op

查看:129
本文介绍了如何向Tensorflow op添加控件依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在运行summary之前先运行update_op.有时候我只是创建一个tf.summary,并且一切正常,但是有时候我想做更多花哨的事情,但仍然具有相同的控件依赖性.

I want update_op to run before I run summary. Sometimes I just create a tf.summary, and everything works just fine, but sometimes I want to do more fancy stuff, but still have the same control dependency.

无效的代码:

with tf.control_dependencies([update_op]):
    if condition:
        tf.summary.scalar('summary', summary)
    else:
        summary = summary

有效的错误hack

with tf.control_dependencies([update_op]):
    if condition:
        tf.summary.scalar('summary', summary)
    else:
        summary += 0

问题在于summary=summary不会创建新节点,因此控件依赖项将被忽略.

The problem is that summary=summary doesn't create a new node, so the control dependency is ignored.

我敢肯定,有什么更好的方法可以解决这个问题,有什么建议吗? :-)

I am sure that there is a way better way of going about this, any suggestions? :-)

推荐答案

我认为对此没有更优雅的解决方案,因为这是设计好的行为. tf.control_dependencies

I don't think there exists a more elegant solution to this, because this the designed behavior. tf.control_dependencies is a shortcut of tf.Graph.control_dependencies call using a default graph, and here's the quote from its documentation:

控件依赖项上下文仅适用于 在上下文中构造.只在其中使用op或张量 上下文不添加控件依赖项.下面的例子 说明了这一点:

N.B. The control dependencies context applies only to ops that are constructed within the context. Merely using an op or tensor in the context does not add a control dependency. The following example illustrates this point:

# WRONG
def my_func(pred, tensor):
  t = tf.matmul(tensor, tensor)
  with tf.control_dependencies([pred]):
    # The matmul op is created outside the context, so no control
    # dependency will be added.
    return t

# RIGHT
def my_func(pred, tensor):
  with tf.control_dependencies([pred]):
    # The matmul op is created in the context, so a control dependency
    # will be added.
    return tf.matmul(tensor, tensor)

因此,请按照注释中的建议使用tf.identity(summary).

So just use tf.identity(summary), as suggested in the comments.

这篇关于如何向Tensorflow op添加控件依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆