使用sklearn绘制多标签混淆矩阵

8
我正在为多标签数据绘制混淆矩阵,其中标签看起来像这样: label1: 1, 0, 0, 0 label2: 0, 1, 0, 0 label3: 0, 0, 1, 0 label4: 0, 0, 0, 1
我能够成功地使用以下代码进行分类。 我只需要一些帮助来绘制混淆矩阵。请注意保留HTML标记。
    for i in range(4):
        y_train= y[:,i]
        print('Train subject %d, class %s' % (subject, cols[i]))
        lr.fit(X_train[::sample,:],y_train[::sample])
        pred[:,i] = lr.predict_proba(X_test)[:,1]

我使用下面的代码来打印混淆矩阵,但它总是返回一个2X2的矩阵。
prediction = lr.predict(X_train)

print(confusion_matrix(y_train, prediction))

我认为OP的意思是多类别而不是多标签。 - Foreever
7个回答

16
我找到了一个可以绘制使用sklearn生成的混淆矩阵的函数。
import numpy as np


def plot_confusion_matrix(cm,
                          target_names,
                          title='Confusion matrix',
                          cmap=None,
                          normalize=True):
    """
    given a sklearn confusion matrix (cm), make a nice plot

    Arguments
    ---------
    cm:           confusion matrix from sklearn.metrics.confusion_matrix

    target_names: given classification classes such as [0, 1, 2]
                  the class names, for example: ['high', 'medium', 'low']

    title:        the text to display at the top of the matrix

    cmap:         the gradient of the values displayed from matplotlib.pyplot.cm
                  see http://matplotlib.org/examples/color/colormaps_reference.html
                  plt.get_cmap('jet') or plt.cm.Blues

    normalize:    If False, plot the raw numbers
                  If True, plot the proportions

    Usage
    -----
    plot_confusion_matrix(cm           = cm,                  # confusion matrix created by
                                                              # sklearn.metrics.confusion_matrix
                          normalize    = True,                # show proportions
                          target_names = y_labels_vals,       # list of names of the classes
                          title        = best_estimator_name) # title of graph

    Citiation
    ---------
    http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html

    """
    import matplotlib.pyplot as plt
    import numpy as np
    import itertools

    accuracy = np.trace(cm) / float(np.sum(cm))
    misclass = 1 - accuracy

    if cmap is None:
        cmap = plt.get_cmap('Blues')

    plt.figure(figsize=(8, 6))
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()

    if target_names is not None:
        tick_marks = np.arange(len(target_names))
        plt.xticks(tick_marks, target_names, rotation=45)
        plt.yticks(tick_marks, target_names)

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]


    thresh = cm.max() / 1.5 if normalize else cm.max() / 2
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        if normalize:
            plt.text(j, i, "{:0.4f}".format(cm[i, j]),
                     horizontalalignment="center",
                     color="white" if cm[i, j] > thresh else "black")
        else:
            plt.text(j, i, "{:,}".format(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\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))
    plt.show()

它会看起来像这样 输入图片描述


1

This works the best for me :

from sklearn.metrics import multilabel_confusion_matrix
y_unique = y_test.unique()
mcm = multilabel_confusion_matrix(y_test, y_pred, labels = y_unique)
mcm

0
from sklearn.metrics import multilabel_confusion_matrix

mul_c = multilabel_confusion_matrix(
    test_Y,
    pred_k,
    labels=["benign", "dos","probe","r2l","u2r"])
mul_c

1
虽然这段代码可能提供了问题的解决方案,但最好添加上为什么/如何运作的上下文。这可以帮助未来的用户学习,并将这些知识应用到他们自己的代码中。当代码被解释时,您还可能会得到用户的积极反馈,例如点赞。 - borchvm

0

我用multilabel_confusion_matrix替换了confusion_matrix,但它报错说'multilabel_confusion_matrix'未定义。有解决这个问题的方法吗?这个问题在Github上似乎是开放的。 - tourist
正如我所说:“仍然是一个未解决的问题”。我只是给你提供了代码链接,以防你想尝试使用它。但它不在sklearn的代码中,这就是为什么它说它没有定义。如果你想使用它(我没有尝试过),你应该将multilabel_confusion_matrix中的所有代码包含在你自己的代码中,并调用该函数。要小心,因为这是一个2014年的开放性问题,它仍然是一个未解决的问题,这可能意味着它不是一个微不足道的问题。我只是给你一个指针,以防你想自己尝试并可能解决它。祝你好运! - Guiem Bosch

0

我在sklearn和seaborn库中找到了一个简单的解决方案。

from sklearn.metrics import confusion_matrix, classification_report
from matplotlib import pyplot as plt
import seaborn as sns

def plot_confusion_matrix(y_test,y_scores, classNames):
    y_test=np.argmax(y_test, axis=1)
    y_scores=np.argmax(y_scores, axis=1)
    classes = len(classNames)
    cm = confusion_matrix(y_test, y_scores)
    print("**** Confusion Matrix ****")
    print(cm)
    print("**** Classification Report ****")
    print(classification_report(y_test, y_scores, target_names=classNames))
    con = np.zeros((classes,classes))
    for x in range(classes):
        for y in range(classes):
            con[x,y] = cm[x,y]/np.sum(cm[x,:])

    plt.figure(figsize=(40,40))
    sns.set(font_scale=3.0) # for label size
    df = sns.heatmap(con, annot=True,fmt='.2', cmap='Blues',xticklabels= classNames , yticklabels= classNames)
    df.figure.savefig("image2.png")

classNames = ['A', 'B', 'C', 'D', 'E'] 
plot_confusion_matrix(y_test,y_scores, classNames) 
#y_test is your ground truth
#y_scores is your predicted probabilities

0

只需使用带有渐变着色的pandas

cm = confusion_matrix(y_true, y_pred)
cm = pd.DataFrame(data=cm, columns = np.unique(y_true), index = np.unique(y_true))
cm = (cm / cm.sum(axis = 1).values.reshape(-1,1))  # to fractions of 1
cm.style.background_gradient().format(precision=2)

现在,Pandas已经拥有了很好的表格格式和装饰选项。


0
另一种简单的方法是使用Seaborn的热力图,配合Pandas数据框。
confusion_matrix = metrics.confusion_matrix(y_true=y_test, 
                                            y_pred=y_test_pred)
mc_df = pd.DataFrame(confusion_matrix,
                     index=model.classes_, 
                     columns=columns)
sns.heatmap(mc_df, annot =True, fmt="d",cmap=plt.get_cmap('Blues'))
plt.title("Confusion Matrix")

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接