我正在尝试将tf.confusion_matrix
与tf.assign_add
一起使用,以便在每个全局步骤中更新一个混淆矩阵。
y_true = tf.placeholder(tf.int16,shape=[None,])
y_pred = tf.placeholder(tf.int16,shape=[None,])
cm = tf.confusion_matrix(labels=y_true,predictions=y_pred)
cm_inc = tf.assign_add(cm, cm) #error
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(5):
feed_dict={y_true:[0,1,0,0],y_pred:[1,1,0,0]}
print(sess.run(cm_inc,feed_dict=feed_dict))
但是我得到
AttributeError: 'Tensor' object has no attribute 'assign_add'
有没有一种方法可以访问混淆矩阵对象的实际矩阵,即cm
来完成这项工作。
答案 0 :(得分:1)
您得到
AttributeError:“ Tensor”对象没有属性“ assign_add”
因为assign_add
仅对变量有意义(请参见my other answer)
如您所知,应该创建一个空变量(所有条目均为零),并将assign_add
的结果import tensorflow as tf
NUM_CLASSES = 4
y_true = tf.placeholder(tf.int16, shape=[None, ])
y_pred = tf.placeholder(tf.int16, shape=[None, ])
cm_diff = tf.confusion_matrix(labels=y_true, predictions=y_pred, num_classes=NUM_CLASSES)
cm = tf.get_variable('confusion_matrix', [NUM_CLASSES, NUM_CLASSES], dtype=tf.int32, initializer=tf.zeros_initializer())
cm_inc = tf.assign_add(cm, cm_diff)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(5):
feed_dict = {y_true: [0, 1, 0, 0], y_pred: [1, 1, 0, 0]}
print(sess.run(cm_inc, feed_dict=feed_dict))
赋给该变量,例如
f