Cheat sheet · Module 1
Cheat sheet: ML foundations
Machine Learning · Cheat sheet · ML foundations
The pattern: every model here is a function, a loss and an optimizer. Training minimises the average loss on the training set (empirical risk, plus an optional penalty ) as a stand-in for the loss on unseen data (expected risk). Parameters are learned by the optimizer; hyperparameters (, learning rate, tree depth) are set by you and chosen on validation data.
Splits: train fits the weights, validation chooses hyperparameters and models, test is used once at the end. Every look at validation leaks a little. Fit scalers and imputers on the training fold only (a Pipeline does this inside each cross-validation fold). With small data use k-fold cross-validation and keep a test set anyway.
- Imbalanced classes: stratified k-fold. Several rows per user or patient: group k-fold. Data ordered in time: forward-chaining split.
Bias and variance: for squared error, expected error = bias squared + variance + irreducible noise . The noise is a floor under validation error; training error of any fitted model sits slightly below it.
- Train error high (judged against a baseline or the floor) means bias: richer model, better features, less regularization. More data of the same kind does not help.
- Train error low, validation much higher means variance: more data, regularization, simpler model, early stopping. A bigger model does not help.
- Learning curves: curves flat and close together at a high level is bias; curves that start apart and converge as data grows is variance, where more data helps.
Regularization: ridge adds , closed form . Lasso adds .
- L2 pushes back in proportion to the weight, so weights shrink but never reach zero. L1 subtracts a fixed amount, so weights reach exactly zero (feature selection).
- Priors: L2 is a Gaussian prior, L1 a Laplace prior (lasso is the posterior mode).
- Too much underfits. Choose it at the validation minimum. Standardize features first.
RidgeandLassoscale the penalty differently in scikit-learn, so the samealphais not the same strength. - Correlated features: lasso tends to pick one at random; elastic net can pick both.
Linear regression: is maximum likelihood under Gaussian noise. Normal equation ; the residual is orthogonal to every feature column.
- Use the closed form when the problem is small. Least squares costs . Avoid it for huge feature counts or streaming data.
- Nearly dependent columns make the estimate high-variance (unstable coefficients across samples). Predictions stay stable while coefficients swing and can flip sign. Ridge stabilises it.
- Checks: residual plot (linearity, independent errors, normal residuals, equal variance), VIF for collinearity, adjusted or validation error for new features (training never falls when a feature is added).
Logistic regression: , log loss (Bernoulli maximum likelihood).
- Gradient: and . The sigmoid’s cancels the log denominators. Softmax with cross-entropy gives softmax output minus one-hot label.
- Squared error on a sigmoid leaves the extra factor, so a confidently wrong prediction gets almost no gradient and learning stalls.
- Log loss is convex in the weights, so every local minimum is global; unique only with strict convexity (L2 penalty, or full-rank non-separable data).
- Weights are log-odds: a one-unit rise in multiplies the odds by . The 0.5 threshold is a default; set it from the cost of each mistake.
- Perfectly separable data: no finite minimiser, weights grow without bound. An L2 penalty fixes it.
Choosing a loss:
| Task | Loss | Note |
|---|---|---|
| Regression | Squared error | Minimised by the mean; sensitive to outliers |
| Regression with outliers | Absolute error, Huber | Absolute is minimised by the median; Huber is quadratic for small errors, linear for large |
| Binary or multiclass | Cross-entropy (log loss) | Gives probabilities |
| Margin classifier (SVM) | Hinge | Score only; zero loss past margin 1 |
Ask why the outliers exist: a corrupted label is a data problem; a real extreme value may be what the business needs forecast.
Gradient descent: . On a quadratic with curvature it converges only if ; exactly oscillates forever.
- Loss rising or NaN: rate too high, unscaled inputs, or a numerical bug such as log of zero (gradient clipping is a guard). Barely moving: rate too low, a loss or label bug, or unscaled features. Bouncing at a plateau: steps are too big to settle, so lower or decay the rate.
- Mini-batches are the default (32 to 256 cited as typical). Noisy steps need a smaller or decaying rate, so tune batch size and rate together.
- Sanity check: drive the loss to about zero on ten rows. If you cannot, it is a bug, not tuning.
Momentum and Adam
- Momentum: , . Agreeing gradients add, flipping gradients cancel. is plain descent. It needs tuned together with .
- Adam: running averages of the gradient () and its square (), bias-corrected, step . PyTorch defaults: , , , . On the first step every parameter moves about whatever its gradient scale.
Feature scaling: the condition number of sets how slow gradient descent is. Standardising shrinks it (in the lesson’s experiment, from about 23,200 raw to about 1.12). Needed for gradient descent, penalties and distance-based methods. Trees and unpenalised closed-form least squares do not need it. Fit the scaler on training data only.
Quick answers
- Generalization: minimise empirical risk, judge on unseen data; train fits, validation chooses, test judges once.
- Train 99%, validation 80%: check leakage and a mismatched validation set first, then more data, regularization, simpler model, early stopping.
- Why L1 gives zeros: constant-size push versus a push proportional to the weight.
- Logistic gradient: .
- Why not MSE on a sigmoid: the factor kills the gradient when the model is confidently wrong.
- Normal equation or gradient descent: closed form for small, well-conditioned problems; gradient descent for large, streaming or non-closed-form models.
Traps
“More data fixes everything” (not for bias) · “regularization always helps” (too much underfits) · tuning on the test set · scaling before splitting · reading train error below the noise floor as overfitting · comparing alpha across Ridge and Lasso · “Adam needs no tuning” · treating the 0.5 threshold as fixed.