Cannot import name ‘plot_confusion_matrix’ from ‘sklearn.metrics’

Explanation:

The error message “cannot import name ‘plot_confusion_matrix’ from ‘sklearn.metrics'” suggests that the plot_confusion_matrix function is not available in the sklearn.metrics module.

This could happen due to one of the following reasons:

  1. The function does not exist in the version of scikit-learn you are using. The function was introduced in a later version (0.22 or higher), so if you have an older version, this function may not be available.
  2. You have a typo in the import statement. Double-check the import statement to ensure the function name is correct and spelled properly.

Here’s an example of how to use the plot_confusion_matrix function:

import matplotlib.pyplot as plt
from sklearn.metrics import plot_confusion_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

# Create a logistic regression model
model = LogisticRegression()

# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# Fit the model on the training data
model.fit(X_train, y_train)

# Plot the confusion matrix
plot_confusion_matrix(model, X_test, y_test, display_labels=["Class 0", "Class 1"])
plt.show()

This example demonstrates how to import plot_confusion_matrix from sklearn.metrics and use it to plot the confusion matrix for a logistic regression model.

Similar post

Leave a comment