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.
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.
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.
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.
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
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.
Mean Squared Error (MSE)
The average squared difference between predicted and actual values.
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.
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.
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
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
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()
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
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.