我正在尝试使用 KNearest Neighbors 解决多类机器学习问题,并使用 Matplotlib.pyplot 的 imshow 为我数据中所有 10 个类的预测绘制混淆矩阵。有些类在数据中的出现次数比其他类多得多,最多 3000 次,而其他类可能只有 50 次,因此我将其标准化以仅显示百分比。图表旁边有一个颜色条,如果没有标准化,范围从 1 到 3000,这是有道理的。然而,在标准化之后,范围一直保持到 3000。我正在使用 Scikit Learn 自己在他们的网站上提供的绘图功能 here .是否有明显的遗漏,或者是否有额外的步骤来缩小颜色条值范围?
代码
virdis = plt.cm.viridis
blues = plt.cm.Blues
autumn = plt.cm.autumn
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
bounds=[0, .1, .2, .3, .4, .5, .6, .7, .8, .9, 1]
plt.colorbar(boundaries=bounds)
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')
cm = np.around(cm, decimals=3)
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 i == 9 and j == 9 else "black")
plt.ylabel('True label')
plt.xlabel('Predicted label')
knn = KNeighborsClassifier()
knn.fit(X_train, y_train)
knn_score = knn.score(X_test, y_test)
knn_fold_score = model_selection.cross_val_score(knn, X_test, y_test, cv=10).mean()
predictions = knn.predict(X_test)
c_matrix = confusion_matrix(y_test, predictions)
# Plot normalized confusion matrix
plt.figure()
plot_confusion_matrix(c_matrix, classes=country_names, normalize=True,
title='Normalized confusion matrix')
plt.show()
请您参考如下方法:
正如您所理解的,颜色条及其范围保持并且应该与情节保持一致,即 plt.imshow。 Scikit Learn 示例和您的示例都在执行或决定是否执行规范化之前绘制矩阵。因此,这两个图及其相关的颜色条看起来完全一样。如果您在绘图之前处理归一化,即移动以下 block :
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
cm = np.around(cm, decimals=3)
在 plt.imshow(cm, interpolation='nearest', cmap=cmap) 前面,标准化绘图的颜色条将在 0 到 1 之间变化。再次提醒您,(颜色)情节本身也会改变。我认为仅将颜色栏的文本标签更改为 0 到 1 的范围而不更改颜色栏本身及其关联的绘图并不是一个好主意。
