← All Google Cloud AI guidesFundamentals · 2.3, 3.2

ML fundamentals 2: bias-variance, regularization and evaluation metrics

The model half of ML fundamentals: underfitting vs overfitting, learning curves, regularization and ensembles, training-loop problems, validation strategies, and evaluation metrics in depth, including why PR AUC beats ROC AUC on imbalanced data, threshold selection, calibration, and regression and ranking metrics. Two calculators make the numbers concrete.

1. Bias, variance and generalization

A model's job is to generalize: do well on data it hasn't seen. Its error on new data comes from three sources:

SourceMeaningSymptom
BiasThe model is too simple, or its assumptions are wrong, so it misses real patternsUnderfitting: high error on training and validation data
VarianceThe model is too sensitive to the particular training sample; it learns noiseOverfitting: low training error, much higher validation error
Irreducible errorNoise in the labels or missing information no model can recoverA floor that more modelling can't break

Making a model more flexible usually lowers bias and raises variance; constraining it does the reverse. The goal is the capacity where validation error is lowest.

A student who memorizes past exam answers (high variance) aces practice papers and fails new questions. A student who learned only one rule of thumb (high bias) does badly on both. You want the one who learned the underlying ideas.

2. Diagnosing with learning curves

What you seeDiagnosisTry
Training and validation error both high, close togetherHigh bias (underfitting)A bigger or more flexible model, better features, less regularization, train longer
Training error low, validation error much higherHigh variance (overfitting)More data, augmentation, regularization (L2, dropout), early stopping, simpler model, fewer features
Validation loss falls, then rises while training loss keeps fallingOverfitting starts at the minimumEarly stopping at the best validation epoch; restore those weights
Gap closes as training data grows, validation still improvingMore data will helpCollect or label more data
Both curves flat as data grows, error still highMore data won't helpChange the model or features
Validation better than trainingRegularization active only in training (dropout), easier validation set, or leakageCheck the split and leakage before celebrating
Loss jumps around or divergesLearning rate too high, bad data, exploding gradientsLower the learning rate, clip gradients, check inputs

3. Regularization and capacity control

TechniqueHow it reduces overfittingNotes
L2 (ridge, weight decay)Penalizes large weights (sum of squares); spreads weight across featuresDefault choice; BigQuery ML l2_reg
L1 (lasso)Penalizes absolute weights; drives some to exactly zeroSparse models and feature selection; l1_reg
Elastic netL1 + L2Correlated features plus sparsity
DropoutRandomly zeroes neurons during trainingNeural networks; inactive at inference
Early stoppingStops when validation loss stops improvingCheap and effective; BigQuery ML early_stop
Data augmentationAdds realistic variationsImages, audio, text
Simpler modelFewer layers, shallower trees (max_tree_depth), fewer featuresAlso cheaper to serve
Tree constraintsMinimum samples per leaf, subsampling rows and columns, learning rate (shrinkage)Gradient boosting's main controls
Batch normalizationStabilizes training; mild regularizing effectMainly an optimization aid

Ensembles

MethodIdeaMainly reduces
Bagging (random forest)Average many models trained on bootstrap samplesVariance
Boosting (XGBoost, gradient-boosted trees)Each new model fixes the previous ones' errorsBias (and variance with shrinkage and subsampling)
StackingA meta-model combines different modelsBoth; more complexity
"Bagging calms variance, boosting beats bias."

4. Training-loop problems

ProblemSignFix
Learning rate too highLoss oscillates, explodes or becomes NaNLower it; learning-rate schedules and warmup
Learning rate too lowLoss falls very slowlyRaise it; adaptive optimizers (Adam)
Vanishing gradientsEarly layers stop learning in deep networksReLU-family activations, residual connections, batch norm, good initialization
Exploding gradientsHuge updates, NaN loss (common in RNNs)Gradient clipping, lower learning rate, normalization
Dead ReLUsMany neurons always output zeroLeaky ReLU, lower learning rate
NaN lossBad inputs (NaN, inf), log(0), division by zeroValidate data, add epsilons, clip
Batch size effectsLarge batches: faster per epoch, may generalize worse; small: noisier, slowerScale the learning rate with batch size; tune both

5. Validation strategies

StrategyUse when
Hold-out validationPlenty of data; fast
k-fold cross-validationSmall or medium data; more reliable estimates (train k times, each fold validates once)
Stratified k-foldClassification, especially imbalanced
Group k-foldMany rows per entity
Time-series (rolling or expanding window) validationForecasting; never shuffle; also called backtesting
Nested cross-validationUnbiased estimate when also tuning hyperparameters
Every choice made by looking at a dataset (features, hyperparameters, thresholds) "uses up" that dataset. Make those choices on validation data; report the final number on untouched test data.

6. Classification metrics

Predicted positivePredicted negative
Actually positiveTrue positive (TP)False negative (FN), a miss
Actually negativeFalse positive (FP), a false alarmTrue negative (TN)
MetricFormulaAnswersPrefer when
PrecisionTP / (TP + FP)When it says positive, how often is it right?False positives are costly: blocking good customers, spam filtering real mail
Recall (sensitivity, true positive rate)TP / (TP + FN)Of all real positives, how many did it find?Misses are costly: fraud, disease screening, safety defects
SpecificityTN / (TN + FP)Of real negatives, how many were cleared?Medical testing pairs it with sensitivity
False positive rate (FPR)FP / (FP + TN) = 1 − specificityHow often negatives are flaggedThe x-axis of the ROC curve
F12PR / (P + R)Balance of precision and recallOne number when both matter; F-beta weights recall β times as much
Accuracy(TP + TN) / allFraction correctOnly for roughly balanced classes with similar error costs
Log loss (cross-entropy)−mean(y·log p + (1−y)·log(1−p))How good the probabilities areProbabilities are used directly; punishes confident mistakes

Multi-class averaging

7. ROC AUC vs PR AUC: why imbalance changes the answer

Both curves sweep the decision threshold from high to low.

Worked example

1,000,000 transactions, 1% fraud (10,000 positives). A model at some threshold has recall 80% and FPR 1%.

QuantityValue
True positives0.80 × 10,000 = 8,000
False positives0.01 × 990,000 = 9,900
Precision8,000 / 17,900 ≈ 45%

On the ROC curve, (FPR 1%, TPR 80%) looks excellent. But more than half the alerts are false. If fraud were 0.1%, the same TPR and FPR would give precision ≈ 7%. ROC doesn't move when prevalence changes, because both of its rates are computed within one class each; precision mixes the two classes, so PR curves show what an analyst reviewing alerts experiences.

Imbalanced data: use PR AUC (and precision at a required recall, or recall at a required precision). ROC AUC is fine for balanced classes and for comparing ranking quality, but on rare-event problems it can look great while the model is unusable.
PR AUC values aren't comparable across datasets with different positive rates; the baseline moves with prevalence. Compare models on the same test set.

8. Prevalence calculator: ROC point to precision

Pick a recall (true positive rate) and false positive rate, then change the positive rate to see what precision users would actually experience.

9. Choosing the threshold

Models output scores; a threshold turns scores into decisions. The default 0.5 is arbitrary. Choose the threshold on validation data from what each error costs.

  1. Price each error: a missed fraud costs the transaction amount; a false alarm costs review time and customer friction.
  2. For each candidate threshold, compute expected cost = FN × costFN + FP × costFP.
  3. Pick the minimum, or the threshold that meets a hard constraint (recall ≥ 95%, or at most 500 alerts per day for the review team).

10. Confusion-matrix calculator

Enter counts at your current threshold to get every metric and which way to move the threshold.

11. Calibration

A model is calibrated if, among cases it scores 0.8, about 80% are positive. Ranking (AUC) can be excellent while probabilities are badly off.

TopicDetail
Why it mattersExpected-cost decisions, risk scores shown to people, combining models, pricing
What breaks itClass weights, resampling, boosting, overconfident neural networks, distribution shift
How to checkReliability diagram (predicted vs observed rate per bin), Brier score, log loss
How to fixPlatt scaling (logistic fit on scores), isotonic regression (more flexible, needs more data), temperature scaling for neural networks; fit on validation data

12. Regression and forecasting metrics

MetricMeaningPrefer when
MAE (mean absolute error)Average absolute miss, in the target's unitsRobust to outliers; easy to explain
RMSE (root mean squared error)Squares errors, so large misses count much moreBig errors are disproportionately bad
MSERMSE squared; common training lossOptimization
Huber lossSquared for small errors, absolute for largeTraining with some outliers
R²Share of variance explained (1 is perfect, 0 equals predicting the mean)Comparing to a mean baseline
MAPEMean absolute percentage errorScale-free comparison; breaks near zero actuals, penalizes over-forecasts more
WAPE / sMAPEWeighted or symmetric percentage errorsForecasting with intermittent or near-zero demand
RMSLERMSE on log valuesRelative errors matter; under-prediction worse than over
Quantile (pinball) loss, interval coverageQuality of prediction intervalsInventory and capacity planning

13. Ranking, recommendation and business metrics

MetricMeaning
Precision@k, recall@kQuality of the top k results
MAP (mean average precision)Rewards putting relevant items early, averaged over queries
NDCG (normalized discounted cumulative gain)Graded relevance with a position discount
MRR (mean reciprocal rank)1 / rank of the first relevant result
Coverage, diversity, noveltyWhether recommendations go beyond the popular few
Online metricsClick-through rate, conversion, revenue per session, retention: measured by A/B tests
Offline metrics choose candidates; online experiments decide launches. A model can improve NDCG offline and still lose an A/B test on revenue.

14. "What does this training curve mean?" chooser

Pick an item to see what it means, why, and the tempting wrong choice.

Pick one above.

15. Scenarios

Exam-style situations: how to diagnose each one, the likely cause and the fix.

16. Searchable reference

ItemMeaning

17. Flashcards (click to flip)

18. Common gotchas in one list

  1. Both errors high = bias; big gap = variance. The fixes are opposite.
  2. More data fixes variance, not bias.
  3. Regularization and early stopping fight overfitting; they make underfitting worse.
  4. PR AUC for imbalanced data. ROC AUC ignores prevalence and can look great while precision is terrible.
  5. PR AUC's random baseline is the positive rate, not 0.5.
  6. Never keep the 0.5 threshold by default; pick it from error costs on validation data.
  7. Precision when false positives hurt, recall when misses hurt.
  8. Class weights and resampling break calibration; recalibrate before using probabilities.
  9. Tuning on the test set makes the test score optimistic.
  10. Time series: no shuffling; backtest with rolling windows.
  11. RMSE punishes big misses; MAE is robust; MAPE breaks near zero.
  12. Macro averages expose rare-class failure that accuracy hides.
  13. Offline metrics pick candidates; A/B tests decide launches.
  14. Validation better than training: check dropout effects and leakage before celebrating.

19. Practice quiz (24 questions)

Score: 0 / 0
← ML fundamentals 1: data, features, imbalanceNext: BigQuery ML, AutoML and AI APIs →