首页 > 解决方案 > TensorFlow 的 tf.control_dependencies 无法按预期工作

问题描述

TensorFlow 版本为 1.14.0

我的示例代码如下:

import sys
import tensorflow as tf
from tensorflow.python import debug as tf_debug

sess = tf.Session()
m = tf.get_variable('m', initializer=tf.constant(1.0))
n = tf.get_variable('n', initializer=tf.constant(2.0))
# z = m*m + n*n                                                                                                                                                   
z = (m*n) ** 2

g1 = tf.gradients(z, [m, n])
r = 0.3 * g1[0]
attack_op = m.assign(m + r)
# attack_op = m.assign_add(r)                                                                                                                                     

with tf.control_dependencies([attack_op]):
    z_a = (m*n) ** 2
    g2 = tf.gradients(z_a, [m, n])

with tf.control_dependencies(g2):
    restore_op = m.assign(m - r)

with tf.control_dependencies([restore_op]):
    g3 = [tf.add_n(x) for x in zip(g1, g2)]
    g4 = [x / 2 for x in g3]

sess.run(tf.global_variables_initializer())

print('m: %g' % sess.run(m))
print('n: %g' % sess.run(n))
print(sess.run([g1, g2, g3, g4]))

以下代码的结果是:

m: 1
n: 2
[[8.0, 4.0], [27.2, 46.24], [35.2, 50.24], [8.0, 4.0]]

但是g4的手动计算结果是:[17.6, 25.12]

这个奇怪结果的原因是什么?谢谢

标签: tensorflowmachine-learning

解决方案


推荐阅读