Regression Loss Functions, Imbalanced Classification Metrics, and Thresholding
Machine LearningModel answerLast updated
Compare MAE vs MSE for regression, interpret ROC-AUC and PR-AUC under severe class imbalance, design loss functions for imbalanced neural networks, and select classification thresholds rigorously.
You're building machine learning systems and need to make sound decisions about loss functions, evaluation metrics, and operating points. Answer each part with specific reasoning:
Part 1: Regression Loss Functions
Compare MAE (mean absolute error) and MSE (mean squared error) as optimization objectives. Discuss their sensitivity to outliers, gradient properties during training, and practical optimization challenges. Provide a specific scenario where MSE produces poor results while MAE works well.
Part 2: Classification Metrics Under Imbalance
You have a binary classifier on a dataset where only 1% of examples are positive. The model achieves ROC-AUC = 0.90 but PR-AUC = 0.25. Explain what each metric reveals about model performance. Why can ROC-AUC appear strong while PR-AUC remains low? Which metric matters more for this use case?
Part 3: Neural Network Design for Imbalanced Data
Design the output layer and loss function for a binary classification neural network. Explain two approaches to handling class imbalance: class weighting and focal loss. For each, describe how it modifies the gradient signal from positive versus negative examples during backpropagation.
Part 4: Threshold Selection Without Bias
Your application requires precision to be at least 0.50 at the chosen operating threshold. Describe a rigorous process for selecting this threshold from model predictions, ensuring your estimate is not optimistically biased. Address data splitting, calibration considerations, and validation strategy.
Hints
Hint 1
For regression, consider what statistical quantity each loss function estimates at its optimum
Hint 2
Under severe imbalance, a small false positive rate translates to many more false positives than true positives in absolute terms
Hint 3
Focal loss reduces gradient contributions based on prediction confidence, not just class membership
Hint 4
Threshold selection requires a held-out set that is never used during model training or hyperparameter tuning
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Loss Functions, Metrics, and Threshold Selection
Part 1: MAE vs MSE in Regression
Statistical Targets
- MSE minimizes (prediction − actual)², driving the model toward the conditional mean of the target distribution
- MAE minimizes |prediction − actual|, pushing the model toward the conditional median
Outlier Sensitivity MSE squares the error, so an error of 50 receives 2,500× more penalty than an error of 1. A handful of extreme values can dominate the entire optimization, pulling predictions away from the typical data range.
MAE scales linearly with error magnitude. Each example contributes a bounded amount regardless of how far off it is, making the loss resistant to extreme values.
Gradient Dynamics For MSE, the gradient with respect to the prediction is proportional to the residual itself (∂L/∂ŷ = 2(ŷ − y)). This means:
- Gradients grow large for outliers, potentially destabilizing training
- Gradients naturally diminish as predictions approach targets, smoothing convergence
For MAE, the gradient is the sign of the residual (∂L/∂ŷ = sign(ŷ − y)). This creates:
- Constant gradient magnitude regardless of error size, preventing outlier domination
- No automatic gradient decay near the optimum, which can cause oscillation without learning rate schedules
- Technical issue at zero residual where the derivative is undefined (handled with subgradients)
Optimization in Practice MAE often requires careful learning rate tuning or smooth approximations like Huber loss (quadratic near zero, linear farther out) or log-cosh loss to avoid bouncing around the solution.
Concrete Example Consider predicting apartment rental prices. Most units rent for $1,200–$2,800 monthly, but data entry errors occasionally produce values like $120,000 (missing decimal) or $12 (misplaced decimal).
With MSE, the model distorts predictions across the entire dataset trying to reduce the squared error on these corrupted points. With MAE, the model learns the typical price range (the median), and the bad entries contribute only their sign, minimally affecting the overall fit.
When MSE Remains Appropriate If you need the expected value rather than a typical value—for instance, calculating total expected revenue or insurance reserves—MSE is the correct choice even with heavy tails, because business decisions depend on the mean.
Part 2: ROC-AUC vs PR-AUC at 1% Prevalence
What the Numbers Mean
- ROC-AUC = 0.90 indicates that given any random positive and negative example, the model assigns a higher score to the positive 90% of the time. This measures ranking quality.
- PR-AUC = 0.25 is much lower than ROC-AUC. Since a random classifier achieves PR-AUC equal to the prevalence (0.01), this represents ~25× improvement over random, but in absolute terms means roughly 1 in 4 flagged examples is actually positive when averaged across recall levels.
The Prevalence Paradox Consider a population of 10,000 cases: 100 positive, 9,900 negative.
Suppose the model achieves 60% true positive rate (TPR) at 5% false positive rate (FPR):
- True positives captured: 60
- False positives generated: 0.05 × 9,900 = 495
- Precision: 60/(60+495) = 10.8%
A 5% false positive rate seems small and produces strong ROC-AUC, but the negative class is 99× larger, so that 5% tail contains far more examples than the entire positive class.
Why This Happens ROC-AUC computes TPR and FPR separately within each class, making it insensitive to class distribution. It's particularly inflated by correctly rejecting the large mass of easy negatives with low scores.
Precision-Recall metrics combine both classes in the denominator (TP/(TP+FP)), making them directly sensitive to imbalance. The overwhelming number of negatives means even a well-separated score distribution will have negative-class tail overlap that dominates the high-score region.
Which Metric Matters For rare events (fraud, disease, defects), you act on the top-ranked predictions. Precision directly measures the cost of false alarms in that operational regime. PR-AUC or precision-recall curves at realistic operating points are more informative than ROC-AUC for imbalanced problems.
Part 3: Neural Network Architecture for Imbalanced Classification
Output and Loss Design
Use a single neuron with sigmoid activation and binary cross-entropy loss. Implement this with a numerically stable logit-based version (e.g., PyTorch's BCEWithLogitsLoss) that combines sigmoid and loss computation to avoid overflow.
The gradient of BCE with respect to the pre-activation logit z is simply (σ(z) − y), where σ is the sigmoid function. This produces gradient (p − 1) for positive examples and gradient p for negatives.
Approach 1: Class Weights Modify the loss to: L = −[w₁·y·log(p) + w₀·(1−y)·log(1−p)]
This multiplies the gradient contribution by w₁ for positives and w₀ for negatives. Common choices:
- w₁/w₀ = n_negative/n_positive (here, ≈99) to balance total gradient contribution per class
- w₁/w₀ = √(n_negative/n_positive) for a gentler correction
Effect: Every positive example's gradient is amplified by the weight ratio, giving rare class examples more influence. This is a uniform per-class rescaling.
Calibration side effect: Predicted probabilities become inflated by approximately the weight ratio. Correct this with: z′ = z − log(w₁/w₀), or recalibrate using Platt scaling or isotonic regression on a validation set.
Approach 2: Focal Loss FL = −α_t · (1 − p_t)^γ · log(p_t)
where p_t is the predicted probability for the true class, γ (typically 2) controls focusing strength, and α (typically 0.25 for the positive class) provides class balance.
Effect: The factor (1 − p_t)^γ down-weights examples the model is already confident about, regardless of class:
- Easy negative (p=0.02): factor = 0.98² ≈ 0.96
- Very easy negative (p=0.001): factor ≈ 0.999² ≈ 0.998
- Hard negative (p=0.60): factor = 0.40² = 0.16
- Misclassified positive (p=0.10): factor = 0.90² = 0.81
This prevents thousands of easy negatives from swamping the gradient signal. Training focuses on hard negatives and misclassified positives. The α parameter adds a mild class-level rebalancing on top.
Key Difference
Class weights rebalance by class membership. Focal loss rebalances by prediction difficulty, automatically down-weighting easy examples of both classes.
Both approaches distort probability calibration, so recalibration is essential before using predicted probabilities for threshold-based decisions.
Part 4: Rigorous Threshold Selection
Data Splitting Strategy
- Split data into three sets before any modeling: train (60%), validation (20%), test (20%)
- Use time-based splits for temporal data (fraud, credit, user behavior) to reflect distribution drift
- Stratify splits if using random assignment to preserve class ratios
Model Development
- Train the model on the training set; tune hyperparameters using cross-validation within this set only
- Calibrate predicted probabilities on the training set (using Platt scaling or isotonic regression) if using focal loss or class weights
Threshold Selection on Validation Set
- Generate predictions on the validation set using the frozen, calibrated model
- Sort predictions and evaluate precision and recall at each unique threshold value
- Select the threshold that maximizes recall while maintaining precision ≥ 0.50
Handling Noise With few positive examples, precision estimates are noisy. Strategies:
- Compute confidence intervals (Wilson score or bootstrap) and require the lower bound to exceed 0.50
- Target a safety margin (e.g., observed precision ≥ 0.55) to account for sampling variability
- Prefer thresholds where precision remains stable across a range of nearby values rather than a single spike
Final Evaluation Score the test set exactly once with the frozen model and selected threshold. Report precision, recall, and confidence intervals. This is your unbiased performance estimate.
Alternative: Nested Cross-Validation When data is limited:
- Outer loop: split data into K folds
- Inner loop: for each outer fold, use the remaining K-1 folds to train the model and select a threshold via cross-validation
- Apply that threshold to the held-out outer fold
- Aggregate outer-fold results for final performance estimate
Production Considerations
- If retraining on all data for deployment, select the final threshold from out-of-fold predictions from the complete pipeline to account for score distribution shifts
- Monitor precision in production continuously, as changes in true prevalence will move precision even with a fixed model and threshold
Common Mistakes to Avoid
- Using test data for threshold selection (optimistic bias)
- Selecting threshold on training data (severe overfitting)
- Ignoring confidence intervals with small validation sets
- Forgetting that class weights and focal loss destroy calibration
- Choosing threshold to maximize F1 without respecting business constraints