3. Classification Metrics
Accuracy Limitations on Imbalanced Datasets
In machine learning, model performance is often summarized with a single metric. While accuracy is the most intuitive metric, it is incredibly dangerous when applied to imbalanced datasets. Accuracy is defined as the number of correct predictions divided by the total number of predictions. This works perfectly when you have balanced classes (e.g., 50% positive and 50% negative samples), but fails catastrophically when one class dominates.
Consider a credit card fraud detection system where only 1% of transactions are fraudulent, and 99% are legitimate. If you build a naive classifier that simply outputs legitimate for every single transaction without looking at the data, it will achieve 99% accuracy. Despite this impressive score, the model is completely useless because it fails to catch a single fraudulent event. Thus, relying solely on accuracy can lead to false confidence and disastrous deployment failures.
import numpy as np from sklearn.metrics import accuracy_score # Create an imbalanced dataset: 99 legitimate (0) and 1 fraud (1) y_true = np.array([0] * 99 + [1] * 1) # Simulating a naive model that predicts the majority class (legitimate) every time y_pred = np.array([0] * 100) # Calculate accuracy accuracy = accuracy_score(y_true, y_pred) print(f"Naive Model Accuracy: {accuracy * 100:.1f}%")
Precision, Recall, and F1-Score Definitions
To evaluate models on imbalanced datasets effectively, we use metrics derived from the Confusion Matrix: True Positives (TP), False Positives (FP), True Negatives (TN), and False Negatives (FN). Precision and Recall provide isolated views of model quality, while the F1-Score combines them into a balanced representation.
Precision (Positive Predictive Value) is the proportion of positive predictions that were actually correct. It is calculated as TP / (TP + FP). Recall (Sensitivity) is the proportion of actual positives that were correctly identified. It is calculated as TP / (TP + FN). The F1-Score is the harmonic mean of Precision and Recall. Unlike an arithmetic mean, the harmonic mean heavily penalizes extreme values; a model with perfect Precision but zero Recall will have an F1-Score of 0 instead of 0.5.
| Metric | Primary Concern | Critical Scenario |
|---|---|---|
| Precision | Minimizing False Positives (FP) | Spam filtering: avoiding safe emails being sent to spam. |
| Recall | Minimizing False Negatives (FN) | Cancer detection: ensuring no sick patient is missed. |
import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score # Ground truth: 1 represents a positive class (e.g., diseased) y_true = np.array([0, 0, 0, 1, 1, 1, 0, 1, 0, 1]) # Model predictions y_pred = np.array([0, 0, 0, 0, 1, 1, 0, 1, 1, 1]) # Calculating metrics prec = precision_score(y_true, y_pred) rec = recall_score(y_true, y_pred) f1 = f1_score(y_true, y_pred) print(f"Precision: {prec:.2f}") print(f"Recall: {rec:.2f}") print(f"F1-Score: {f1:.2f}")
Using classification_report to Audit Per-Class Metrics
In multi-class settings or multi-label datasets, parsing metrics for each individual class becomes complex. Scikit-learn provides an elegant audit utility called the classification_report. This tool outputs a formatted table containing Precision, Recall, F1-Score, and Support for each class.
Support is simply the actual count of occurrences of each class in the specified dataset. The report also lists different overall averages: 'macro avg' computes the metric independently for each class and takes their unweighted mean (treating all classes equally, regardless of size). 'weighted avg' calculates the mean of metrics weighted by the support of each class, which can hide poor minority class performance.
from sklearn.metrics import classification_report import numpy as np # Multi-class scenario: Class 0 (Apples), Class 1 (Bananas), Class 2 (Cherries) y_true = np.array([0, 0, 0, 0, 1, 1, 1, 2, 2, 2]) y_pred = np.array([0, 0, 0, 1, 1, 1, 1, 2, 0, 2]) target_names = ['Apples', 'Bananas', 'Cherries'] report = classification_report(y_true, y_pred, target_names=target_names) print(report)
Trading off Precision vs Recall Depending on Model Goals
Classifiers do not output raw binary outputs (0 or 1) by default; instead, they output probabilities between 0.0 and 1.0. The standard decision threshold is 0.5. If the model computes a probability >= 0.5, it predicts class 1, otherwise class 0.
You can manipulate this decision threshold to bias your model toward high Precision or high Recall. Decreasing the threshold (e.g., to 0.2) makes the model highly sensitive, flagging any borderline case as positive. This increases Recall but decreases Precision. Conversely, raising the threshold (e.g., to 0.8) makes the model highly selective, predicting positive only when highly confident. This increases Precision but decreases Recall.
import numpy as np from sklearn.metrics import precision_score, recall_score # True labels y_true = np.array([0, 0, 1, 1, 0, 1, 0, 1, 1, 0]) # Model probability predictions for the positive class probabilities = np.array([0.1, 0.3, 0.45, 0.9, 0.2, 0.75, 0.15, 0.6, 0.85, 0.4]) # Scenario A: Low threshold (0.3) -> Maximizing Recall y_pred_low = (probabilities >= 0.3).astype(int) # Scenario B: High threshold (0.8) -> Maximizing Precision y_pred_high = (probabilities >= 0.8).astype(int) print("Threshold 0.3:") print(f" -> Precision: {precision_score(y_true, y_pred_low):.2f}, Recall: {recall_score(y_true, y_pred_low):.2f}") print("\nThreshold 0.8:") print(f" -> Precision: {precision_score(y_true, y_pred_high):.2f}, Recall: {recall_score(y_true, y_pred_high):.2f}")
Knowledge Check
Ready to test your understanding of 3. Classification Metrics?