The Agentic AI Codex
Ch 03 · Classical Machine Learning
Chapter 03 · Theory + Practice

Classical Machine Learning

Before transformers — and still under the hood of every modern stack — sits classical ML. In this chapter every algorithm is unpacked the same way: a one-line definition, a small SVG diagram, a worked example, and where you’d use it in practice. By the end you’ll know what each method does, what it assumes, and when to reach for it.

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.

Supervised

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).

Unsupervised

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).

Reinforcement

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

Supervised data → label x → y = cat x → y = dog x → y = cat teacher gives answers Unsupervised data only finds groups itself Reinforcement action → reward agent env action reward improves by trial

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.

Problem→ Data→ Features→ Model→ Train / CV→ Evaluate→ Deploy + monitor

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.

house size → price ŷ = wx + b

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.

w·x + b p "no" "yes" threshold = 0.5

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.

new point ? k = 3 nearest → majority class wins

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.

age > 30? no yes income > 50k? owns home? deny approve deny approve

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.
Random Forest — parallel trees tree 1 tree 2 tree N average / vote Boosting — sequential trees tree 1 tree 2 (fixes 1) tree N (fixes N-1)

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.

decision boundary margin

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

SituationFirst try
Tabular, < 10k rows, interpretability mattersLogistic / Linear regression
Tabular, many mixed featuresXGBoost / LightGBM
Text classification, small dataNaive Bayes / Logistic on TF-IDF
Image / audioPre-trained deep model + fine-tune (Ch 5)
Anomaly detectionIsolation forest, autoencoder
RecommendationMatrix 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.

k = 3 clusters; white diamonds are centroids

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.

noise

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.

A B C D E F cut here → 2 clusters

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.

PC 1 (max variance) PC 2 (orthogonal)

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)$

State $s_t$→ Policy $\pi(a|s)$→ Action $a_t$→ Environment→ Reward $r_t$, next state $s_{t+1}$
FamilyIdeaExamples
Value-basedLearn $Q(s,a)$, the expected return for each action.Q-learning, DQN
Policy-basedDirectly parameterize $\pi_\theta(a|s)$ and ascend its gradient.REINFORCE, PPO
Actor-criticTwo networks: actor picks actions, critic estimates value.A2C, SAC
Model-basedLearn 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).

Tie back to LLMs
RLHF (Reinforcement Learning from Human Feedback) uses PPO: humans rank model outputs; those rankings train a reward model; PPO then nudges the LLM to maximise that reward — kept near the base model by a KL penalty (Ch 2).

3.6 · Bias / variance / regularization — the eternal triangle

Error Model complexity → Bias² (high when too simple) Variance (high when too complex) Total error (U-shape) sweet spot
SymptomWhat's highFix
Train and test both badBias (underfitting)Bigger / deeper model, more features, longer training.
Train great, test badVariance (overfitting)More data, simpler model, dropout, weight decay, early stop.
Test stays bad regardlessIrreducible noiseRe-define problem; collect better labels.

The regularization toolbox — definitions

TechniqueWhat 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.
DropoutDuring training, randomly zero a fraction of activations — forces the model not to rely on any single neuron.
Early stoppingTrack validation loss; stop training when it stops improving — cheapest regularizer in the world.
Data augmentationGenerate 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

TP (predicted +, actually +) FP (predicted +, actually −) FN (predicted −, actually +) TN (predicted −, actually −) Actually + Actually − Predicted + Predicted −
MetricFormulaDefinitionUse 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-AUCarea under TPR–FPRProbability the model ranks a random + above a random −.Threshold-free quality on balanced data.
PR-AUCarea under Precision–RecallBetter 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 19Balanced 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 accuracy1 if true label in top-k predsMulti-class generalisation of accuracy.1000-class image classifiers (top-1 / top-5).
Multi-class avgmacro / micro / weightedHow 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

ROC: TPR vs FPR random good classifier TPR FPR PR: Precision vs Recall drop with high recall P R

On imbalanced data, ROC can look "good" while precision quietly collapses — always check PR-AUC too.

Regression metrics — definitions

MetricFormulaDefinitionUse 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$.
SMAPEsymmetric MAPEHandles 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 # featuresR² that doesn't inflate when you add useless features.Linear models with feature selection.
Huber lossquadratic near 0, linear farHybrid 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%).
RMSLERMSE on $\log(1+y)$Log-scale RMSE.Targets span orders of magnitude (prices, counts).

Residual plot — the diagnostic every regression needs

y − ŷ ŷ → good: random scatter around 0

Clustering metrics — definitions

Two flavours: internal (no ground truth — score the geometry) and external (compare to known labels).

MetricTypeDefinitionUse when
Silhouette scoreinternal$(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–BouldininternalAvg ratio of within-cluster scatter to between-cluster distance. Lower is better.Comparing two clusterings.
Calinski–HarabaszinternalRatio of between- to within-cluster dispersion. Higher is better.Choosing $k$ in K-Means.
Inertia (SSE)internalSum of squared distances of points to their centroid. K-Means objective itself.Elbow method for $k$.
Adjusted Rand Index (ARI)externalPair-agreement with true labels, corrected for chance. Range $[-1, 1]$.You have ground-truth groupings.
Normalised Mutual Info (NMI)externalMutual information between cluster and true label, normalised to $[0, 1]$.Alternative to ARI.
Homogeneity / Completeness / V-measureexternalTriple analogous to precision / recall / F1 for clusterings.Want pure clusters (homogeneity) vs full classes (completeness).

Ranking / IR metrics — definitions

MetricDefinitionUse when
Precision@kFraction of top-k that are relevant.Search-results page quality.
Recall@kFraction of relevant items captured in top-k.RAG retrieval quality.
MRRMean of $1/\text{rank}$ of the first relevant item.Q&A — one right answer matters.
MAPMean of average precisions across queries.Classic IR benchmarks.
nDCG@kDiscounted cumulative gain normalised by the ideal ranking. Handles graded relevance + position discount.Gold standard for ranking quality.
Hit@k1 if any relevant item is in top-k.Recommendations.
RBORank-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

  1. Data leakage — anything from the future or the test set sneaks into training.
  2. Train/test contamination — feature scaler fit on the full dataset instead of train only.
  3. Misaligned metric — optimising accuracy on a 99:1 imbalanced dataset.
  4. Selection bias — your sample doesn’t look like the deployment distribution.
  5. Look-ahead bias in time series — random split instead of forward chaining.
  6. Tuning on the test set — only the very last evaluation should touch test.
  7. 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]))
A working habit
Always build a baseline first: logistic regression with default settings. If your fancy model can’t beat it by a meaningful margin, the win is probably noise.

3.9 · Self-check

Q1 · Which loss does linear regression minimise?
Cross-entropy
Mean Squared Error
Hinge loss
Accuracy
Q2 · Train accuracy is 99%, test accuracy is 71%. The model has high…
Bias
Variance
Irreducible error
Regularization
Q3 · You want to cluster a dataset with weird, crescent-shaped groups and label outliers automatically. Best fit?
K-Means
DBSCAN
PCA
t-SNE