【问题标题】:How to change the ticks in a confusion matrix?如何更改混淆矩阵中的刻度?
【发布时间】:2017-03-07 21:00:21
【问题描述】:

我正在使用混淆矩阵(图 A)

如何让我的ticks 从 1 到 3 而不是从 0 到 2 开始?

我尝试在 tick_marks 中添加 +1。但它不起作用(图B)

检查我的代码:

import itertools

cm = confusion_matrix(y_test, y_pred)
np.set_printoptions(precision=2)
print('Confusion matrix, without normalization')
print(cm)
plt.figure()
plot_confusion_matrix(cm)


def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Oranges):
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(iris.target_names)) + 1

    plt.xticks(tick_marks, rotation=45)
    plt.yticks(tick_marks)

    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')

图A:

图B

【问题讨论】:

    标签: python-3.x numpy matplotlib scikit-learn confusion-matrix


    【解决方案1】:

    您应该获得pltaxis 并更改xtick_labels(如果您打算这样做):

    import itertools
    import numpy as np
    import matplotlib.pyplot as plt
    
    from sklearn import svm, datasets
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import confusion_matrix
    
    # import some data to play with
    iris = datasets.load_iris()
    X = iris.data
    y = iris.target
    class_names = iris.target_names
    
    # Split the data into a training set and a test set
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
    
    # Run classifier, using a model that is too regularized (C too low) to see
    # the impact on the results
    classifier = svm.SVC(kernel='linear', C=0.01)
    y_pred = classifier.fit(X_train, y_train).predict(X_test)
    
    
    def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Oranges):
        plt.imshow(cm, interpolation='nearest', cmap=cmap)
        plt.title(title)
        plt.colorbar()
        tick_marks = np.arange(len(iris.target_names))
        plt.xticks(tick_marks, rotation=45)
        ax = plt.gca()
        ax.set_xticklabels((ax.get_xticks() +1).astype(str))
        plt.yticks(tick_marks)
    
        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')
    
    cm = confusion_matrix(y_test, y_pred)
    np.set_printoptions(precision=2)
    print('Confusion matrix, without normalization')
    print(cm)
    fig, ax = plt.subplots()
    plot_confusion_matrix(cm)
    
    plt.show()
    

    结果:

    【讨论】:

    • @Aizzaac 将 ax.set_xticklabels((ax.get_xticks() +1).astype(str)) 更改为 ax.set_xticklabels([lab+'s' for lab in (ax.get_xticks() +1).astype(str)])
    • @Aizzaac 如果答案解决了您的问题,请通过单击该答案的复选标记(如here)接受它,以便其他人注意到它会在第一眼看到。
    【解决方案2】:

    我遇到了类似的问题:当我想为我的类使用自定义标签时,正方形框超出范围或标签被偏移,如您在此处显示的那样。

    如果您有多个标签 (>7),那么首先您需要使用 plticker.MultipleLocator 将滴答频率显式设置为一个。然后您只需设置 x 和 y 刻度标签而不提及刻度(不设置 xticks 和 yticks 很重要。如果这样做,imshow/matshow 部分会在顶部被切掉。)在 plot_confusion_matrix 函数。

    import matplotlib.ticker as plticker
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(cm,cmap=cmap)
    fig.colorbar(cax)
    loc = plticker.MultipleLocator(base=1.0)
    ax.xaxis.set_major_locator(loc)
    ax.yaxis.set_major_locator(loc)
    ax.set_yticklabels(['']+iris.target_names)
    ax.set_xticklabels(['']+iris.target_names)
    

    【讨论】:

      猜你喜欢
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 2014-07-09
      • 2019-09-28
      • 2019-11-24
      • 1970-01-01
      相关资源
      最近更新 更多