Skip to main content

Welcome to a Grasp lesson

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

Lesson 26

Classification Model Evaluation

This lesson is built with resources from geeksforgeeks.org and cohere.com.

Hello! Welcome back to our course on building AI models.

In our last lesson, you did some excellent work implementing a complete training loop in PyTorch. You learned how to take a model architecture and teach it by minimizing a loss function over many epochs. This is the engine of deep learning.

However, a low training loss doesn't automatically guarantee a useful model. It only tells us that the model has gotten good at predicting the data it was trained on. How will it perform on new, unseen data? To answer that, we need to move from training to evaluation.

This lesson addresses the learning outcome: Evaluate a classification model using metrics such as accuracy, precision, recall, and F1-score. We'll explore why simply measuring "how many did we get right?" isn't enough, especially for real-world problems, and introduce a suite of more insightful metrics that will become essential tools in your AI engineering toolkit.

1. Accuracy: The Simplest Metric (and Its Pitfalls)

The most intuitive way to measure a model's performance is accuracy: the proportion of correct predictions out of the total number of predictions.

While simple and easy to understand, accuracy can be dangerously misleading, especially when dealing with imbalanced datasets, where one class is much more frequent than others.

Imagine a fraud detection model for a financial application. If only 0.1% of transactions are fraudulent, a lazy model that predicts "not fraud" every single time would achieve 99.9% accuracy! It sounds impressive, but it's completely useless because it fails at its primary task of detecting fraud.

This is why we need a more nuanced set of metrics. The following reading explains this problem clearly using a spam classification example.

Classification Metrics Explained: Accuracy, Precision, ...

This article from Cohere provides a great introduction to the most common classification metrics. We'll start with the section on accuracy to solidify your understanding of its limitations.

Please read the section titled 'Accuracy'. It will walk you through a clear example of why accuracy can be a misleading metric in the face of imbalanced data.


2. The Confusion Matrix: A Deeper Look at Errors

To move beyond accuracy, we first need to categorize a model's predictions in more detail. We do this using a Confusion Matrix, which breaks down predictions into four categories. For a binary classification task (e.g., Spam vs. Not Spam), we first define a "positive" and "negative" class. Let's say "Spam" is our positive class (the one we want to find).

The four categories are:

  • True Positive (TP): The model correctly predicts the positive class. (e.g., correctly identifies a spam email).
  • True Negative (TN): The model correctly predicts the negative class. (e.g., correctly identifies a non-spam email).
  • False Positive (FP): The model incorrectly predicts the positive class. Also known as a "Type I Error". (e.g., a legitimate email is flagged as spam).
  • False Negative (FN): The model incorrectly predicts the negative class. Also known as a "Type II Error". (e.g., a spam email is missed and goes to the inbox).

The Confusion Matrix is the foundation for calculating precision, recall, and F1-score.

Confusion Matrix with Precision and Recall Formulas
This image shows a standard 2x2 confusion matrix, which visualizes the performance of a binary classifier. It categorizes outcomes into True Positives (TP), True Negatives (TN), False Positives (FP), and False Negatives (FN), and provides the formulas for calculating precision and recall.

Now, let's continue with the same article to see how the confusion matrix is constructed.

Classification Metrics Explained: Accuracy, Precision, ...

Let's formalize the concept of the confusion matrix with the same running example.

Read the section titled 'Confusion Matrix'. Focus on understanding the definitions of TP, TN, FP, and FN and how they are laid out in the 2x2 matrix.


3. Precision vs. Recall: The Fundamental Trade-off

With the confusion matrix established, we can define two critical metrics: Precision and Recall.

Precision

Precision answers the question: Of all the times the model predicted "positive", how often was it correct?

High precision is important when the cost of a False Positive is high. For an email spam filter, a false positive means an important email gets sent to spam. You want to be very precise when you mark an email as spam, so you prioritize high precision.

Recall (or Sensitivity)

Recall answers the question: Of all the actual positive cases, how many did the model correctly identify?

High recall is important when the cost of a False Negative is high. For medical screening (e.g., detecting cancer), a false negative means a sick patient is told they are healthy, with potentially fatal consequences. You want to recall or "catch" as many positive cases as possible, so you prioritize high recall, even if it means some healthy patients are flagged for more testing (more false positives).

Often, improving precision comes at the cost of recall, and vice-versa. This is known as the Precision-Recall Trade-off. The choice of which metric to prioritize depends entirely on the business or product objective.

The next two sections of the article elaborate on these two metrics and the trade-off between them.

Classification Metrics Explained: Accuracy, Precision, ...

Now let's dive into the definitions and implications of precision and recall.

Please read the sections 'Precision' and 'Recall'. Pay close attention to the formulas and the discussion about the trade-off, including which metric to prioritize for the spam classification task.


4. F1-Score: A Balanced Measure

What if both precision and recall are important? In that case, we can use the F1-Score. The F1-score is the harmonic mean of precision and recall.

The harmonic mean is used because it penalizes extreme values. A model will only get a high F1-score if both its precision and recall are high. If either one is very low, the F1-score will also be low. It's a great default metric when you need a balance between minimizing false positives and minimizing false negatives.

Let's complete our conceptual overview with the final part of the article.

Classification Metrics Explained: Accuracy, Precision, ...

The F1-score provides a single number to summarize a model's performance when both precision and recall matter.

Read the section titled 'F1' to understand how it combines precision and recall into one metric.

Test your understanding!

Imagine you have built a model to detect defective parts on an assembly line. After testing it on 1000 parts, you get the following results:

  • True Positives (TP): 90 (correctly identified defective parts)
  • False Positives (FP): 10 (incorrectly flagged good parts as defective)
  • False Negatives (FN): 20 (missed defective parts)
  • True Negatives (TN): 880 (correctly identified good parts)

Questions:

  1. Calculate the Precision, Recall, and F1-Score for your model.
  2. Given the context (manufacturing), which is more costly: a False Positive or a False Negative? Would you want to optimize for higher Precision or higher Recall? Explain your reasoning.
Show answer

1. Calculations:

  • Precision = TP / (TP + FP) = 90 / (90 + 10) = 90 / 100 = 0.90
  • Recall = TP / (TP + FN) = 90 / (90 + 20) = 90 / 110 = ~0.82
  • F1-Score = 2 * (Precision * Recall) / (Precision + Recall) = 2 * (0.90 * 0.82) / (0.90 + 0.82) = 1.476 / 1.72 = ~0.86

2. Interpretation and Optimization:
The choice depends on the business context:

  • A False Positive means a good part is flagged as defective. This might lead to it being discarded or re-inspected, which costs time and materials.
  • A False Negative means a defective part is missed and shipped to a customer. This could lead to product failure, customer dissatisfaction, safety issues, brand damage, and expensive recalls.

In most manufacturing scenarios, the cost of a False Negative is much higher. Therefore, you would want to optimize for higher Recall. You want to catch as many defective parts as possible, even if it means you accidentally flag a few good ones for re-inspection.


5. Implementation in PyTorch

Now that you understand the theory, let's see how to calculate these metrics in code. In a real project, you'd typically use a library like scikit-learn for this, but it's very instructive to see how to calculate them from scratch using PyTorch tensors. This reinforces the concepts and your tensor manipulation skills.

Assuming you have your true labels (y_true_tensor) and your model's predictions (y_pred_tensor), you can use boolean indexing to count the TP, FP, and FN.

How to calculate the F1 score and other custom metrics in PyTorch?

This article from GeeksforGeeks includes a concise code snippet that demonstrates how to calculate these metrics manually using PyTorch tensors. This is exactly what you would do in your evaluation loop after getting predictions from your model.

Focus only on the Python code block under the heading 'Calculating Model Metrics: Precision, Recall, F1-score, ROC AUC'. Ignore the surrounding text and setup. Study how boolean logic (&) and .sum() are used on PyTorch tensors to count the TP, FP, and FN, which are then used in the familiar formulas.

This code would fit perfectly into a validation or testing loop. After iterating through your test data loader and collecting all predictions and true labels, you would run this block to get a final performance score for your model.


6. A Note on Multi-Class Classification

So far, we've focused on binary classification. How do these metrics work when you have more than two classes (e.g., classifying news articles into "Sports", "Politics", or "Technology")?

The general approach is to calculate the metrics for each class individually in a "one-vs-rest" manner. For example, to calculate the precision for "Sports", you would treat "Sports" as the positive class and "Politics" and "Technology" combined as the negative class.

After calculating metrics for each class, you can average them to get a single overall score. A common method is the macro-average, which calculates the metric for each class and then takes the unweighted average. This treats every class as equally important, regardless of how many samples it has.

The first article we read has a great section that covers this.

Classification Metrics Explained: Accuracy, Precision, ...

Let's briefly see how these concepts extend to problems with more than two classes.

Read the final section, 'Multi-Class Classification'. Focus on the idea of calculating Precision and Recall on a per-class basis and then averaging them to get a 'Macro-Average' score.


Conclusion

You now have a solid set of tools for evaluating classification models far more effectively than with accuracy alone. This is a critical skill for any AI engineer, as choosing the right metric directly influences how you judge a model's success and guides your efforts to improve it.

Key Takeaways:

  • Accuracy is misleading for imbalanced datasets.
  • The Confusion Matrix (TP, TN, FP, FN) is the basis for more advanced metrics.
  • Precision measures correctness among positive predictions (minimizes FPs). It's important when the cost of a false positive is high.
  • Recall measures the ability to find all actual positives (minimizes FNs). It's important when the cost of a false negative is high.
  • The F1-Score provides a balanced measure when both precision and recall are important.
  • In multi-class settings, these metrics are often calculated per-class and then averaged (e.g., macro-average).

Next up:

Now that you know how to properly measure a model's performance, how do you improve it? In the next lesson, we'll dive into hyperparameter tuning, where you'll use these very metrics to guide your experiments as you adjust the learning rate, batch size, and network architecture to build better models.