python - keras 迁移学习中的混淆矩阵
问题描述
我打算在我的模型中绘制混淆矩阵,并使用基于深度学习模型的迁移学习概念。
混淆矩阵的代码
def plot_confusion_matrix(cm, classes, normalize=False,title='Confusion Matrix', cmap=plt.cm.Blues):
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)
if normalize:
cm=cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized Confusion Matrix")
else:
print("Confusion matrix, without normalization")
print(cm)
thresh = cm.max() / 2
for i, j in itertools.product(range(cm.shape[0]),range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i,j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True Label')
plt.xlabel('Predicted Label')
现在下面给出了test_labels和预测的形状,
test_labels.shape
(12,)
predictions.shape
(10,2)
上面的代码运行良好,但我在下面看到错误。所以请关注下面的代码,
cm = confusion_matrix(test_labels, predictions.argmax(axis=1))
这是错误,
ValueError Traceback (most recent call last)
<ipython-input-40-79fd4e2e074c> in <module>()
----> 1 cm = confusion_matrix(test_labels, predictions.argmax(axis=1))
2 frames
/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py in check_consistent_length(*arrays)
210 if len(uniques) > 1:
211 raise ValueError("Found input variables with inconsistent numbers of"
--> 212 " samples: %r" % [int(l) for l in lengths])
213
214
ValueError: Found input variables with inconsistent numbers of samples: [12, 10]
注意:这是价值错误,我对此感到困惑,我尝试越来越多,但我失败了。所以我需要帮助来解决这个错误。
解决方案
test_labels
正如错误所暗示的,对于和,您有不同的样本量predictions
。当您使用批次进行预测时可能会发生这种情况,这可能会导致最后几个样本的丢失。
一种可能性是,您可以使用:
cm = confusion_matrix(test_labels[:-2], predictions.argmax(axis=1))
这可能会解决形状不匹配问题(但它是基于最后两个样本在预测中丢失的假设)。
如果您可以共享用于预测的代码,我也许可以提供更有用的答案。
推荐阅读
- python - 将重复的行值转换为具有多列的单行
- c++ - 任何可能将多个名称添加到变量c ++中
- python - 为什么 Python 逻辑运算符不能使用这个 if 语句?
- java - 403 - 使用 Java 将数据写入 Google 电子表格的权限不足
- snowflake-cloud-data-platform - 在共享表上流式传输的替代方案
- xcode - 多个命令产生 Parse.bundle
- javascript - 使用 browserify + babel 的 gulp.task 语法问题
- typescript - 如何使用 Mocha Chai 单元测试来测试一个函数是否有两个字符串参数
- javascript - 如何摆脱 React.js 中的 NO ACCESS CONTROL ORIGIN 错误?
- html - 带字幕的 HTML 文本