plot_confusion_matrix#
- scikitplot.api.metrics.plot_confusion_matrix(y_true, y_pred, *, labels=None, true_labels=None, pred_labels=None, normalize=False, hide_zeros=False, hide_counts=False, title=None, title_fontsize='large', text_fontsize='medium', x_tick_rotation=0, cmap='Blues', show_colorbar=True, **kwargs)[source]#
Generates a confusion matrix plot from predictions and true labels.
The confusion matrix is a summary of prediction results that shows the counts of true and false positives and negatives for each class. This function also provides options for normalizing, hiding zero values, and customizing the plot appearance.
- Parameters:
- y_truearray-like, shape (n_samples,)
Ground truth (correct) target values.
- y_predarray-like, shape (n_samples,)
Estimated targets as returned by a classifier.
- labelsarray-like, shape (n_classes), optional
List of labels to index the matrix. This may be used to reorder or select a subset of labels. If None, labels appearing at least once in
y_true
ory_pred
are used in sorted order. (new in v0.2.5)- true_labelsarray-like, optional
The true labels to display. If None, all labels are used.
- pred_labelsarray-like, optional
The predicted labels to display. If None, all labels are used.
- normalizebool, optional, default=False
If True, normalizes the confusion matrix before plotting.
- hide_zerosbool, optional, default=False
If True, cells containing a value of zero are not plotted.
- hide_countsbool, optional, default=False
If True, counts are not overlaid on the plot.
- titlestring, optional
Title of the generated plot. Defaults to “Confusion Matrix” if
normalize
is True. Otherwise, defaults to “Normalized Confusion Matrix”.- title_fontsizestring or int, optional, default=”large”
Font size for the plot title. Use “small”, “medium”, “large”, or integer values.
- text_fontsizestring or int, optional, default=”medium”
Font size for text in the plot. Use “small”, “medium”, “large”, or integer values.
- x_tick_rotationint, optional, default=0
Rotates x-axis tick labels by the specified angle. Useful when labels overlap.
- cmapNone, str or matplotlib.colors.Colormap, optional, default=None
Colormap used for plotting. Options include ‘viridis’, ‘PiYG’, ‘plasma’, ‘inferno’, ‘nipy_spectral’, etc. See Matplotlib Colormap documentation for available choices.
https://matplotlib.org/stable/users/explain/colors/index.html
plt.colormaps()
plt.get_cmap() # None == ‘viridis’
- show_colorbarbool, optional, default=True
If False, the colorbar is not displayed.
Added in version 0.3.9.
- **kwargs: dict
Generic keyword arguments.
- Returns:
- axmatplotlib.axes.Axes
The axes on which the plot was drawn.
- Other Parameters:
- axmatplotlib.axes.Axes, optional, default=None
The axis to plot the figure on. If None is passed in the current axes will be used (or generated if required).
- figmatplotlib.pyplot.figure, optional, default: None
The figure to plot the Visualizer on. If None is passed in the current plot will be used (or generated if required).
- figsizetuple, optional, default=None
Width, height in inches. Tuple denoting figure size of the plot e.g. (12, 5)
- nrowsint, optional, default=1
Number of rows in the subplot grid.
- ncolsint, optional, default=1
Number of columns in the subplot grid.
- plot_stylestr, optional, default=None
Check available styles with “plt.style.available”. Examples include: [‘ggplot’, ‘seaborn’, ‘bmh’, ‘classic’, ‘dark_background’, ‘fivethirtyeight’, ‘grayscale’, ‘seaborn-bright’, ‘seaborn-colorblind’, ‘seaborn-dark’, ‘seaborn-dark-palette’, ‘tableau-colorblind10’, ‘fast’].
Added in version 0.4.0.
- show_figbool, default=True
Show the plot.
- save_figbool, default=False
Save the plot.
- save_fig_filenamestr, optional, default=’’
Specify the path and filetype to save the plot. If nothing specified, the plot will be saved as png inside
result_images
under to the current working directory. Defaults to plot image named to usedfunc.__name__
.- verbosebool, optional
If True, prints debugging information.
Notes
Ensure that
y_true
andy_pred
have the same shape and contain valid class labels. Thenormalize
parameter applies only to the confusion matrix plot. Adjustcmap
andx_tick_rotation
to customize the appearance of the plot. Theshow_colorbar
parameter controls whether a colorbar is displayed.Examples
>>> from sklearn.datasets import load_digits as data_10_classes >>> from sklearn.model_selection import train_test_split >>> from sklearn.naive_bayes import GaussianNB >>> import scikitplot as skplt >>> X, y = data_10_classes(return_X_y=True, as_frame=False) >>> X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.5, random_state=0) >>> model = GaussianNB() >>> model.fit(X_train, y_train) >>> y_val_pred = model.predict(X_val) >>> skplt.metrics.plot_confusion_matrix( >>> y_val, y_val_pred, >>> );
(
Source code
,png
)