考虑以下示例:
import numpy as np
import tensorflow as tf
labels = np.zeros([2, 3, 3, 1])
labels[0,0,1,0], labels[0,0,2,0] = 1, 1
predictions = np.zeros([2, 3, 3, 1])
predictions[0,0,0,0], predictions[0,0,1,0], predictions[0,0,2,0] = 1, 1, 1
我将数据写入tf.constant
:
tf_labels = tf.constant(labels, dtype=tf.float32)
tf_predictions = tf.constant(predictions, dtype=tf.float32)
现在奇怪的行为:
tf_metric, tf_metric_update = tf.metrics.mean_iou(tf_labels,
tf_predictions, 2,
name="my_metric")
with tf.control_dependencies([tf_metric_update]):
tf_metric = tf.identity(tf_metric)
with tf.Session() as session:
session.run(tf.local_variables_initializer())
for _ in range(20):
# Calculate the score
score = session.run(tf_metric)
print(score)
结果包含一些奇怪的数字
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.724359
0.8020834
0.7386364
0.8020834
0.69627035
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
现在,我删除tf.control_dependencies
块并显式运行tf_metric_update
操作。
tf_metric, tf_metric_update = tf.metrics.mean_iou(tf_labels,
tf_predictions, 2,
name="my_metric")
with tf.Session() as session:
session.run(tf.local_variables_initializer())
for _ in range(20):
session.run(tf_metric_update)
# Calculate the score
score = session.run(tf_metric)
print(score)
现在一切都可以正常运行
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
0.8020834
我以错误的方式使用tf.control_dependencies
吗?