Handbooks / Machine Learning Basics / Chapter 1

ML Foundations

7 pages · ~5 min✓ Reviewed

Start here. Next up: Linear and Logistic Regression.

Machine Learning BasicsPage 1

Three Learning Paradigms

1. The Paradigms

  • Supervised: learn X → y from labelled examples
  • Regression = continuous value; classification = category
  • Unsupervised: structure in unlabelled X only
  • Clustering (k-means), PCA, anomaly detection
  • RL: agent learns a policy maximising cumulative reward
  • No labelled answers; feedback is delayed
  1. Agent
  2. Action
  3. Environment
  4. Reward

2. Compared

ParadigmFeedbackExample
Supervisedlabel per examplespam filter
Unsupervisedno labelscustomer segments
RLreward signalgame-playing agent
Quick test

Label, no label, or a reward?

3. Interview Point

  • House price? Regression: the target is continuous
  • RL vs supervised? RL gets delayed rewards, not a label per example
  • Clustering accuracy? No: there are no true labels to compare against
Machine Learning BasicsPage 2

Features, Labels and Data Splits

1. Data and the three sets

  • Features = input columns X
  • Label (target) = column y the model predicts
  • One row = one example
SetJob
Trainfits model parameters
Validationtunes hyperparameters, picks the model
Testone final unbiased estimate

2. Split choices

  • Typical split: 60/20/20 or 70/15/15
  • Imbalanced classes: stratified split
  • Time series: time-ordered split, never random

3. Data leakage

  • Scaler, imputer or feature selection fitted on full data leaks test information
  • Fit on train only, then transform val/test: use a Pipeline
python
from sklearn.pipeline import make_pipeline
pipe = make_pipeline(StandardScaler(), SVC())
pipe.fit(X_train, y_train)  # scaler sees train only
pipe.score(X_val, y_val)  # reuses train mean/std

preprocessing lives inside the pipeline

4. Interview Point

  • Why validation and test? Tuning on validation makes it optimistic; untouched test gives the honest score
  • Data leakage? Test information reaching training; fit preprocessing on train only, inside a Pipeline
  • Time-series split? Order by time: train on the past, test on the future
Machine Learning BasicsPage 3

Overfitting and Underfitting

1. Spot the Fit

CaseTrain errorVal error
Underfit: model too simplehighhigh
Overfit: memorises noiselowmuch higher
Good fitlowlow, close to train

2. Diagnose with Learning Curves

  1. Too simpleboth errors high
  2. Sweet spotval error minimum
  3. Too complextrain falls, val rises
  • Plot error vs training size, or error vs model complexity
  • Val error bottoms out, then rises as complexity grows
  • The train-val gap is the overfit symptom

3. Fixes

Overfit (big gap)Underfit (both high)
More dataMore capacity
Regularise: L1/L2, dropoutBetter features
Simpler modelLess regularisation
Early stoppingTrain longer
Fewer features—
Data fixes variance only

More rows cannot rescue a model too simple to fit them. Add capacity or features.

4. Interview Point

  • 99% train, 70% test? Overfit (large gap): add data, regularise, simplify, early stop
  • Early stopping? Halts training once val error starts rising, before noise is memorised
  • More data fixes underfitting? No: the model lacks capacity, so add capacity or features
Machine Learning BasicsPage 4

Bias-Variance Trade-off

1. Error Decomposition

  • Expected error = bias² + variance + irreducible noise
  • Noise is in the data: no model can remove it

2. Bias vs Variance

BiasVariance
CauseWrong assumptionsSensitive to the sample
SymptomMisses true patternPredictions swing between samples
MeansUnderfitOverfit
  1. More complexity
  2. Bias falls
  3. Variance rises
  4. Sweet spotlowest total

3. Models and Ensembles

Model / methodEffect
Linear regressionHigh bias, low variance
Deep decision treeLow bias, high variance
Bagging, random forestCut variance
BoostingCuts bias
Mistake

Zero train error is not low total error: past the sweet spot, variance wins.

4. Interview Point

  • Bias vs variance? Line on curved data misses it (bias); deep tree changes per sample (variance)
  • Why a trade-off? Complexity cuts bias but raises variance, so total error is U-shaped
  • Which ensemble? Bagging cuts variance; boosting cuts bias
Machine Learning BasicsPage 5

Cross-Validation in Practice

1. k-fold CV

  1. Splitk folds
  2. Traink-1 folds
  3. Validate1 fold
  4. Rotatek times
  5. Averagek scores
  • Usual choice: k=5 or 10
  • cross_val_score(model, X, y, cv=5) returns k scores

2. Splitters and Selection

DataSplitter
Class ratios matterStratifiedKFold (classifier default)
Time orderTimeSeriesSplit
Rows per entityGroupKFold
  • GridSearchCV uses CV for model selection and tuning
  • Keep an untouched test set for the final score
  • Leave-one-out: costly, high variance

3. Mistakes

  • Preprocessing outside the Pipeline (leakage)
  • Tuning on the test set
  • Reporting only the mean, ignoring the std across folds

4. Interview Point

  • Why CV, not one split? Every row validates once; the mean is steadier.
  • When is plain k-fold wrong? Imbalanced classes, time data, grouped rows.
  • Nested CV? Inner loop tunes, outer loop scores; avoids optimistic bias.
Machine Learning BasicsPage 6

ML Fundamentals Cheat Sheet

1. Paradigms

DataTask
SupervisedX + labels yregression, classification
UnsupervisedX onlyclustering, PCA
RLagent + rewardmaximise cumulative reward

2. Splits

  1. Trainfit parameters
  2. Validationtune
  3. Testuse once
  • Stratify for classes; order by time for time series
  • Fit preprocessing on train only, then transform val/test

3. Diagnose and Fix

UnderfitOverfit
Errorstrain and val both hightrain low, val high
Causehigh biashigh variance
Fixmore capacity, better features, less regularisationmore data, regularise, simplify, early stop
Test set

Touch it once. Tuning on it leaks.

4. Interview Point

  • Workflow? Split, fit pipeline on train, tune on val or CV, test once.
  • Pick a model? Compare CV mean and std; prefer the simpler on a tie; confirm once on test.
  • Cut variance? More data, regularisation, bagging or early stopping.
Machine Learning BasicsPage 7

Check yourself

Train accuracy is 99%, test accuracy 70%. Diagnosis and one fix?
  • Overfitting (high variance)
  • The big train-test gap is the symptom
  • Regularise, simplify or add data
Spot the bug: the scaler is fitted before splitting. What breaks?
  • Data leakage: test statistics shape the scaler
  • The score looks better than reality
  • Fit on train only, or use a Pipeline
scaler = StandardScaler().fit(X)
X_tr, X_te = train_test_split(scaler.transform(X))
Train error 30%, validation error 31%. Will doubling the data help?
  • No: both errors high and close means underfitting (high bias)
  • Add capacity or better features instead
Why is random k-fold wrong for daily sales data?
  • Future rows land in training folds, so the model peeks ahead
  • The score is too optimistic
  • Use TimeSeriesSplit