Skip to content
ml-recall

Topic notes

ML Fundamentals

How models learn from data and how to check that they generalize — learning paradigms, train/validation/test splits, over- and underfitting, bias–variance, cross-validation and tuning.

6-min read AI-checked

Practise 162 questions Take a test

Key ideas

Learning paradigms1

Parameters vs hyperparameters. Parameters (weights, biases) are fitted by training. Hyperparameters (learning rate, batch size, tree depth, kk in kk-NN, regularization strength) are not learned by the estimator; you set them and pick them by validation6.

Generalization2. Training error is the average loss on the data the model was fitted to; generalization error is the expected loss on new data from the same distribution. The usual argument that one predicts the other assumes training and test examples are drawn i.i.d. from one distribution. A flexible enough model can drive the training error to zero and still generalize badly, so the training error alone proves nothing.

Three splits4

split used for rule
training fitting the parameters usually the largest part
validation choosing hyperparameters, features, stopping point reusable, but wears out with reuse
test one final estimate of quality look at it once; never tune on it

A good test set is large enough for a statistically meaningful result, representative of the data the model will meet, and contains no duplicates of training examples4. Splitting a fixed dataset is a trade-off: every test example is one less training example. Shuffle before splitting so the parts share one distribution — except for time-ordered data: shuffled, the model is validated on samples artificially close in time to its training samples and the score is inflated, so split by time5.

Diagnosing a fit2

Bias–variance3. Bias is error from wrong assumptions (a model family too simple to express the truth); variance is sensitivity to the particular training sample; the noise term is irreducible. Flexibility (higher polynomial degree, more features, smaller kk in kk-NN) lowers bias and raises variance; regularization such as ridge adds bias to cut variance; a larger training set mainly lowers variance3. Small training sets make overfitting more likely, and too simple a model class makes underfitting more likely2.

Cross-validation5. kk-fold CV splits the training data into kk folds, trains kk models (each on k−1k-1 folds), scores each on its held-out fold and averages2. It gives a more robust estimate than one split at kk times the cost — linear in kk — and adds no data. Leave-one-out is k=nk = n; stratified folds keep the class proportions; group folds keep all samples of one patient or device on one side; time series use forward-chaining splits5. Preprocessing goes inside the CV loop (a pipeline).

Hyperparameter search6. Grid search evaluates every combination, so its cost multiplies with each hyperparameter (10 hyperparameters with 4 values each: 410=1,048,5764^{10} = 1{,}048{,}576 settings). Random search samples a fixed budget (n_iter) of settings; the budget does not grow with the number of hyperparameters, and adding ones that don't matter wastes no trials. Neither method guarantees the optimum, and different random-search runs can return different winners.

Around the model1

Formulas

Bias–variance decomposition of the expected squared error at xx, for y=f(x)+εy = f(x) + \varepsilon with Var⁡(ε)=σ2\operatorname{Var}(\varepsilon) = \sigma^23:

E[(y−f^(x))2]=(E[f^(x)]−f(x))2+Var⁡[f^(x)]+σ2\mathbb{E}\big[(y - \hat f(x))^2\big] = \big(\mathbb{E}[\hat f(x)] - f(x)\big)^2 + \operatorname{Var}\big[\hat f(x)\big] + \sigma^2

Grid search with m1,…,mhm_1, \dots, m_h values per hyperparameter and kk-fold CV: k∏jmjk \prod_j m_j fits, plus one final refit on all training data.

Worked example

Optimization bias. Answer a 20-question true/false quiz at random: the expected score is 50%. Take 5 attempts and keep only the best: the expected best score is about 62.9%; the best of 50 attempts, about 74.6%. On a fresh quiz each "winner" still scores 50%. Picking the best of many hyperparameter settings on one small validation set inflates the winning score in the same way — which is why the reported number comes from held-out data that the search never saw2,6.

Cost. A grid of 4×5×3=604 \times 5 \times 3 = 60 settings with 5-fold CV costs 60×5=30060 \times 5 = 300 fits, plus 1 refit: 301 calls to fit.

In code

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_validate
from sklearn.tree import DecisionTreeClassifier

X, y = load_breast_cancer(return_X_y=True)
scores = []
for depth in [1, 4, None]:                       # None: grow the tree fully
    cv = cross_validate(DecisionTreeClassifier(max_depth=depth, random_state=0),
                        X, y, cv=5, return_train_score=True)
    scores.append((depth, float(cv["train_score"].mean().round(3)),
                   float(cv["test_score"].mean().round(3))))
print(scores)  # [(1, 0.924, 0.9), (4, 0.985, 0.916), (None, 1.0, 0.917)]

(depth, mean training accuracy, mean validation accuracy): the one-split stump scores lower on both with a small gap; the fully grown tree is perfect on its training folds and has the largest gap.

Common pitfalls

References

  1. Google for Developers: Machine Learning Glossary — Entries: supervised machine learning; unsupervised machine learning; self-supervised learning; reinforcement learning (RL); overfitting; underfitting; early stopping; baseline; heuristic; proxy labels; static; dynamic; offline inference; online inference; feedback loop; recommendation system; candidate generation; collaborative filtering; permutation variable importances
  2. Dive into Deep Learning — Sec. 3.6 Generalization (3.6.1 Training Error and Generalization Error, 3.6.2 Underfitting or Overfitting?, 3.6.3 Model Selection, 3.6.3.1 Cross-Validation)
  3. Wikipedia: Bias–variance tradeoff — Bias–variance decomposition of mean squared error; Approaches
  4. Machine Learning Crash Course — Datasets: Dividing the original dataset (Training, validation, and test sets; Additional problems with test sets)
  5. scikit-learn User Guide — Sec. 3.1 Cross-validation: evaluating estimator performance (3.1.2 Cross validation iterators, 3.1.3 A note on shuffling)
  6. scikit-learn User Guide — Sec. 3.2 Tuning the hyper-parameters of an estimator (3.2.1 Exhaustive Grid Search, 3.2.2 Randomized Parameter Optimization, 3.2.4.4 Model selection: development and evaluation)