sklearn plot confusion matrix

To plot a confusion matrix using the scikit-learn library in Python, you can follow these steps:

  1. Import the necessary modules:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix
  1. Compute the confusion matrix using the true labels and predicted labels:
true_labels = [1, 0, 1, 1, 0, 1]
predicted_labels = [1, 0, 0, 1, 0, 1]
cm = confusion_matrix(true_labels, predicted_labels)
  1. Define a function to plot the confusion matrix:
def plot_confusion_matrix(cm, classes):
    sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
    plt.title('Confusion Matrix')
    plt.xlabel('Predicted Label')
    plt.ylabel('True Label')
    plt.xticks(np.arange(len(classes)), classes)
    plt.yticks(np.arange(len(classes)), classes)
  1. Call the function to plot the confusion matrix:
class_names = ['Class 0', 'Class 1']
plot_confusion_matrix(cm, class_names)

By following these steps, you will be able to plot a confusion matrix using scikit-learn in Python.