Cheat sheets

Model Evaluation, Bias-Variance and Tuning

Splits and cross-validation, metric formulas, bias-variance diagnosis, search strategies and imbalanced classes.

  • Concepts and terms
  • Tasks and commands
  • Annotated code
  • Diagrams
  • Defaults and numbers
  • Troubleshooting
  • Questions and tips

Source

Diagnose train and test error#

SymptomCauseFix
High train error, high test errorHigh biasMore features, complex model, less regularization
Low train error, high test errorHigh varianceMore data, regularization, simpler model
Train error falls, test error risesOverfitting in progressEarly stopping
Both curves flat and highBias. More data will not helpChange the model
Large gap, validation still fallingVariance that data can fixCollect more data
99% accuracy, zero positives caughtClass imbalanceF1, AUPRC or MCC
Validation score too optimisticScaler fit before the splitPreprocess inside a Pipeline
Best value at the search edgeRange too narrowWiden the search space

From Lesson 02.10, Lesson 02.09, Lesson 02.12, Lesson 02.17

Split, tune, report#

validateFull datasetTrain set60-70%Validation set15-20%Test set15-20%, use onceFit modelTunehyperparametersselect modelsFinal modelReport performancevalidateFulldatasetTrainset60-70%Validationset15-20%Test set15-20%,use onceFitmodelTunehyperparametersselectmodelsFinalmodelReportperformance

From Lesson 02.09

Metric formulas#

Accuracy
(TP + TN) / (TP + TN + FP + FN). Misleading with imbalanced classes.
Precision
TP / (TP + FP). Use it when false positives are costly.
Recall
TP / (TP + FN). Use it when false negatives are costly.
F1
2PR / (P + R), the harmonic mean of precision and recall.
F-beta
(1+\beta^2) P R / (\beta^2 P + R). \beta > 1 weights recall. F2 is common for fraud.
MCC
(TP \cdot TN - FP \cdot FN) / \sqrt{\ldots}. It goes from -1 to +1.
AUC-ROC
0.5 is random guessing, 1.0 is perfect separation.
AUPRC
a random model scores the positive class rate.
RMSE and MAE
RMSE is \sqrt{\text{MSE}} in target units. MAE is robust to outliers.
Decomposition
expected error = \text{Bias}^2 + \text{Variance} + \sigma^2.

From Lesson 02.09, Lesson 02.17, Lesson 02.10

Fix a model step by step#

1Traincompute the train error and the test error.2Both higha bias problem. Go to step 4.3Train low, test higha variance problem. Plot a learning curve.Regularize if data does not help.4Validation curvesweep the main complexity knob. Find the sweetspot.5Learning curveplot it at the sweet spot. A large gap needsdata or regularization.6Alpha sweeptry Ridge or Lasso alphas with cross_val_score.Keep the lowest CV error.

From Lesson 02.10

Cross-validate and tune#

scores = cross_val_score(model, X, y, cv=StratifiedKFold(5), scoring="f1")
param_dist = {
"learning_rate": loguniform(1e-4, 0.5),log scale
"max_depth": randint(2, 10),
"n_estimators": randint(50, 500),
}
search = RandomizedSearchCV(GradientBoostingRegressor(), param_dist,
n_iter=100, cv=5, scoring="neg_mean_squared_error", n_jobs=-1)
search.fit(X_train, y_train)
search.best_params_best settings
outer_scores = cross_val_score(inner_cv, X, y, cv=5, scoring="neg_mean_squared_error")

From Lesson 02.09, Lesson 02.12

Search strategies#

CommandWhat it does
Grid searchEvery combination. Cost grows exponentially
Random searchSamples distributions. More unique values per budget
Bayesian optimizationSurrogate plus acquisition. 2-5x fewer evaluations
HyperbandMany configs on small budgets. 10-50x faster
MedianPrunerStops a trial worse than the median at that step
GridSearchCVExhaustive grid with cross-validation
RandomizedSearchCVRandom search with CV. n_jobs=-1 uses all cores
trial.suggest_floatOptuna sample. Add log=True for lr

From Lesson 02.12

Pick an imbalance fix#

SettingDefaultNote
Mild, under 70/30class weightsTry them first
Moderate, 70/30 to 95/5SMOTE + class weightsOr SMOTE with threshold tuning
Severe, over 95/5combine multiple strategiesSMOTE, class weights and threshold
Under 1000 samplesOversample or SMOTE, avoid undersamplingSmall data
1000-10000 samplesSMOTE + threshold tuningMedium data
Over 10000 samplesUndersampling OK, or class weightsLarge data

From Lesson 02.17

Numbers to know#

SettingDefaultNote
K folds5Or 10
Decision threshold0.5Lower it for rare positives
Random search trials6095% chance to land within 5% of the optimum
Hyperband start81Configs at 1 epoch. Keep the top third
Nested CV fits6755 outer x 5 inner x 27 grid points
Bootstrap fits200n_bootstrap=200 in the decomposition
SMOTE k5n_synthetic=100
Positive class weight10.01000 samples, 50 positive

From Lesson 02.09, Lesson 02.12, Lesson 02.17, 02.10 code/bias_variance.py, 02.17 code/imbalanced.py

Questions#

Why stratified folds?
Each fold keeps the class ratio of the full dataset.
Why use the test set once?
Each look and adjust turns it into a second validation set.
Why random over grid?
Only 1-2 of 6 hyperparameters usually matter.
Bagging or boosting?
Bagging for high variance. Boosting for high bias.
Class weights or oversampling?
Weights equal oversampling in expectation, with no duplicates.
Where is the worst capacity?
At the interpolation threshold, where parameters are near samples.
How do I report a final score?
Use nested CV or a test set you never touch while tuning.

From Lesson 02.09, Lesson 02.10, Lesson 02.12, Lesson 02.17

Tips#

  • Split first, then preprocess.
  • Tune the learning rate first. Search it on a log scale.
  • Use early stopping in place of tuning n_estimators.
  • Spend 60% of the tuning budget on the top 2 hyperparameters.
  • Start with library defaults. Coarse search 20-50 trials, then fine search 50-100.
  • Sweep thresholds from 0.0 to 1.0 on validation data. Keep the best F1.

From Lesson 02.09, Lesson 02.12, Lesson 02.17

From-scratch functions#

TaskCode
Stratified foldsstratified_kfold_split(y, k=5, seed=42)
ROC areaauc_roc(y_true, y_scores)
Synthetic minority rowssmote(X_minority, k=5, n_synthetic=100)
Balanced class weightscompute_class_weights(y)
Best cutoff by F1find_optimal_threshold(y_true, y_probs)

From 02.09 code/evaluation.py, 02.17 code/imbalanced.py