3.1 · The three flavors of learning
The first split in machine learning is what kind of signal teaches the model. Everything else — algorithms, losses, evaluation — sits on top of this split.
Learn from labelled examples
Definition. Given pairs $(x, y)$ where $y$ is the correct answer, learn a function $\hat{y} = f_\theta(x)$ that minimises a loss between $\hat{y}$ and $y$. We then apply $f_\theta$ to new, unlabelled inputs.
Everyday example. A bank shows you 10,000 past loans labelled "repaid" or "defaulted"; you learn a model that flags risky new applicants.
Used in: spam filters, credit scoring, medical imaging, LLM fine-tuning (SFT).
Find structure in unlabelled data
Definition. Given only inputs $x$ (no $y$), discover hidden patterns — clusters, low-dimensional manifolds, anomalies, density. No "correct answer" exists; we judge by usefulness.
Everyday example. A retailer feeds purchase histories of 1 million customers; the algorithm groups them into 8 customer personas the marketing team can target.
Used in: segmentation, anomaly detection, embeddings, LLM pre-training (self-supervised).
Learn from reward by trying
Definition. An agent takes actions in an environment, receives a scalar reward, and updates its policy $\pi(a|s)$ to maximise long-run reward.
Everyday example. A delivery-route bot tries different orderings; routes that finish faster earn higher reward; over thousands of trials it learns near-optimal routes.
Used in: games (AlphaGo), robotics, recommender bandits, RLHF for LLM alignment.
Three flavors — one picture
3.2 · The ML pipeline (every project, every time)
A model is only as good as the pipeline around it. The flow below is universal — only the tools change.
Most rookie failures live in Problem (wrong objective), Data (leakage, biased sample), and Features (signal too weak). Spend at least half your time there.
3.3 · Supervised learning — the canonical algorithms
3.3.1 · Linear regression
Definition. Fits a straight line (in $n$ dims: a hyperplane) so predictions are a weighted sum of features: $\hat{y} = \mathbf{w}^\top \mathbf{x} + b$. Loss is mean-squared-error.
Example. Predict house price from area: rows = $(\text{area}, \text{price})$. The fitted line tells you "each extra m² adds Rs 38,000 on average". Use the slope to estimate the price of any new listing.
Use when: the relationship looks roughly linear, you want interpretability, and you have a numeric target.
3.3.2 · Logistic regression
Definition. Despite the name, this is a classifier. It computes a weighted sum then squashes it through a sigmoid into a probability:
$\hat{p} = \sigma(\mathbf{w}^\top \mathbf{x} + b),\quad \sigma(z) = \dfrac{1}{1+e^{-z}}$
Loss is binary cross-entropy. A threshold (usually 0.5) turns the probability into a yes/no decision.
Example. "Will this user cancel their subscription next month?" Features = usage in last 30 days, plan tier, support tickets opened. Output = probability of churn. If $\hat{p} > 0.7$, route to the retention team.
Use when: binary or multi-class target; you want a strong, interpretable baseline before reaching for fancier methods.
3.3.3 · k-Nearest Neighbours (kNN)
Definition. A "lazy" learner — no training step. To classify a new point, look at the $k$ closest training points (by distance), and take the majority vote.
Example. Movie recommendation. For a new user, find the 5 users most similar by past ratings; recommend movies those neighbours liked.
Use when: small/medium dataset, no clear linear boundary, and you can pay per-prediction cost.
3.3.4 · Decision trees
Definition. A flowchart of yes/no questions on features, learned greedily by splitting where the data becomes most "pure" (Gini or information gain). Leaves carry the predicted class or value.
Example. A loan-approval tree: "age > 30? → income > 50k? → own home?" Each leaf is a decision a human reviewer can read in plain English.
Watch out: a single deep tree memorises noise → high variance. Almost always used inside an ensemble.
3.3.5 · Random Forest & Gradient Boosting
Definition. Train many trees and combine them.
- Random Forest = many trees, each on a random subsample of rows and features; predictions are averaged or majority-voted. Reduces variance.
- Gradient Boosting = trees added one at a time, each one trained to predict the residual (mistakes) of the previous. XGBoost / LightGBM / CatBoost are state-of-the-art for tabular data.
Example. Predicting which insurance claims are fraudulent on 200,000 rows of mixed numeric and categorical features — XGBoost is almost always the right first call.
3.3.6 · Support Vector Machines (SVM)
Definition. Find the hyperplane that maximally separates the two classes — leaving the widest possible margin. With the kernel trick (RBF, polynomial), SVMs can carve curved boundaries without explicitly computing high-dim features.
Example. Classifying handwritten digits from 8×8 pixel grids. SVM with an RBF kernel was the state-of-the-art for years before deep nets.
Use when: medium dataset, clear margin between classes, you need a strong non-linear classifier without going deep.
3.3.7 · Naive Bayes
Definition. Apply Bayes’ rule with a strong simplifying assumption — features are conditionally independent given the class. Surprisingly hard to beat on text data with few examples.
$P(\text{class} \mid \text{words}) \propto P(\text{class})\,\prod_i P(\text{word}_i \mid \text{class})$
Example. A classic spam filter — emails are bags of words; the model multiplies the per-word probabilities under "spam" vs "ham" and picks the higher.
The supervised algorithm chooser
| Situation | First try |
|---|---|
| Tabular, < 10k rows, interpretability matters | Logistic / Linear regression |
| Tabular, many mixed features | XGBoost / LightGBM |
| Text classification, small data | Naive Bayes / Logistic on TF-IDF |
| Image / audio | Pre-trained deep model + fine-tune (Ch 5) |
| Anomaly detection | Isolation forest, autoencoder |
| Recommendation | Matrix factorization, then two-tower NN |
3.4 · Unsupervised learning — finding hidden structure
3.4.1 · K-Means clustering
Definition. Partition $n$ points into $k$ groups by alternating two steps: (1) assign each point to its nearest centroid, (2) recompute each centroid as the mean of its assigned points. Repeat until stable. Minimises the total within-cluster variance.
Example. Group 50,000 e-commerce customers into 5 personas using "monthly spend, # categories shopped, avg basket size". Marketing campaigns are tailored per cluster.
Caveats: you must choose $k$; assumes roughly spherical clusters; sensitive to outliers.
3.4.2 · DBSCAN
Definition. A density-based clusterer. Two parameters: $\varepsilon$ (radius) and $\text{minPts}$ (density threshold). Points are core, border, or noise. Clusters grow from core points; outliers fall out for free.
Example. Detect fraudulent ATM withdrawals: legitimate spending forms dense clusters; rare outlying points get flagged automatically as noise.
Use when: clusters are odd shapes, you want outliers labelled, and you can’t pre-pick $k$.
3.4.3 · Hierarchical clustering
Definition. Build a tree (dendrogram) by repeatedly merging the two closest points/clusters (agglomerative) or splitting the largest (divisive). You then choose a cutoff height that yields the number of clusters you want.
Example. Biology — group species by genetic distance to recover an evolutionary tree.
3.4.4 · Principal Component Analysis (PCA)
Definition. Find the directions in which data varies most — these are the principal components, the eigenvectors of the covariance matrix. Project data onto the top-$k$ to reduce dimensionality while preserving variance.
Example. Compress 1000 survey questions into 5 latent factors — the same trick that "personality types" are derived from.
In modern stacks: PCA is the linear ancestor of embeddings; we still use it to visualise high-dim vectors before t-SNE/UMAP polish.
3.4.5 · t-SNE & UMAP — non-linear dimensionality reduction
Definition. Algorithms that preserve neighbourhood structure when mapping high-dim points into 2D/3D. Where PCA preserves global variance, t-SNE and UMAP preserve local geometry — perfect for visualisation.
Example. Project 1536-dim sentence embeddings (e.g. customer support tickets) into 2D so you can see topical clusters before clustering them properly.
3.4.6 · Autoencoders (bridge to deep learning)
Definition. A neural network with a bottleneck: an encoder compresses $x$ into a small latent vector $z$, a decoder reconstructs $\hat{x}$. The training objective is reconstruction loss.
Example. Train an autoencoder on normal credit-card transactions; at inference, transactions that don’t reconstruct well are flagged as anomalies.
3.5 · Reinforcement learning — the basics that power RLHF
Definition. An agent sits in an environment; at each step it observes a state $s_t$, picks an action $a_t$ via its policy $\pi(a|s)$, and receives a reward $r_t$. It maximises expected discounted return:
$G_t = \sum_{k=0}^{\infty} \gamma^k\, r_{t+k+1},\quad \gamma \in [0, 1)$
| Family | Idea | Examples |
|---|---|---|
| Value-based | Learn $Q(s,a)$, the expected return for each action. | Q-learning, DQN |
| Policy-based | Directly parameterize $\pi_\theta(a|s)$ and ascend its gradient. | REINFORCE, PPO |
| Actor-critic | Two networks: actor picks actions, critic estimates value. | A2C, SAC |
| Model-based | Learn the environment dynamics first. | MuZero |
Example. Train a robot arm to stack blocks. State = joint angles + camera image. Action = motor torques. Reward = +1 when a block is placed correctly, −0.01 per step (to encourage speed).
3.6 · Bias / variance / regularization — the eternal triangle
| Symptom | What's high | Fix |
|---|---|---|
| Train and test both bad | Bias (underfitting) | Bigger / deeper model, more features, longer training. |
| Train great, test bad | Variance (overfitting) | More data, simpler model, dropout, weight decay, early stop. |
| Test stays bad regardless | Irreducible noise | Re-define problem; collect better labels. |
The regularization toolbox — definitions
| Technique | What it does |
|---|---|
| L1 (Lasso) | Adds $\lambda \sum |w_i|$ to the loss — pushes many weights to exactly zero, giving a sparse model. |
| L2 (Ridge / weight decay) | Adds $\lambda \sum w_i^2$ — shrinks weights smoothly toward zero, never quite reaching it. |
| Dropout | During training, randomly zero a fraction of activations — forces the model not to rely on any single neuron. |
| Early stopping | Track validation loss; stop training when it stops improving — cheapest regularizer in the world. |
| Data augmentation | Generate variations of existing samples (flips, crops, paraphrases) so the model can't memorise. |
3.7 · Evaluation metrics — by task family
The right metric depends on the kind of task. The four families below cover almost every classical-ML problem you'll meet. Each metric gets a definition, a formula, and a clear when to use it.
The Confusion Matrix — source of every classification metric
| Metric | Formula | Definition | Use when |
|---|---|---|---|
| Accuracy | $(TP+TN)/N$ | Fraction of all predictions that are correct. | Classes are roughly balanced. Misleading on imbalance. |
| Precision | $TP/(TP+FP)$ | Of items we flagged positive, how many really are? | False positives are costly — spam filter flagging good mail. |
| Recall (Sensitivity) | $TP/(TP+FN)$ | Of all true positives, how many did we catch? | False negatives are costly — cancer screening. |
| Specificity | $TN/(TN+FP)$ | Recall on the negative class. | Healthy patients shouldn't get a positive diagnosis. |
| F1 | $2 \cdot \tfrac{P \cdot R}{P+R}$ | Harmonic mean of precision and recall. | Imbalanced classes; want both P and R high. |
| F-β | $(1+\beta^2)\tfrac{P R}{\beta^2 P + R}$ | Weights recall β times more than precision. | β=2 if missing positives is the bigger sin. |
| ROC-AUC | area under TPR–FPR | Probability the model ranks a random + above a random −. | Threshold-free quality on balanced data. |
| PR-AUC | area under Precision–Recall | Better than ROC when positives are rare. | Fraud, anomaly detection (1:1000 positives). |
| Log-loss | $-\tfrac{1}{N}\sum y\log\hat{p}+(1-y)\log(1-\hat{p})$ | Penalises confident wrong probabilities. | You need calibrated probabilities, not just labels. |
| Brier score | $\tfrac{1}{N}\sum (\hat{p}-y)^2$ | MSE on probability predictions. | Weather-style forecasting; calibration matters. |
| Matthews CC (MCC) | see Ch 19 | Balanced single score in $[-1, +1]$. | Heavily imbalanced + you want one number. |
| Cohen's κ | $\tfrac{p_o-p_e}{1-p_e}$ | Agreement above what chance would give. | Inter-rater / human-vs-model agreement. |
| Top-k accuracy | 1 if true label in top-k preds | Multi-class generalisation of accuracy. | 1000-class image classifiers (top-1 / top-5). |
| Multi-class avg | macro / micro / weighted | How to average per-class scores. Macro = unweighted, micro = pooled, weighted = by support. | Imbalanced multi-class → macro or weighted. |
ROC vs PR curves — same model, two views
On imbalanced data, ROC can look "good" while precision quietly collapses — always check PR-AUC too.
Regression metrics — definitions
| Metric | Formula | Definition | Use when |
|---|---|---|---|
| MAE | $\tfrac{1}{n}\sum |y - \hat{y}|$ | Mean absolute error; same units as $y$. | Outliers exist and shouldn't dominate. |
| MSE | $\tfrac{1}{n}\sum (y - \hat{y})^2$ | Penalises large errors quadratically. | Big mistakes hurt more than small ones; differentiable for training. |
| RMSE | $\sqrt{\text{MSE}}$ | Back in the original units; most-reported. | Reporting "average error" to humans. |
| MAPE | $\tfrac{100}{n}\sum |y-\hat{y}|/|y|$ | Mean absolute percentage error. | Cross-scale comparison; breaks when $y \approx 0$. |
| SMAPE | symmetric MAPE | Handles zeros better than MAPE. | Forecasting at varying scales. |
| R² | $1 - \tfrac{\sum(y-\hat{y})^2}{\sum(y-\bar{y})^2}$ | Fraction of variance explained by the model. | Comparing models on the same dataset. |
| Adjusted R² | R² penalised by # features | R² that doesn't inflate when you add useless features. | Linear models with feature selection. |
| Huber loss | quadratic near 0, linear far | Hybrid of MSE and MAE. | Want stable training + outlier robustness. |
| Quantile loss | $\max(q(y-\hat{y}),(q-1)(y-\hat{y}))$ | Loss for predicting a specific quantile. | Prediction intervals (e.g. 5% / 95%). |
| RMSLE | RMSE on $\log(1+y)$ | Log-scale RMSE. | Targets span orders of magnitude (prices, counts). |
Residual plot — the diagnostic every regression needs
Clustering metrics — definitions
Two flavours: internal (no ground truth — score the geometry) and external (compare to known labels).
| Metric | Type | Definition | Use when |
|---|---|---|---|
| Silhouette score | internal | $(b - a)/\max(a, b)$ where $a$ = avg distance to own cluster, $b$ = distance to nearest other. Range $[-1, 1]$. | No labels — pick best $k$. |
| Davies–Bouldin | internal | Avg ratio of within-cluster scatter to between-cluster distance. Lower is better. | Comparing two clusterings. |
| Calinski–Harabasz | internal | Ratio of between- to within-cluster dispersion. Higher is better. | Choosing $k$ in K-Means. |
| Inertia (SSE) | internal | Sum of squared distances of points to their centroid. K-Means objective itself. | Elbow method for $k$. |
| Adjusted Rand Index (ARI) | external | Pair-agreement with true labels, corrected for chance. Range $[-1, 1]$. | You have ground-truth groupings. |
| Normalised Mutual Info (NMI) | external | Mutual information between cluster and true label, normalised to $[0, 1]$. | Alternative to ARI. |
| Homogeneity / Completeness / V-measure | external | Triple analogous to precision / recall / F1 for clusterings. | Want pure clusters (homogeneity) vs full classes (completeness). |
Ranking / IR metrics — definitions
| Metric | Definition | Use when |
|---|---|---|
| Precision@k | Fraction of top-k that are relevant. | Search-results page quality. |
| Recall@k | Fraction of relevant items captured in top-k. | RAG retrieval quality. |
| MRR | Mean of $1/\text{rank}$ of the first relevant item. | Q&A — one right answer matters. |
| MAP | Mean of average precisions across queries. | Classic IR benchmarks. |
| nDCG@k | Discounted cumulative gain normalised by the ideal ranking. Handles graded relevance + position discount. | Gold standard for ranking quality. |
| Hit@k | 1 if any relevant item is in top-k. | Recommendations. |
| RBO | Rank-biased overlap between two rankings. | Compare two rankers without ground truth. |
A cross-task metric library lives in Ch 19 · Glossary.
3.8 · The 7 pitfalls juniors learn the hard way
- Data leakage — anything from the future or the test set sneaks into training.
- Train/test contamination — feature scaler fit on the full dataset instead of train only.
- Misaligned metric — optimising accuracy on a 99:1 imbalanced dataset.
- Selection bias — your sample doesn’t look like the deployment distribution.
- Look-ahead bias in time series — random split instead of forward chaining.
- Tuning on the test set — only the very last evaluation should touch test.
- Concept drift — the world changes after deploy; monitor or retrain.
Mini notebook — three-line ML, three-line eval
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, test_size=0.2, random_state=42)
model = GradientBoostingClassifier().fit(X_tr, y_tr)
print(roc_auc_score(y_te, model.predict_proba(X_te)[:, 1]))