【问题标题】:Display misclassified digits from confusion matrix从混淆矩阵中显示错误分类的数字
【发布时间】:2020-09-10 19:22:54
【问题描述】:

我写了一个函数来查找我的模型的混淆矩阵:

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)

您能看看我的代码出了什么问题吗?谢谢!

【问题讨论】:

    标签: python-3.x scikit-learn


    【解决方案1】:

    因此,我不能对您的代码提出问题。因此,我在这里提供了一个可重现的代码。

    您可以在预测值和实际值之间的布尔比较中使用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')
    

    【讨论】:

      猜你喜欢
      • 2020-03-09
      • 1970-01-01
      • 2020-07-25
      • 2019-01-05
      • 2017-01-13
      • 1970-01-01
      • 2019-10-15
      • 2015-09-18
      • 1970-01-01
      相关资源
      最近更新 更多