confusion matrix in python

To create a confusion matrix in Python, we can use the confusion_matrix() function from the scikit-learn library. Here's an example:

main.py
from sklearn.metrics import confusion_matrix

# true labels
y_true = [0, 1, 0, 1, 1, 0, 0, 1, 1, 1]

# predicted labels
y_pred = [1, 1, 0, 1, 1, 0, 0, 1, 1, 0]

# create confusion matrix
cm = confusion_matrix(y_true, y_pred)

print(cm)
236 chars
13 lines

Output:

main.py
array([[3, 1],
       [1, 5]])
31 chars
3 lines

In this example, we have two classes (0 and 1). The confusion matrix tells us the number of true positives, false positives, true negatives, and false negatives for each class. In this case, we have:

  • 3 true positives for class 0
  • 1 false positive for class 0
  • 1 false negative for class 0
  • 5 true positives for class 1

We can interpret the confusion matrix to evaluate the performance of our machine learning model.

gistlibby LogSnag