Handbooks / Machine Learning Basics / Chapter 1
ML Foundations
7 pages · ~5 min✓ Reviewed
Start here. Next up: Linear and Logistic Regression.
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
- Agent
- Action
- Environment
- Reward
2. Compared
| Paradigm | Feedback | Example |
|---|---|---|
| Supervised | label per example | spam filter |
| Unsupervised | no labels | customer segments |
| RL | reward signal | game-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
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
| Set | Job |
|---|---|
| Train | fits model parameters |
| Validation | tunes hyperparameters, picks the model |
| Test | one 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
Overfitting and Underfitting
1. Spot the Fit
| Case | Train error | Val error |
|---|---|---|
| Underfit: model too simple | high | high |
| Overfit: memorises noise | low | much higher |
| Good fit | low | low, close to train |
2. Diagnose with Learning Curves
- Too simpleboth errors high
- Sweet spotval error minimum
- 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 data | More capacity |
| Regularise: L1/L2, dropout | Better features |
| Simpler model | Less regularisation |
| Early stopping | Train 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
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
| Bias | Variance | |
|---|---|---|
| Cause | Wrong assumptions | Sensitive to the sample |
| Symptom | Misses true pattern | Predictions swing between samples |
| Means | Underfit | Overfit |
- More complexity
- Bias falls
- Variance rises
- Sweet spotlowest total
3. Models and Ensembles
| Model / method | Effect |
|---|---|
| Linear regression | High bias, low variance |
| Deep decision tree | Low bias, high variance |
| Bagging, random forest | Cut variance |
| Boosting | Cuts 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
Cross-Validation in Practice
1. k-fold CV
- Splitk folds
- Traink-1 folds
- Validate1 fold
- Rotatek times
- Averagek scores
- Usual choice: k=5 or 10
cross_val_score(model, X, y, cv=5)returns k scores
2. Splitters and Selection
| Data | Splitter |
|---|---|
| Class ratios matter | StratifiedKFold (classifier default) |
| Time order | TimeSeriesSplit |
| Rows per entity | GroupKFold |
GridSearchCVuses 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.
ML Fundamentals Cheat Sheet
1. Paradigms
| Data | Task | |
|---|---|---|
| Supervised | X + labels y | regression, classification |
| Unsupervised | X only | clustering, PCA |
| RL | agent + reward | maximise cumulative reward |
2. Splits
- Trainfit parameters
- Validationtune
- Testuse once
- Stratify for classes; order by time for time series
- Fit preprocessing on train only, then transform val/test
3. Diagnose and Fix
| Underfit | Overfit | |
|---|---|---|
| Errors | train and val both high | train low, val high |
| Cause | high bias | high variance |
| Fix | more capacity, better features, less regularisation | more 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.
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