如何创建张量流分类的混淆矩阵

2024-03-22

我有 CNN 模型,它有 4 个输出节点,我正在尝试计算混淆矩阵,以便我可以知道各个类别的准确性。我能够计算总体准确性。 在链接中here https://stackoverflow.com/questions/35756710/how-do-i-create-confusion-matrix-of-predicted-and-ground-truth-labels-with-tenso,Igor Valantic 给出了一个可以计算混淆矩阵变量的函数。 它给了我一个错误correct_prediction = tf.nn.in_top_k(logits, labels, 1, name="correct_answers")错误是TypeError: DataType float32 for attr 'T' not in list of allowed values: int32, int64

我已经尝试在提到的函数内将 logits 类型转换为 int32def evaluation(logits, labels),它在计算时给出了另一个错误correct_prediction = ... as TypeError:Input 'predictions' of 'InTopK' Op has type int32 that does not match expected type of float32

如何计算这个混淆矩阵?

sess = tf.Session()
model = dimensions() # CNN input weights are calculated 
data_train, data_test, label_train, label_test =  load_data(files_test2,folder)
data_train, data_test, = reshapedata(data_train, data_test, model)
# input output placeholders
x  = tf.placeholder(tf.float32, [model.BATCH_SIZE, model.input_width,model.input_height,model.input_depth]) # last column = 1 
y_ = tf.placeholder(tf.float32, [model.BATCH_SIZE, model.No_Classes])
p_keep_conv = tf.placeholder("float")
# 
y  = mycnn(x,model, p_keep_conv)
# loss
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_))
# train step
train_step = tf.train.AdamOptimizer(1e-3).minimize(cost)
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
true_positives, false_positives, true_negatives, false_negatives = evaluation(y,y_)
lossfun = np.zeros(STEPS)
sess.run(tf.global_variables_initializer())

for i in range(STEPS):
    image_batch, label_batch = batchdata(data_train, label_train, model.BATCH_SIZE)
    epoch_loss = 0
    for j in range(model.BATCH_SIZE):
        sess.run(train_step, feed_dict={x: image_batch, y_: label_batch, p_keep_conv:1.0})
        c = sess.run( cost, feed_dict={x: image_batch, y_: label_batch, p_keep_conv: 1.0})
        epoch_loss += c
    lossfun[i] = epoch_loss
    print('Epoch',i,'completed out of',STEPS,'loss:',epoch_loss )
 TP,FP,TN,FN = sess.run([true_positives, false_positives, true_negatives,  false_negatives], feed_dict={x: image_batch, y_: label_batch, p_keep_conv:1.0})

这是我的代码片段


您可以简单地使用 Tensorflow 的混淆矩阵 https://www.tensorflow.org/api_docs/python/tf/confusion_matrix。我假设y是你的预测,你可能有也可能没有num_classes(这是可选的)

y_ = placeholder_for_labels # for eg: [1, 2, 4]
y = mycnn(...) # for eg: [2, 2, 4]

confusion = tf.confusion_matrix(labels=y_, predictions=y, num_classes=num_classes)

If you print(confusion), 你得到

  [[0 0 0 0 0]
   [0 0 1 0 0]
   [0 0 1 0 0]
   [0 0 0 0 0]
   [0 0 0 0 1]]

If print(confusion)不打印混淆矩阵,然后使用print(confusion.eval(session=sess)). Here sess是 TensorFlow 会话的名称。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何创建张量流分类的混淆矩阵 的相关文章

随机推荐