Cheat sheet · Module 1

Cheat sheet: ML foundations

Machine Learning · Cheat sheet · ML foundations

Open the moduleModule quiz

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 λR(θ)\lambda R(\theta)) as a stand-in for the loss on unseen data (expected risk). Parameters are learned by the optimizer; hyperparameters (λ\lambda, 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 σ2\sigma^2. 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 λ∥w∥22\lambda\lVert w\rVert_2^2, closed form w^=(X⊤X+λI)−1X⊤y\hat w=(X^{\top}X+\lambda I)^{-1}X^{\top}y. Lasso adds λ∥w∥1\lambda\lVert w\rVert_1.

  • 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 λ\lambda underfits. Choose it at the validation minimum. Standardize features first. Ridge and Lasso scale the penalty differently in scikit-learn, so the same alpha is not the same strength.
  • Correlated features: lasso tends to pick one at random; elastic net can pick both.

Linear regression: J(w)=1n∥Xw−y∥2J(w)=\tfrac1n\lVert Xw-y\rVert^2 is maximum likelihood under Gaussian noise. Normal equation X⊤X w=X⊤yX^{\top}X\,w=X^{\top}y; the residual is orthogonal to every feature column.

  • Use the closed form when the problem is small. Least squares costs O(nd2)O(n d^2). 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 R2R^2 or validation error for new features (training R2R^2 never falls when a feature is added).

Logistic regression: p=σ(w⊤x+b)p=\sigma(w^{\top}x+b), log loss −[ylog⁡p+(1−y)log⁡(1−p)]-[y\log p+(1-y)\log(1-p)] (Bernoulli maximum likelihood).

  • Gradient: ∇wℓ=(p−y) x\nabla_w\ell=(p-y)\,x and ∂ℓ/∂b=p−y\partial\ell/\partial b=p-y. The sigmoid’s p(1−p)p(1-p) cancels the log denominators. Softmax with cross-entropy gives softmax output minus one-hot label.
  • Squared error on a sigmoid leaves the extra p(1−p)p(1-p) 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 xjx_j multiplies the odds by ewje^{w_j}. 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:

TaskLossNote
RegressionSquared errorMinimised by the mean; sensitive to outliers
Regression with outliersAbsolute error, HuberAbsolute is minimised by the median; Huber is quadratic for small errors, linear for large
Binary or multiclassCross-entropy (log loss)Gives probabilities
Margin classifier (SVM)Hinge max⁡(0,1−m)\max(0,1-m)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: w←w−η∇J(w)w\leftarrow w-\eta\nabla J(w). On a quadratic with curvature hh it converges only if η<2/h\eta<2/h; exactly 2/h2/h 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: v←βv+gv\leftarrow\beta v+g, w←w−ηvw\leftarrow w-\eta v. Agreeing gradients add, flipping gradients cancel. β=0\beta=0 is plain descent. It needs β\beta tuned together with η\eta.
  • Adam: running averages of the gradient (mm) and its square (vv), bias-corrected, step η m^/(v^+ϵ)\eta\,\hat m/(\sqrt{\hat v}+\epsilon). PyTorch defaults: η=0.001\eta=0.001, β1=0.9\beta_1=0.9, β2=0.999\beta_2=0.999, ϵ=10−8\epsilon=10^{-8}. On the first step every parameter moves about η\eta whatever its gradient scale.

Feature scaling: the condition number of X⊤X/nX^{\top}X/n 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: (p−y) x(p-y)\,x.
  • Why not MSE on a sigmoid: the p(1−p)p(1-p) 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.