ConfusionMatrixDisplay#

classsklearn.metrics.ConfusionMatrixDisplay(confusion_matrix,*,display_labels=None)[source]#

Confusion Matrix visualization.

It is recommended to usefrom_estimator orfrom_predictions tocreate aConfusionMatrixDisplay. All parameters are stored asattributes.

For general information regardingscikit-learn visualization tools, seetheVisualization Guide.For guidance on interpreting these plots, refer to theModel Evaluation Guide.

Parameters:
confusion_matrixndarray of shape (n_classes, n_classes)

Confusion matrix.

display_labelsndarray of shape (n_classes,), default=None

Display labels for plot. If None, display labels are set from 0 ton_classes-1.

Attributes:
im_matplotlib AxesImage

Image representing the confusion matrix.

text_ndarray of shape (n_classes, n_classes), dtype=matplotlib Text, or None

Array of matplotlib axes.None ifinclude_values is false.

ax_matplotlib Axes

Axes with confusion matrix.

figure_matplotlib Figure

Figure containing the confusion matrix.

See also

confusion_matrix

Compute Confusion Matrix to evaluate the accuracy of a classification.

ConfusionMatrixDisplay.from_estimator

Plot the confusion matrix given an estimator, the data, and the label.

ConfusionMatrixDisplay.from_predictions

Plot the confusion matrix given the true and predicted labels.

Examples

>>>importmatplotlib.pyplotasplt>>>fromsklearn.datasetsimportmake_classification>>>fromsklearn.metricsimportconfusion_matrix,ConfusionMatrixDisplay>>>fromsklearn.model_selectionimporttrain_test_split>>>fromsklearn.svmimportSVC>>>X,y=make_classification(random_state=0)>>>X_train,X_test,y_train,y_test=train_test_split(X,y,...random_state=0)>>>clf=SVC(random_state=0)>>>clf.fit(X_train,y_train)SVC(random_state=0)>>>predictions=clf.predict(X_test)>>>cm=confusion_matrix(y_test,predictions,labels=clf.classes_)>>>disp=ConfusionMatrixDisplay(confusion_matrix=cm,...display_labels=clf.classes_)>>>disp.plot()<...>>>>plt.show()
../../_images/sklearn-metrics-ConfusionMatrixDisplay-1.png
classmethodfrom_estimator(estimator,X,y,*,labels=None,sample_weight=None,normalize=None,display_labels=None,include_values=True,xticks_rotation='horizontal',values_format=None,cmap='viridis',ax=None,colorbar=True,im_kw=None,text_kw=None)[source]#

Plot Confusion Matrix given an estimator and some data.

For general information regardingscikit-learn visualization tools, seetheVisualization Guide.For guidance on interpreting these plots, refer to theModel Evaluation Guide.

Added in version 1.0.

Parameters:
estimatorestimator instance

Fitted classifier or a fittedPipelinein which the last estimator is a classifier.

X{array-like, sparse matrix} of shape (n_samples, n_features)

Input values.

yarray-like of shape (n_samples,)

Target values.

labelsarray-like of shape (n_classes,), default=None

List of labels to index the confusion matrix. This may be used toreorder or select a subset of labels. IfNone is given, thosethat appear at least once iny_true ory_pred are used insorted order.

sample_weightarray-like of shape (n_samples,), default=None

Sample weights.

normalize{‘true’, ‘pred’, ‘all’}, default=None

Either to normalize the counts display in the matrix:

  • if'true', the confusion matrix is normalized over the trueconditions (e.g. rows);

  • if'pred', the confusion matrix is normalized over thepredicted conditions (e.g. columns);

  • if'all', the confusion matrix is normalized by the totalnumber of samples;

  • ifNone (default), the confusion matrix will not be normalized.

display_labelsarray-like of shape (n_classes,), default=None

Target names used for plotting. By default,labels will be usedif it is defined, otherwise the unique labels ofy_true andy_pred will be used.

include_valuesbool, default=True

Includes values in confusion matrix.

xticks_rotation{‘vertical’, ‘horizontal’} or float, default=’horizontal’

Rotation of xtick labels.

values_formatstr, default=None

Format specification for values in confusion matrix. IfNone, theformat specification is ‘d’ or ‘.2g’ whichever is shorter.

cmapstr or matplotlib Colormap, default=’viridis’

Colormap recognized by matplotlib.

axmatplotlib Axes, default=None

Axes object to plot on. IfNone, a new figure and axes iscreated.

colorbarbool, default=True

Whether or not to add a colorbar to the plot.

im_kwdict, default=None

Dict with keywords passed tomatplotlib.pyplot.imshow call.

text_kwdict, default=None

Dict with keywords passed tomatplotlib.pyplot.text call.

Added in version 1.2.

Returns:
displayConfusionMatrixDisplay

See also

ConfusionMatrixDisplay.from_predictions

Plot the confusion matrix given the true and predicted labels.

Examples

>>>importmatplotlib.pyplotasplt>>>fromsklearn.datasetsimportmake_classification>>>fromsklearn.metricsimportConfusionMatrixDisplay>>>fromsklearn.model_selectionimporttrain_test_split>>>fromsklearn.svmimportSVC>>>X,y=make_classification(random_state=0)>>>X_train,X_test,y_train,y_test=train_test_split(...X,y,random_state=0)>>>clf=SVC(random_state=0)>>>clf.fit(X_train,y_train)SVC(random_state=0)>>>ConfusionMatrixDisplay.from_estimator(...clf,X_test,y_test)<...>>>>plt.show()
../../_images/sklearn-metrics-ConfusionMatrixDisplay-2_00_00.png

For a detailed example of using a confusion matrix to evaluate aSupport Vector Classifier, please seeConfusion matrix

classmethodfrom_predictions(y_true,y_pred,*,labels=None,sample_weight=None,normalize=None,display_labels=None,include_values=True,xticks_rotation='horizontal',values_format=None,cmap='viridis',ax=None,colorbar=True,im_kw=None,text_kw=None)[source]#

Plot Confusion Matrix given true and predicted labels.

For general information regardingscikit-learn visualization tools, seetheVisualization Guide.For guidance on interpreting these plots, refer to theModel Evaluation Guide.

Added in version 1.0.

Parameters:
y_truearray-like of shape (n_samples,)

True labels.

y_predarray-like of shape (n_samples,)

The predicted labels given by the methodpredict of anclassifier.

labelsarray-like of shape (n_classes,), default=None

List of labels to index the confusion matrix. This may be used toreorder or select a subset of labels. IfNone is given, thosethat appear at least once iny_true ory_pred are used insorted order.

sample_weightarray-like of shape (n_samples,), default=None

Sample weights.

normalize{‘true’, ‘pred’, ‘all’}, default=None

Either to normalize the counts display in the matrix:

  • if'true', the confusion matrix is normalized over the trueconditions (e.g. rows);

  • if'pred', the confusion matrix is normalized over thepredicted conditions (e.g. columns);

  • if'all', the confusion matrix is normalized by the totalnumber of samples;

  • ifNone (default), the confusion matrix will not be normalized.

display_labelsarray-like of shape (n_classes,), default=None

Target names used for plotting. By default,labels will be usedif it is defined, otherwise the unique labels ofy_true andy_pred will be used.

include_valuesbool, default=True

Includes values in confusion matrix.

xticks_rotation{‘vertical’, ‘horizontal’} or float, default=’horizontal’

Rotation of xtick labels.

values_formatstr, default=None

Format specification for values in confusion matrix. IfNone, theformat specification is ‘d’ or ‘.2g’ whichever is shorter.

cmapstr or matplotlib Colormap, default=’viridis’

Colormap recognized by matplotlib.

axmatplotlib Axes, default=None

Axes object to plot on. IfNone, a new figure and axes iscreated.

colorbarbool, default=True

Whether or not to add a colorbar to the plot.

im_kwdict, default=None

Dict with keywords passed tomatplotlib.pyplot.imshow call.

text_kwdict, default=None

Dict with keywords passed tomatplotlib.pyplot.text call.

Added in version 1.2.

Returns:
displayConfusionMatrixDisplay

See also

ConfusionMatrixDisplay.from_estimator

Plot the confusion matrix given an estimator, the data, and the label.

Examples

>>>importmatplotlib.pyplotasplt>>>fromsklearn.datasetsimportmake_classification>>>fromsklearn.metricsimportConfusionMatrixDisplay>>>fromsklearn.model_selectionimporttrain_test_split>>>fromsklearn.svmimportSVC>>>X,y=make_classification(random_state=0)>>>X_train,X_test,y_train,y_test=train_test_split(...X,y,random_state=0)>>>clf=SVC(random_state=0)>>>clf.fit(X_train,y_train)SVC(random_state=0)>>>y_pred=clf.predict(X_test)>>>ConfusionMatrixDisplay.from_predictions(...y_test,y_pred)<...>>>>plt.show()
../../_images/sklearn-metrics-ConfusionMatrixDisplay-3.png
plot(*,include_values=True,cmap='viridis',xticks_rotation='horizontal',values_format=None,ax=None,colorbar=True,im_kw=None,text_kw=None)[source]#

Plot visualization.

Parameters:
include_valuesbool, default=True

Includes values in confusion matrix.

cmapstr or matplotlib Colormap, default=’viridis’

Colormap recognized by matplotlib.

xticks_rotation{‘vertical’, ‘horizontal’} or float, default=’horizontal’

Rotation of xtick labels.

values_formatstr, default=None

Format specification for values in confusion matrix. IfNone,the format specification is ‘d’ or ‘.2g’ whichever is shorter.

axmatplotlib axes, default=None

Axes object to plot on. IfNone, a new figure and axes iscreated.

colorbarbool, default=True

Whether or not to add a colorbar to the plot.

im_kwdict, default=None

Dict with keywords passed tomatplotlib.pyplot.imshow call.

text_kwdict, default=None

Dict with keywords passed tomatplotlib.pyplot.text call.

Added in version 1.2.

Returns:
displayConfusionMatrixDisplay

Returns aConfusionMatrixDisplay instancethat contains all the information to plot the confusion matrix.

Gallery examples#

Faces recognition example using eigenfaces and SVMs

Faces recognition example using eigenfaces and SVMs

Recognizing hand-written digits

Recognizing hand-written digits

Visualizations with Display Objects

Visualizations with Display Objects

Confusion matrix

Confusion matrix

Release Highlights for scikit-learn 1.5

Release Highlights for scikit-learn 1.5

Label Propagation digits: Demonstrating performance

Label Propagation digits: Demonstrating performance

Classification of text documents using sparse features

Classification of text documents using sparse features