Evaluation

Proper evaluation is important for training effective models that meet the project requirements.

In this lesson, we’ll discuss key evaluation metrics for classification and regression problems, along with tools like ROC curves and confusion matrices.

This Lesson Will Cover
  • πŸ“Š Classification Metrics (Accuracy, Precision, Recall, F1)
  • πŸ“ˆ Regression Metrics (MSE, MAE, R-squared)
  • πŸ“‰ ROC Curves and AUC
  • πŸ”„ Confusion Matrices
  • πŸ† Model Performance Evaluation

Classification Metrics

As we’ve discussed, classification problems involve predicting discrete labels (e.g., spam vs. not spam).

Below are some common metrics for classification.

Accuracy

The proportion of correctly classified samples.

Accuracy=Number of Correct PredictionsTotal Number of Predictions \text{Accuracy} = \frac{\text{Number of Correct Predictions}}{\text{Total Number of Predictions}}

When to use it?
When classes are balanced and all types of errors are equally important.

Examples

  • Evaluating general model performance on balanced datasets
  • Image classification for common objects
  • Quality control in manufacturing where defects occur at similar rates to good products

Precision

The fraction of true positives among all predicted positives.

Precision=True PositivesTrue Positives+False Positives \text{Precision} = \frac{\text{True Positives}}{\text{True Positives} + \text{False Positives}}

When to use it?
When false positives are costly or need to be minimized.

Examples

  • Medical diagnosis where false positives lead to unnecessary treatments
  • Spam detection where marking legitimate emails as spam is problematic
  • Fraud detection where false accusations are costly

Recall

The fraction of true positives among all actual positives.

Recall=True PositivesTrue Positives+False Negatives \text{Recall} = \frac{\text{True Positives}}{\text{True Positives} + \text{False Negatives}}

When to use it?
When missing positive cases is costly.

Examples

  • Disease detection where missing a sick patient is dangerous
  • Criminal detection where missing a true threat is high-risk
  • Mechanical failure prediction where missing a potential failure could be catastrophic

F1 Score

The harmonic mean of precision and recall.

F1=2β‹…Precisionβ‹…RecallPrecision+Recall \text{F1} = 2 \cdot \frac{\text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}}

When to use it?
When we need to find a balance between precision and recall.

Examples

  • Search engines to balance returning relevant results vs. finding all relevant items
  • Content recommendation systems where both relevance and coverage matter
  • Customer churn prediction where balance between false alarms and missed cases is needed
Decision Flow for Selecting a Classification Metric
Quick reference decision flow for selecting a classification metric.

Computing Classification Metrics with Scikit-Learn

These metrics are all implemented in scikit-learn:

from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score

# Example predictions and labels
y_true = [0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1]
y_pred = [0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0]

# Calculate metrics
accuracy = accuracy_score(y_true, y_pred)
precision = precision_score(y_true, y_pred)
recall = recall_score(y_true, y_pred)
f1 = f1_score(y_true, y_pred)

print(f"Accuracy: {accuracy:.2f}")    # Proportion of correctly classified samples
print(f"Precision: {precision:.2f}")  # Fraction of true positives among predicted positives
print(f"Recall: {recall:.2f}")        # Fraction of true positives among actual positives
print(f"F1 Score: {f1:.2f}")          # Harmonic mean of precision and recall

# Outputs:
# Accuracy: 0.61
# Precision: 0.58
# Recall: 0.64
# F1 Score: 0.61

Regression Metrics

Regression problems involve predicting continuous values (e.g., house prices, temperature, sales).

Below are some common metrics for regression.

Decision Flow for Selecting a Regression Metric
Quick reference decision flow for selecting a regression metric.

Mean Squared Error (MSE)

The average squared difference between predicted and actual values.

MSE=1nβˆ‘i=1n(y^iβˆ’yi)2 \text{MSE} = \frac{1}{n} \sum_{i=1}^{n} (\hat{y}_i - y_i)^2

When to use it?
When larger errors should be penalized more heavily and the scale of the target variable matters.

Examples

  • Stock price prediction where large errors are particularly costly
  • Energy consumption forecasting where significant deviations impact resource planning
  • Manufacturing quality control where precision is critical

Mean Absolute Error (MAE)

The average absolute difference between predicted and actual values.

MAE=1nβˆ‘i=1n∣y^iβˆ’yi∣ \text{MAE} = \frac{1}{n} \sum_{i=1}^{n} |\hat{y}_i - y_i|

When to use it?
When we need a metric that’s robust to outliers and easy to interpret.

Examples

  • Sales forecasting where interpretability is important
  • Weather temperature prediction where errors are equally important in both directions
  • Inventory management where absolute deviations matter

R-squared (RΒ²)

The proportion of variance in the dependent variable explained by the model.

R2=1βˆ’βˆ‘i=1n(y^iβˆ’yi)2βˆ‘i=1n(yiβˆ’yΛ‰)2 R^2 = 1 - \frac{\sum_{i=1}^n (\hat{y}_i - y_i)^2}{\sum_{i=1}^n (y_i - \bar{y})^2}

When to use it?
When we need to understand how well our model explains the variability in the data.

Examples

  • Real estate price prediction to understand model effectiveness
  • Academic performance prediction where explaining variance is important
  • Economic indicator forecasting where model fit is crucial
Comparison of MSE, MAE, and R-Squared Across Uniform Prediction Bias
Each curve shows the value of an error metric after every model prediction has been shifted by some constant offset sigma (the uniform bias). A positive bias moves all predictions upward; negative bias moves them downward. MSE (purple) grows quadratically with the bias, MAE (orange) grows linearly, and R-squared (pink) follows an inverted parabola. The exact numeric values depend on the dataset details (we used a sample dataset here), but the overall shapes are universally true. The key insight is that MSE & MAE tell us how wrong the predictions are (with MSE being more sensitive to large errors), whereas R-squared tells us how much variability we've captured.

Computing Regression Metrics with Scikit-Learn

These metrics are all implemented in scikit-learn:

from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
import numpy as np

# Example predictions and labels
y_true = [3.0, -0.5, 2.0, 7.0, 1.5, 4.2, -2.1, 8.9, 3.3, 5.7, 2.8, -1.4, 6.1, 0.8, 4.5]
y_pred = [2.5, 0.0, 2.0, 8.0, 1.8, 3.9, -1.8, 9.2, 3.0, 5.2, 3.1, -1.0, 5.8, 1.2, 4.8]

# Calculate metrics
mse = mean_squared_error(y_true, y_pred)
mae = mean_absolute_error(y_true, y_pred)
r2 = r2_score(y_true, y_pred)

print(f"MSE: {mse:.2f}")      # Average squared difference between predicted and actual values
print(f"MAE: {mae:.2f}")      # Average absolute difference between predicted and actual values
print(f"R-squared: {r2:.2f}") # Proportion of variance explained by the model

# Outputs:
# MSE: 0.19
# MAE: 0.38
# R-squared: 0.98

ROC Curves and AUC

ROC (Receiver Operating Characteristic) curves visualize the trade-off between true positive rate (TPR) and false positive rate (FPR) at different classification thresholds.

The area under the curve (AUC) is a metric calculated from the ROC curve that quantifies the overall ability of the model to distinguish between classes.

The ROC curve plots:

  • True Positive Rate (Sensitivity/Recall) on the y-axis
  • False Positive Rate (1 - Specificity) on the x-axis
TPR=True PositivesTrue Positives+False Negatives \text{TPR} = \frac{\text{True Positives}}{\text{True Positives} + \text{False Negatives}}
FPR=False PositivesFalse Positives+True Negatives \text{FPR} = \frac{\text{False Positives}}{\text{False Positives} + \text{True Negatives}}

When to use it?
When we need to:

  • Evaluate binary classifier performance across different thresholds
  • Compare multiple models’ discriminative ability
  • Choose an optimal classification threshold

Examples

  • Medical screening tests to balance sensitivity and specificity
  • Fraud detection systems where threshold tuning is critical
  • Risk assessment models where different operating points are needed
  • Credit scoring where different approval thresholds need evaluation

Example: Plotting ROC Curve with Scikit-Learn

from sklearn.metrics import roc_curve, roc_auc_score
import matplotlib.pyplot as plt

# Example predictions
y_true = [0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0]
y_scores = [0.1, 0.4, 0.35, 0.8, 0.2, 0.7, 0.3, 0.9, 0.15, 0.25, 0.65, 0.75, 0.1, 0.85, 0.2, 0.95, 0.3, 0.6, 0.8, 0.1, 0.67, 0.63, 0.54, 0.0, 0.27, 0.41, 0.67, 0.87, 0.66, 0.98, 0.32, 0.41, 0.02, 0.95, 0.7, 0.81, 0.96, 0.92, 0.27, 0.43]

# Compute ROC curve
fpr, tpr, thresholds = roc_curve(y_true, y_scores)
auc = roc_auc_score(y_true, y_scores)

# Plot
plt.plot(fpr, tpr, label=f"AUC = {auc:.2f}")
plt.plot([0, 1], [0, 1], 'k--')  # Add diagonal line
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plt.title("ROC Curve")
plt.legend()
plt.grid(True)
plt.show()
ROC Curve with AUC for Binary Classifier Performance
ROC curve example (with additional styles not shown in code above, see the Jupyter Notebook on GitHub for the full code).

Looking at these results:

  • The ROC curve starts at (0,0), where nothing is classified as positive.
  • As the decision threshold lowers, more positives are correctly identified, but false positives also increase.
  • The ideal classifier has a steep rise at the beginning (high TPR with low FPR).
  • A higher AUC would indicate even better performance, while an AUC closer to 0.5 suggests a weak model (random guessing).

Just to really drive the idea of the ROC curve home, consider this example:

Let’s consider a sample that gets a model score (probability of belonging to class 1) of 0.8.

  • If our threshold = 0.9, this score is below the threshold, so it’s classified as negative (0).
    • This is what happens near the bottom-left of the ROC chart, where we start with a threshold of 1 and decrease it in order to generate the curve from left to right.
  • Now say our threshold = 0.7, the score meets the new threshold, so it’s now classified as positive (1).

Lowering the threshold makes the model classify more samples as positive, increasing TPR but also increasing FPR.

Confusion Matrices

A confusion matrix is a fundamental tool for understanding classification performance.

It provides a detailed breakdown of model predictions, showing true positives (TP), true negatives (TN), false positives (FP), and false negatives (FN).

The matrix is organized as follows:

                 Predicted
Actual    |  Positive  |  Negative
-------------------------------
Positive  |     TP     |    FN
Negative  |     FP     |    TN

When to use it?
When we need to:

  • Understand detailed model performance beyond accuracy
  • Identify specific types of errors the model makes
  • Analyze class-specific performance
  • Debug model behavior

Examples

  • Medical diagnosis to understand misdiagnosis patterns
  • Quality control systems to analyze error types
  • Security systems where different types of failures have different costs
  • Customer churn prediction to analyze false alarm rates

Example: Displaying a Confusion Matrix

from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import matplotlib.pyplot as plt

# Example predictions and labels
y_true = [0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1]
y_pred = [0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1]

# Generate confusion matrix
cm = confusion_matrix(y_true, y_pred)
disp = ConfusionMatrixDisplay(confusion_matrix=cm,
                             display_labels=['Negative', 'Positive'])

# Plot with customization
disp.plot(cmap='Blues', values_format='d')
plt.title('Confusion Matrix')
plt.grid(False)
plt.show()

# Print additional metrics
tn, fp, fn, tp = cm.ravel()
print(f"True Negatives: {tn}")   # Correctly predicted negative cases
print(f"False Positives: {fp}")  # Incorrectly predicted as positive when actually negative
print(f"False Negatives: {fn}")  # Incorrectly predicted as negative when actually positive
print(f"True Positives: {tp}")   # Correctly predicted positive cases

# Outputs:
# True Negatives: 8
# False Positives: 3
# False Negatives: 3
# True Positives: 11
Confusion Matrix Heatmap for Binary Classification Task
Confusion matrix heatmap example (with additional styles not shown in code above, see the Jupyter Notebook on GitHub for the full code).

Conclusion

Fun fact about ROC curves – they were invented during World War II to analyze radar signals and assess the ability of radar operators to distinguish enemy aircraft from noise (e.g., birds). This is where the term β€œReceiver Operating Characteristic” comes from.

Key Takeaways

🎯 Choose evaluation metrics based on our specific problem and business requirements.

πŸ“Š Classification metrics include accuracy, precision, recall, and F1 score.

πŸ“ˆ Regression metrics include MSE, MAE, and R-squared.

πŸ” ROC curves and AUC help evaluate binary classifier performance across thresholds.

πŸ“‘ Confusion matrices provide a detailed breakdown of model predictions and errors.

πŸ› οΈ Scikit-learn provides comprehensive tools for calculating all these metrics.

βš–οΈ Different metrics are suitable for different scenarios and business objectives.

Next: Hyperparameter Optimization

Next, we’re diving back into model training and learning about grid search.

Comments (0)

No comments yet.