9951 explained code solutions for 126 technologies


python-kerasHow do I generate a confusion matrix using Python and Keras?


A confusion matrix is a table used to evaluate the performance of a classification model. It is used to measure the accuracy of a model by comparing the predicted values with the actual values.

Using Python and Keras, a confusion matrix can be generated by first creating a prediction vector and a ground truth vector. These vectors should be the same size and contain binary values, where 1 represents a positive prediction and 0 represents a negative prediction.

Example code

# Create prediction vector
predictions = [1, 0, 1, 0, 1, 0, 1, 0]

# Create ground truth vector
ground_truth = [1, 0, 0, 0, 1, 0, 1, 0]

# Generate confusion matrix
from sklearn.metrics import confusion_matrix
conf_matrix = confusion_matrix(ground_truth, predictions)
print(conf_matrix)

Output example

[[4 1]
 [0 3]]

The code above creates two vectors, one for predictions and one for ground truth. The sklearn library is then imported and the confusion_matrix() function is used to generate the confusion matrix. The confusion matrix is printed to the console.

The confusion matrix contains four values: true positives, true negatives, false positives, and false negatives. In the example above, there are 4 true positives, 3 true negatives, 1 false positive, and 0 false negatives.

Helpful links

Edit this code on GitHub