簡體   English   中英

從混淆矩陣中顯示錯誤分類的數字

[英]Display misclassified digits from confusion matrix

我寫了一個 function 來找到我的 model 的混淆矩陣:

NN_model = KNeighborsClassifier(n_neighbors=1)
NN_model.fit(mini_train_data, mini_train_labels)
# Create the confusion matrix for the dev data
confusion = confusion_matrix(dev_labels, NN_model.predict(dev_data))
print(confusion)

我得到以下輸出

但是我在顯示經常與其他數字混淆的 5 位以上的圖像時遇到了麻煩。 但是當我嘗試下面的代碼時,我沒有得到預期的結果。

index = 0
misclassifiedIndexes = []
for label, predict in zip(dev_labels, predictions):
     if label != predict: 
        misclassifiedIndexes.append(index)
        index +=1

plt.figure(figsize=(20,4))
for plotIndex, badIndex in enumerate(misclassifiedIndexes[0:5]):
    plt.subplot(1, 5, plotIndex + 1)
    plt.imshow(np.reshape(dev_data[badIndex], (28,28)), cmap=plt.cm.gray)
    plt.title('Predict: {}, Actual: {}'.format(predictions[badIndex], dev_labels[badIndex]), fontsize = 15)

這是我得到的,但理想情況下我想顯示錯誤分類的數字

你能看看我的代碼有什么問題嗎? 謝謝!

因此,我不能對您的代碼提出問題。 因此,我在這里提供了一個可重現的代碼。

您可以使用np.where上的 np.where 比較預測值和實際值。

試試這個例子:

from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4)

NN_model = KNeighborsClassifier(n_neighbors=1)
NN_model.fit(X_train, y_train)
# Create the confusion matrix for the dev data
from sklearn.metrics import confusion_matrix
predictions = NN_model.predict(X_test)
confusion = confusion_matrix(y_test, predictions)

import matplotlib.pyplot as plt
misclassifiedIndexes = np.where(y_test!=predictions)[0]


fig, ax = plt.subplots(4, 3,figsize=(15,8))
ax = ax.ravel()
for i, badIndex in enumerate(misclassifiedIndexes):
    ax[i].imshow(np.reshape(X_test[badIndex], (8, 8)), cmap=plt.cm.gray)
    ax[i].set_title(f'Predict: {predictions[badIndex]}, '
                    f'Actual: {y_test[badIndex]}', fontsize = 10)
    ax[i].set(frame_on=False)
    ax[i].axis('off')
plt.box(False)
plt.axis('off')

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM