python - control_dependencies 不符合预期
问题描述
我希望 tensorflow 在f(...)
- 获取数据[索引]
- 缓存值
- 返回数据[索引]
但tf.control_dependencies
没有做我想做的事。
如何修复控制依赖?
结果:
cache_ 0.0
x_ 2.0
AssertionError
测试:
import tensorflow as tf
import numpy as np
def f(a, cache):
assign_op = tf.assign(cache, a)
with tf.control_dependencies([assign_op]):
return a
def main():
dtype = np.float32
data = tf.range(5, dtype=dtype)
cache = tf.Variable(0, dtype=dtype)
x = f(data[2], cache)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
x_ = sess.run(x)
cache_ = sess.run(cache)
print("cache_", cache_)
print("x_", x_)
assert np.allclose(cache_, x_)
main()
解决方案
问题在于return a
Python 代码。您没有在with
块中创建任何 TensorFlow 操作。您可以使用它tf.identity
来创建一个操作,以确保首先执行a
读取的时间。assign_op
这是更新的代码:
def f(a, cache):
assign_op = tf.assign(cache, a)
with tf.control_dependencies([assign_op]):
return tf.identity(a)
推荐阅读
- email - 在另一个通讯组中有一个通讯组来重定向电子邮件
- amazon-web-services - 指定镜像时如何升级kubernetes版本
- regex - 读取文件并获取 perl 中特定单词之后的所有单词
- java - 有没有办法在Java中用RSA同时解密一个大的加密文件?
- tfs - TFS 2018 中的日志管理
- tomcat - MATA-INFcontext.xml 被 tomcat/conf/contex.xml 覆盖
- perl - 无论偶数或奇数出现,捕获独特的部分
- javascript - 垫表中的复选框问题-Angular7
- reactjs - 无法从 React 中的子组件更改父级的状态
- wordpress - 自定义菜单栏 wordpress 以构建一页功能