Machine learning models are increasingly used in various applications to classify data into different categories. However, evaluating the performance of these models is crucial to ensure their accuracy and reliability. One essential tool in this evaluation process is the confusion matrix. In this article, we will delve into the details of the confusion matrix, its significance in machine learning, and how it can be used to improve the performance of classification models.
What is a Confusion Matrix?
A confusion matrix is a matrix that summarizes the performance of a machine learning model on a set of test data. It is a means of displaying the number of accurate and inaccurate instances based on the model’s predictions. It is often used to measure the performance of classification models, which aim to predict a categorical label for each input instance.
The matrix displays the number of instances produced by the model on the test data.
- True Positive (TP): The model correctly predicted a positive outcome (the actual outcome was positive).
- True Negative (TN): The model correctly predicted a negative outcome (the actual outcome was negative).
- False Positive (FP): The model incorrectly predicted a positive outcome (the actual outcome was negative). Also known as a Type I error.
- False Negative (FN): The model incorrectly predicted a negative outcome (the actual outcome was positive). Also known as a Type II error.
Why do we need a Confusion Matrix?
When assessing a classification model’s performance, a confusion matrix is essential. It offers a thorough analysis of true positive, true negative, false positive, and false negative predictions, facilitating a more profound comprehension of a model’s recall, accuracy, precision, and overall effectiveness in class distinction. When there is an uneven class distribution in a dataset, this matrix is especially helpful in evaluating a model’s performance beyond basic accuracy metrics.
Metrics based on Confusion Matrix Data
1. Accuracy
Accuracy is used to measure the performance of the model. It is the ratio of Total correct instances to the total instances.Â
[Tex]Accuracy = \frac {TP+TN}{TP+TN+FP+FN}
[/Tex]
For the above case:
Accuracy = (5+3)/(5+3+1+1) = 8/10 = 0.8
2. Precision
Precision is a measure of how accurate a model’s positive predictions are. It is defined as the ratio of true positive predictions to the total number of positive predictions made by the model.
[Tex]\text{Precision} = \frac{TP}{TP+FP}
[/Tex]
For the above case:
Precision = 5/(5+1) =5/6 = 0.8333
3. Recall
Recall measures the effectiveness of a classification model in identifying all relevant instances from a dataset. It is the ratio of the number of true positive (TP) instances to the sum of true positive and false negative (FN) instances.
[Tex]\text{Recall} = \frac{TP}{TP+FN}
[/Tex]
 For the above case:
Recall = 5/(5+1) =5/6 = 0.8333
Note: We use precision when we want to minimize false positives, crucial in scenarios like spam email detection where misclassifying a non-spam message as spam is costly. And we use recall when minimizing false negatives is essential, as in medical diagnoses, where identifying all actual positive cases is critical, even if it results in some false positives.
4. F1-Score
F1-score is used to evaluate the overall performance of a classification model. It is the harmonic mean of precision and recall,
[Tex]\text{F1-Score} = \frac {2 \cdot Precision \cdot Recall}{Precision + Recall}
[/Tex]
For the above case:
F1-Score: = (2* 0.8333* 0.8333)/( 0.8333+ 0.8333) Â = 0.8333
We balance precision and recall with the F1-score when a trade-off between minimizing false positives and false negatives is necessary, such as in information retrieval systems.
5. Specificity
Specificity is another important metric in the evaluation of classification models, particularly in binary classification. It measures the ability of a model to correctly identify negative instances. Specificity is also known as the True Negative Rate. Formula is given by:
[Tex]\text{Specificity} = \frac{TN}{TN+FP}
[/Tex]
For example,
Specificity=3/(1+3)â=3/4=0.75
6. Type 1 and Type 2 error
1. Type 1 error
Type 1 error occurs when the model predicts a positive instance, but it is actually negative. Precision is affected by false positives, as it is the ratio of true positives to the sum of true positives and false positives.
[Tex]\text{Type 1 Error} = \frac{FP}{TN+FP}
[/Tex]
For example, in a courtroom scenario, a Type 1 Error, often referred to as a false positive, occurs when the court mistakenly convicts an individual as guilty when, in truth, they are innocent of the alleged crime. This grave error can have profound consequences, leading to the wrongful punishment of an innocent person who did not commit the offense in question. Preventing Type 1 Errors in legal proceedings is paramount to ensuring that justice is accurately served and innocent individuals are protected from unwarranted harm and punishment.
2. Type 2 error
Type 2 error occurs when the model fails to predict a positive instance. Recall is directly affected by false negatives, as it is the ratio of true positives to the sum of true positives and false negatives.
In the context of medical testing, a Type 2 Error, often known as a false negative, occurs when a diagnostic test fails to detect the presence of a disease in a patient who genuinely has it. The consequences of such an error are significant, as it may result in a delayed diagnosis and subsequent treatment.
[Tex]\text{Type 2 Error} = \frac{FN}{TP+FN}
[/Tex]
Precision emphasizes minimizing false positives, while recall focuses on minimizing false negatives.
Confusion Matrix For binary classification
A 2X2 Confusion matrix is shown below for the image recognition having a Dog image or Not Dog image.
| Predicted Dog | Predicted Not Dog |
|---|
| Actual Dog | True Positive (TP) | False Negative (FN) |
|---|
| Actual Not Dog | False Positive (FP) | True Negative (TN) |
|---|
- True Positive (TP): It is the total counts having both predicted and actual values are Dog.
- True Negative (TN): It is the total counts having both predicted and actual values are Not Dog.
- False Positive (FP): It is the total counts having prediction is Dog while actually Not Dog.
- False Negative (FN): It is the total counts having prediction is Not Dog while actually, it is Dog.
Example: Confusion Matrix for Dog Image Recognition with Numbers
Index
| 1
| 2
| 3
| 4
| 5
| 6
| 7
| 8
| 9
| 10
|
|---|
Actual
| Dog
| Dog
| Dog
| Not Dog
| Dog
| Not Dog
| Dog
| Dog
| Not Dog
| Not Dog
|
|---|
Predicted
| Dog
| Not Dog
| Dog
| Not Dog
| Dog
| Dog
| Dog
| Dog
| Not Dog
| Not Dog
|
|---|
Result
| TP
| FN
| TP
| TN
| TP
| FP
| TP
| TP
| TN
| TN
|
|---|
- Actual Dog Counts = 6Â
- Actual Not Dog Counts = 4
- True Positive Counts = 5
- False Positive Counts = 1
- True Negative Counts = 3
- False Negative Counts = 1
Â
| Predicted
|
|---|
Dog
| Not Dog
|
|---|
Actual
| Dog
| True Positive (TP =5)
| False Negative (FN =1)
|
|---|
Not Dog
| False Positive (FP=1)
| True Negative (TN=3)
|
|---|
Implementation of Confusion Matrix for Binary classification using Python
Step 1: Import the necessary libraries
Python
import numpy as np
from sklearn.metrics import confusion_matrix,classification_report
import seaborn as sns
import matplotlib.pyplot as plt
Step 2: Create the NumPy array for actual and predicted labels
Python
actual = np.array(
['Dog','Dog','Dog','Not Dog','Dog','Not Dog','Dog','Dog','Not Dog','Not Dog'])
predicted = np.array(
['Dog','Not Dog','Dog','Not Dog','Dog','Dog','Dog','Dog','Not Dog','Not Dog'])
Step 3: Compute the confusion matrix
Python
cm = confusion_matrix(actual,predicted)
Step 4: Plot the confusion matrix with the help of the seaborn heatmap
Python
sns.heatmap(cm,
annot=True,
fmt='g',
xticklabels=['Dog','Not Dog'],
yticklabels=['Dog','Not Dog'])
plt.ylabel('Actual', fontsize=13)
plt.title('Confusion Matrix', fontsize=17, pad=20)
plt.gca().xaxis.set_label_position('top')
plt.xlabel('Prediction', fontsize=13)
plt.gca().xaxis.tick_top()
plt.gca().figure.subplots_adjust(bottom=0.2)
plt.gca().figure.text(0.5, 0.05, 'Prediction', ha='center', fontsize=13)
plt.show()
Output:

Visualizing the Confusion Matrix
Step 5: Classifications Report based on Confusion Metrics
Python
print(classification_report(actual, predicted))
Output:
precision recall f1-score support
Dog 0.83 0.83 0.83 6
Not Dog 0.75 0.75 0.75 4
accuracy 0.80 10
macro avg 0.79 0.79 0.79 10
weighted avg 0.80 0.80 0.80 10
Confusion Matrix For Multi-class Classification
In multi-class classification, you have more than two possible classes for your model to predict. The confusion matrix expands to accommodate these additional classes.
- Rows: Represent the actual classes (ground truth) in your dataset.
- Columns: Represent the predicted classes by your model.
Each cell within the matrix shows the count of instances where the model predicted a particular class (column) when the actual class was another (row).
Now, let’s consider there are three classes. A 3X3 Confusion matrix is shown below for the image having three classes.
Example: Confusion Matrix for Image Classification (Cat, Dog, Horse)
| Predicted Cat | Predicted Dog | Predicted Horse |
|---|
| Actual Cat | True Positive (TP) | False Negative (FN) | False Negative (FN) |
|---|
| Actual Dog | False Negative (FN) | True Positive (TP) | False Negative (FN) |
|---|
| Actual Horse | False Negative (FN) | False Negative (FN) | True Positive (TP) |
|---|
- True Positive (TP): The image was of a particular animal (cat, dog, or horse), and the model correctly predicted that animal. For example, a picture of a cat correctly identified as a cat.
- True Negative (TN): The image was not of a particular animal and the model correctly predicted it as not that animal. For example, a picture of a car correctly identified as not a cat, not a dog, and not a horse.
- False Positive (FP): The image was not of a particular animal, but the model incorrectly predicted it as that animal. For example, a picture of a horse mistakenly identified as a dog.
- False Negative (FN): The image was of a particular animal, but the model incorrectly predicted it as a different animal. For example, a picture of a dog mistakenly identified as a cat.
Example with Numbers:
Let’s consider the scenario where the model processed 30 images:
| Predicted Cat | Predicted Dog | Predicted Horse |
|---|
| Actual Cat | 8 | 1 | 1 |
|---|
| Actual Dog | 2 | 10 | 0 |
|---|
| Actual Horse | 0 | 2 | 8 |
|---|
In this scenario:
- Cats: 8 were correctly identified, 1 was misidentified as a dog, and 1 was misidentified as a horse.
- Dogs: 10 were correctly identified, 2 were misidentified as cats.
- Horses: 8 were correctly identified, 2 were misidentified as dogs.
To calculate true negatives, we need to know the total number of images that were NOT cats, dogs, or horses. Let’s assume there were 10 such images, and the model correctly classified all of them as “not cat,” “not dog,” and “not horse.”
Therefore:
- True Negative (TN) Counts: 10 (for each class, as the model correctly identified each non-cat/dog/horse image as not belonging to that class)
Implementation of Confusion Matrix for Multi-Class classification using Python
Step 1: Import the necessary libraries
Python
import numpy as np
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay, classification_report
import matplotlib.pyplot as plt
Step 2: Create the NumPy array for actual and predicted labels
Python
# Actual labels
y_true = ['Cat'] * 10 + ['Dog'] * 12 + ['Horse'] * 10
# Predicted labels
y_pred = ['Cat'] * 8 + ['Dog'] + ['Horse'] + ['Cat'] * 2 + ['Dog'] * 10 + ['Horse'] * 8 + ['Dog'] * 2
# Classes
classes = ['Cat', 'Dog', 'Horse']
Step 3: Generate and Visualize the Confusion Matrix
Python
# Generate the confusion matrix
cm = confusion_matrix(y_true, y_pred, labels=classes)
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=classes)
disp.plot(cmap=plt.cm.Blues)
plt.title('Confusion Matrix', fontsize=15, pad=20)
plt.xlabel('Prediction', fontsize=11)
plt.ylabel('Actual', fontsize=11)
#Customizations
plt.gca().xaxis.set_label_position('top')
plt.gca().xaxis.tick_top()
plt.gca().figure.subplots_adjust(bottom=0.2)
plt.gca().figure.text(0.5, 0.05, 'Prediction', ha='center', fontsize=13)
plt.show()
Output:

Display the confusion matrix
Step 4: Print the Classification Report
Python
# Print classification report
print(classification_report(y_true, y_pred, target_names=classes))
Output:
precision recall f1-score support
Cat 0.80 0.80 0.80 10
Dog 0.77 0.83 0.80 12
Horse 0.89 0.80 0.84 10
accuracy 0.81 32
macro avg 0.82 0.81 0.81 32
weighted avg 0.82 0.81 0.81 32
Conclusion
To sum up, the confusion matrix is an essential instrument for evaluating the effectiveness of classification models. Insights into a model’s accuracy, precision, recall, and general efficacy in classifying instances are provided by the thorough analysis of true positive, true negative, false positive, and false negative predictions it offers. The article provided examples to illustrate each metric’s computation and discussed its importance. It also demonstrated how confusion matrices can be implemented in Python for binary and multi-class classification scenarios. Practitioners can make well-informed decisions regarding model performanceâparticularly when dealing with imbalanced class distributionsâby comprehending and applying these metrics.
FAQs on Confusion Matrix
How to interpret a confusion matrix?
A confusion matrix summarizes a classification model’s performance, with entries representing true positive, true negative, false positive, and false negative instances, providing insights into model accuracy and errors.
What are the advantages of using Confusion matrix?
The confusion matrix provides a comprehensive evaluation of a classification model’s performance, offering insights into true positives, true negatives, false positives, and false negatives, aiding nuanced analysis beyond basic accuracy.
What are some examples of confusion matrix applications?
Confusion matrices find applications in various fields, including medical diagnosis (identifying true/false positives/negatives for diseases), fraud detection, sentiment analysis, and image recognition accuracy assessment.
What is the confusion matrix diagram?
A confusion matrix diagram visually represents the performance of a classification model. It displays true positive, true negative, false positive, and false negative values in a structured matrix format.
What are the three values of the confusion matrix?
The three values of the confusion matrix are true positive (correctly predicted positive instances), true negative (correctly predicted negative instances), and false positive (incorrectly predicted positive instances).