sklearn plot confusion matrix with labels

前端 未结 7 1216
生来不讨喜
生来不讨喜 2020-11-29 19:09

I want to plot a confusion matrix to visualize the classifer\'s performance, but it shows only the numbers of the labels, not the labels themselves:

from skl         


        
7条回答
  •  时光取名叫无心
    2020-11-29 19:31

    To add to @akilat90's update about sklearn.metrics.plot_confusion_matrix:

    You can use the ConfusionMatrixDisplay class within sklearn.metrics directly and bypass the need to pass a classifier to plot_confusion_matrix. It also has the display_labels argument, which allows you to specify the labels displayed in the plot as desired.

    The constructor for ConfusionMatrixDisplay doesn't provide a way to do much additional customization of the plot, but you can access the matplotlib axes obect via the ax_ attribute after calling its plot() method. I've added a second example showing this.

    I found it annoying to have to rerun a classifier over a large amount of data just to produce the plot with plot_confusion_matrix. I am producing other plots off the predicted data, so I don't want to waste my time re-predicting every time. This was an easy solution to that problem as well.

    Example:

    from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
    
    cm = confusion_matrix(y_true, y_preds, normalize='all')
    cmd = ConfusionMatrixDisplay(cm, display_labels=['business','health'])
    cmd.plot()
    

    Example using ax_:

    cm = confusion_matrix(y_true, y_preds, normalize='all')
    cmd = ConfusionMatrixDisplay(cm, display_labels=['business','health'])
    cmd.plot()
    cmd.ax_.set(xlabel='Predicted', ylabel='True')
    
    

提交回复
热议问题