Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 65

Classification Model Evaluation Metrics

Recommended resources

Hello! Welcome to the first lesson of our new module, "Model Evaluation and Improvement."

In the last module, we built several classification models, including logistic regression and decision trees. We used accuracy as our main yardstick to measure their performance. But is accuracy always the best way to judge a model?

Imagine you're building a system to detect a rare disease that only affects 1 in 10,000 people. A model that simply predicts "no disease" for everyone would be 99.99% accurate, but it would be completely useless because it would never find a single person who is actually sick. This is a classic example of an imbalanced dataset, where one class is much more frequent than the other.

To get a true picture of a model's performance, especially in such cases, we need more sophisticated tools. In this lesson, your goal is to evaluate classification models using accuracy, precision, recall, and the F1-score. These metrics will give you a much deeper understanding of your model's strengths and weaknesses.

1. The Foundation: The Confusion Matrix

All advanced classification metrics are derived from a simple but powerful tool called the Confusion Matrix. It's a table that breaks down a model's predictions and compares them to the actual, true values.

A confusion matrix has four key components, which are best understood with an example.

Precision, Recall, F1 score, True Positive|Deep Learning Tutorial 19 (Tensorflow2.0, Keras & Python)

To understand these new metrics, let's first learn about the Confusion Matrix. This video from the 'codebasics' channel uses a simple and clear example of classifying images as 'dog' or 'not a dog' to explain the core concepts.

Watch from the beginning to 03:37. Focus on understanding the four key terms based on the 'dog' class being our 'positive' class: True Positive (TP): The model correctly predicted 'dog'. False Positive (FP): The model incorrectly predicted 'dog' (it was actually 'not a dog'). True Negative (TN): The model correctly predicted 'not a dog'. False Negative (FN): The model incorrectly predicted 'not a dog' (it was actually a 'dog').

To summarize, for a given "positive" class (e.g., 'spam', 'disease detected', 'dog'):

  • True Positive (TP): You predicted positive, and it's true. (Correct positive prediction)
  • True Negative (TN): You predicted negative, and it's true. (Correct negative prediction)
  • False Positive (FP): You predicted positive, but it's false. Also known as a Type I Error.
  • False Negative (FN): You predicted negative, but it's false. Also known as a Type II Error.

With these four values, we can calculate all our metrics.


2. Accuracy: A Good Start, But Not Enough

Let's revisit accuracy, but this time define it with our new terminology.

Accuracy tells you the overall fraction of correct predictions.

It answers the question: Out of all predictions, how many were right?

As we discussed, accuracy can be misleading on imbalanced datasets. If you have 99 negative samples and 1 positive sample, a model that always predicts "negative" has 99% accuracy but fails at its primary task of finding the positive sample. This is why we need precision and recall.


3. Precision and Recall: The Specialist Duo

Precision and recall are two metrics that focus on the performance of the positive class. They help us understand different kinds of errors.

This image gives a great analogy for the difference between accuracy and precision. Accuracy is about getting close to the target, while precision is about the consistency of your predictions.

Accuracy vs. Precision: Dartboard Analogy
In model evaluation, **accuracy** measures how close predictions are to the true values overall. **Precision** measures the consistency of positive predictions, i.e., how many of the predicted positives are actually positive.

Precision

Precision measures the accuracy of the positive predictions.

It answers the question: Of all the items we predicted as positive, how many were actually positive?

  • When is it important? When the cost of a False Positive is high.
  • Example: Email spam detection. If an important email (negative class) is incorrectly marked as spam (positive class), you might miss a job offer! You want the predictions of "spam" to be very precise.

Recall

Recall (also known as Sensitivity or True Positive Rate) measures how many of the actual positive cases the model was able to "recall" or find.

It answers the question: Of all the actual positive items, how many did we correctly identify?

  • When is it important? When the cost of a False Negative is high.
  • Example: Medical screening for a disease. If a sick patient (positive class) is incorrectly told they are healthy (negative class), the consequences can be catastrophic. You want to find or "recall" every single sick patient.

Let's watch how these are calculated.

Precision, Recall, F1 score, True Positive|Deep Learning Tutorial 19 (Tensorflow2.0, Keras & Python)

Now that we have the concepts, let's see how Precision and Recall are calculated from the confusion matrix. The video continues with the dog classification example.

Watch from 04:06 to 06:01. Notice the key difference in the denominator for each formula: Precision's denominator is the total number of positive predictions (TP + FP). Recall's denominator is the total number of actual positive cases (TP + FN).

Test your understanding!

A classifier is used to detect fraudulent transactions ('Fraud' is the positive class). After testing on 150 transactions, its performance is summarized in this confusion matrix.

Predicted: Fraud Predicted: Not Fraud
Actual: Fraud 8 (TP) 2 (FN)
Actual: Not Fraud 5 (FP) 135 (TN)
  1. What is the Precision of the classifier? (What does this number mean in the context of fraud detection?)
  2. What is the Recall of the classifier? (What does this number mean?)
Show answer
  1. Precision = TP / (TP + FP) = 8 / (8 + 5) = 8 / 13 ≈ 0.615.
    This means that when the model flags a transaction as fraudulent, it is correct about 61.5% of the time. The other 38.5% of the time, it's a false alarm (a legitimate transaction is blocked).

  2. Recall = TP / (TP + FN) = 8 / (8 + 2) = 8 / 10 = 0.80.
    This means that the model successfully catches 80% of all actual fraudulent transactions. It misses 20% of them.


4. F1-Score: The Balanced Approach

Often, there's a trade-off: improving precision can hurt recall, and vice-versa. So how do we find a balance? The F1-Score is a single metric that combines both.

The F1-Score is the harmonic mean of precision and recall.

We use the harmonic mean because it penalizes extreme values. If either precision or recall is very low, the F1-score will also be low. A high F1-score requires both precision and recall to be high.

F1 Score in Machine Learning

The F1-Score is our go-to metric when we need to balance precision and recall, especially for imbalanced datasets. To understand why it uses a 'harmonic mean' instead of a simple average, let's read a short explanation.

Read the section 'F1 Score by combining Precision and Recall' and the subsection 'Why We Use Harmonic Mean Instead of Simple Average?'. The key takeaway is that the harmonic mean ensures a low score in either precision or recall will drag the F1-score down.

This image provides a great visual summary, connecting the confusion matrix to the formulas for all four metrics we've discussed.

Confusion Matrix and Classification Metrics Calculation
This diagram shows how to get from a confusion matrix (top-left) with counts of True/False Positives/Negatives to the final calculated values for Accuracy, Precision, Recall, and F1-score.

5. Implementation in Python with Scikit-Learn

Manually calculating these metrics is great for understanding, but in practice, you'll use libraries. Scikit-learn provides functions that do all the work for you. The most useful one is classification_report, which gives you everything in a neat format.

Precision, Recall, F1 score, True Positive|Deep Learning Tutorial 19 (Tensorflow2.0, Keras & Python)

Let's see how easy it is to generate these metrics in Python. The final part of the 'codebasics' video shows how to use scikit-learn's confusion_matrix and classification_report functions.

Watch from 07:56 to 10:59. Notice how the output from the classification_report function matches the values that were calculated manually earlier in the video.

Here is a complete code snippet you can run. It uses y_true (the actual labels) and y_pred (the model's predictions) to generate both a confusion matrix and the full report.

from sklearn.metrics import classification_report, confusion_matrix

# Let's use a spam detection example where 1 = spam and 0 = not spam.
y_true = [1, 0, 1, 1, 0, 1, 0, 0, 1, 0] # Actual labels
y_pred = [1, 0, 1, 0, 0, 1, 0, 1, 1, 0] # Our model's predictions

# Generate and print the confusion matrix
# In scikit-learn's output:
# [[TN, FP],
#  [FN, TP]]
cm = confusion_matrix(y_true, y_pred)
print("Confusion Matrix:")
print(cm)
print("\n---------------------\n")

# Generate and print the classification report
# 'target_names' makes the report easier to read
report = classification_report(y_true, y_pred, target_names=['not spam (0)', 'spam (1)'])
print("Classification Report:")
print(report)

When you run this code, the classification report will show you the precision, recall, and f1-score for each class ('spam' and 'not spam'). It also provides the overall accuracy and averaged scores, giving you a complete performance summary in one command.


Conclusion

You've now moved beyond simple accuracy and have a professional toolkit for evaluating classification models!

Key Takeaways:

  • Accuracy measures overall correctness but can be misleading on imbalanced datasets.
  • The Confusion Matrix (TP, TN, FP, FN) is the foundation for detailed classification metrics.
  • Precision is crucial when you want to minimize False Positives (e.g., spam filtering). It asks: "When my model predicts positive, how often is it right?"
  • Recall is crucial when you want to minimize False Negatives (e.g., medical diagnosis). It asks: "Of all the true positive cases, how many did my model find?"
  • The F1-Score provides a balanced measure of precision and recall, making it a robust metric for many scenarios.
  • The sklearn.metrics.classification_report is your go-to function for a comprehensive model evaluation in Python.

Preview of the Next Lesson:
We've covered how to evaluate classification models. But what about regression models, where we predict a continuous number (like a price or temperature) instead of a class? In the next lesson, we'll explore the equivalent metrics for regression, learning how to evaluate model performance using Mean Squared Error (MSE) and R-squared.