我试图创建TensorFlow混淆矩阵,但我得到一个
类型错误:图像数据无法被转换成浮动。
图像被准确预测,但现在我想用matplotlib显示混淆矩阵。我试着转换为以np.array(),但错误还是一样。
我下面从scikit学习混淆矩阵的官方文档。 https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.tight_layout()
if result[0][0]>0.85:
predictions.append(result[0][0])
elif result[0][1]>0.85:
predictions.append(result[0][1])
elif result[0][2]>0.85:
predictions.append(result[0][2])
elif result[0][3]>0.85:
predictions.append(result[0][3])
elif result[0][4]>0.85:
predictions.append(result[0][4])
elif result[0][5]>0.85:
predictions.append(result[0][5])
class_names = ['Up', 'Down', 'Left', 'Right', 'Forward', 'Backward']
# label_list contains the filename e.g. hand1.jpg, hand2.jpg....
# Compute confusion matrix
cnf_matrix = tf.confusion_matrix(label_list,predictions,num_classes=6)
np.set_printoptions(precision=2)
# Plot non-normalized confusion matrix
plt.figure()
# ERROR HERE
plot_confusion_matrix(cnf_matrix, classes=class_names,title='Confusion matrix, without normalization')
# Plot normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=class_names, normalize=True,title='Normalized confusion matrix')
plt.show()
我还没有在我的电脑进行了测试。您的描述,我(错误的行等),有点暧昧,但你的代码的主要区别和你链接的文档confusion_matrix()
。只要尝试去用的confusion_matrix()
sckit学习,而不是tensorflow的confusion_matrix()
(在链路,前者使用)。在我看来,这是你可以去最简单的方法。
编辑:请您预测是这样的:
for i in range(6):
if result[0][i] > 0.85:
predictions.append(i)
continue
然后,你的预测可能会不连续的。在这里你的预测应该是整数,因为你是预测类的标签。