To plot a confusion matrix with labels in scikit-learn (sklearn), you can use the plot_confusion_matrix function from the sklearn.metrics module. This function allows you to create a visually informative confusion matrix plot with class labels. Here's an example of how to use it:
import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix, plot_confusion_matrix from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression # Load a dataset (for demonstration purposes) data = load_iris() X, y = data.data, data.target # Split the dataset into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # Train a classifier (for demonstration purposes) clf = LogisticRegression() clf.fit(X_train, y_train) # Predict on the test set y_pred = clf.predict(X_test) # Calculate the confusion matrix cm = confusion_matrix(y_test, y_pred) # Define class labels (assuming they correspond to the target classes) class_names = data.target_names # Plot the confusion matrix with labels plt.figure(figsize=(8, 6)) plot_confusion_matrix(clf, X_test, y_test, display_labels=class_names, cmap=plt.cm.Blues, normalize=None) plt.title('Confusion Matrix') plt.show() In this example:
We load the Iris dataset, split it into training and testing sets, and train a classifier (Logistic Regression) for demonstration purposes. Replace this part with your actual dataset and classifier.
We calculate the confusion matrix using the confusion_matrix function.
We define the class labels using class_names, assuming they correspond to the target classes.
We create a plot for the confusion matrix using plot_confusion_matrix. The display_labels parameter is set to class_names to label the rows and columns with class names.
Finally, we display the confusion matrix plot using plt.show().
Make sure to replace the dataset and classifier in this example with your specific use case. The plot_confusion_matrix function provides a visual representation of the confusion matrix with class labels, which can be helpful for evaluating the performance of a classification model.
"Sklearn plot confusion matrix with labels example"
import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import seaborn as sns # Example labels and predictions y_true = ["cat", "ant", "cat", "cat", "ant", "bird"] y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"] # Calculate confusion matrix cm = confusion_matrix(y_true, y_pred) # Plot confusion matrix with labels plt.figure(figsize=(8,6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=np.unique(y_true), yticklabels=np.unique(y_true)) plt.xlabel('Predicted labels') plt.ylabel('True labels') plt.title('Confusion Matrix') plt.show() "How to plot confusion matrix in scikit-learn with class names?"
# Assuming you have classes stored in a list called 'class_names' class_names = ["cat", "ant", "bird"] # Plot confusion matrix with custom class names plt.figure(figsize=(8,6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=class_names, yticklabels=class_names) plt.xlabel('Predicted labels') plt.ylabel('True labels') plt.title('Confusion Matrix') plt.show() "Scikit-learn confusion matrix plot with labels and percentages"
# Calculate confusion matrix as before cm = confusion_matrix(y_true, y_pred) # Convert counts to percentages cm_perc = cm / cm.sum(axis=1)[:, np.newaxis] # Plot confusion matrix with labels and percentages plt.figure(figsize=(8,6)) sns.heatmap(cm_perc, annot=True, fmt='.2%', cmap='Blues', xticklabels=np.unique(y_true), yticklabels=np.unique(y_true)) plt.xlabel('Predicted labels') plt.ylabel('True labels') plt.title('Confusion Matrix (Percentages)') plt.show() "Python confusion matrix plot with sklearn and labeled axes"
# Plot confusion matrix with labeled axes plt.figure(figsize=(8,6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues') plt.xlabel('Predicted labels') plt.ylabel('True labels') plt.title('Confusion Matrix') plt.xticks(np.arange(len(class_names)), class_names) plt.yticks(np.arange(len(class_names)), class_names) plt.show() "Visualizing confusion matrix in Python with class names"
# Assuming 'class_names' is defined as before plt.figure(figsize=(8,6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=class_names, yticklabels=class_names) plt.xlabel('Predicted labels') plt.ylabel('True labels') plt.title('Confusion Matrix') plt.show() "Scikit-learn confusion matrix plot with labels on axes"
# Plot confusion matrix with labeled axes plt.figure(figsize=(8,6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=np.unique(y_true), yticklabels=np.unique(y_true)) plt.xlabel('Predicted labels') plt.ylabel('True labels') plt.title('Confusion Matrix') plt.show() "Scikit-learn plot confusion matrix with labels and color coding"
# Plot confusion matrix with labeled axes and color coding plt.figure(figsize=(8,6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=np.unique(y_true), yticklabels=np.unique(y_true)) plt.xlabel('Predicted labels') plt.ylabel('True labels') plt.title('Confusion Matrix') plt.show() "Python code for confusion matrix with sklearn and labeled classes"
# Plot confusion matrix with labeled classes plt.figure(figsize=(8,6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=class_names, yticklabels=class_names) plt.xlabel('Predicted labels') plt.ylabel('True labels') plt.title('Confusion Matrix') plt.show() "How to create confusion matrix plot in Python with scikit-learn?"
# Plot confusion matrix plt.figure(figsize=(8,6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues') plt.xlabel('Predicted labels') plt.ylabel('True labels') plt.title('Confusion Matrix') plt.show() "Plot confusion matrix with labeled axes in Python using sklearn"
# Plot confusion matrix with labeled axes plt.figure(figsize=(8,6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=np.unique(y_true), yticklabels=np.unique(y_true)) plt.xlabel('Predicted labels') plt.ylabel('True labels') plt.title('Confusion Matrix') plt.show() react-testing-library touch-event html5-canvas street-address buttonclick percentage jasmine-node tsc sticky signal-processing