A guided field manual

Machine learning,
from the roots up.

A ground-up guide to the whole terrain — algorithms, evaluation, deep nets, and the LLM era — organised so that by the last section you can hold your own with data scientists.

30+ concepts 18 algorithms & architectures 2 live demos 1 confidence check
Start with the big picture
01 — The territory

AI, ML, deep learning, generative AI — the nesting dolls

These four words get used interchangeably and it drives data scientists slightly mad. They're actually nested: each one lives inside the one before it. Get this straight and half the confusion disappears.

AI Machine learning Deep learning GenAI
Tap a ring to explore

Four words, one hierarchy

Artificial intelligence is the whole ambition: machines doing things that seem to require intelligence. Everything else is a subset. Click each band in the diagram to see where it sits and what belongs to it.

▲ Say this to a data scientist

"All deep learning is machine learning, but not all machine learning is deep learning — a random forest is ML with no neural network in sight." That one sentence signals you understand the map.

02 — How a model actually learns

The loop hiding inside every model

Before the algorithms themselves, it pays to know the engine underneath them. Almost every model — from linear regression to GPT — learns through the same four-beat loop. This is the single most useful mental model you can carry.

1 · Predict

The model makes a guess using its current internal numbers (its parameters, also called weights).

2 · Measure error

A loss function scores how wrong the guess was — e.g. squared error for numbers, cross-entropy for categories.

3 · Find the slope

Backpropagation works out which direction to nudge each weight to reduce the loss (the gradient).

4 · Nudge & repeat

Gradient descent takes a small step downhill. Do this millions of times and the model "learns".

▲ The distinction people trip on

Parameters are learned by the model during training (the weights). Hyperparameters are set by you before training — learning rate, number of trees, network depth. You tune hyperparameters; the model tunes parameters. Confusing the two is a rookie tell.

The knob that controls step size in beat 4 is the learning rate — too big and training overshoots and diverges; too small and it crawls. That single hyperparameter causes more failed training runs than almost anything else.

03 — Three ways a machine learns

Supervised, unsupervised, reinforcement

This is the backbone of the whole field, and the right place to start. The difference is entirely about what feedback the model gets. Every algorithm a data scientist would expect you to know is here — especially the ensemble methods, which do most of the real-world heavy lifting on tabular data.

Labelled data. Every training example comes with the right answer. The model learns the mapping from inputs → answer, then predicts answers for data it's never seen.

Linear RegressionRegression+

Fits a straight-line relationship between input features and a continuous number, then reads predictions off the line.

Predicts
A continuous value
Learns
A slope + intercept per feature
In the wild
Estimating house prices from square footage, bedrooms and location. Still the honest first thing a good DS tries before reaching for anything fancy — a baseline you must beat.
Logistic RegressionClassification+

Despite the name, it's a classifier. It squashes a linear score through a logistic (sigmoid) curve to output a probability between 0 and 1.

▲ Precision point

It's often described as "just binary classification." True, but incomplete: with a softmax it extends naturally to multiclass (multinomial logistic regression). Say "binary by default, multiclass with softmax" and you'll sound precise.

In the wild
Spam vs not-spam; will-this-customer-churn. Fintech loves it because the coefficients are interpretable — you can explain why a loan was scored the way it was, which matters for regulators.
Decision TreesBoth+

A flowchart of if/else splits learned from data. Fully interpretable, handles numbers and categories, needs little preprocessing — but a single deep tree overfits badly.

In the wild
Triage-style decisions. Rarely used alone in production; their real power shows up when you combine hundreds of them (see Random Forest & Gradient Boosting below).
Support Vector Machine (SVM)Both+

Finds the boundary (hyperplane) that leaves the widest possible margin between classes.

▲ The half that's usually missed

The linear case is only half the story. The reason SVMs are famous is the kernel trick — it bends the boundary to separate classes that aren't linearly separable, without ever computing the high-dimensional coordinates. SVMs also do regression (SVR).

In the wild
Handwritten-digit and text classification on smaller datasets. Falls out of favour on very large data, where trees and neural nets win.
k-Nearest Neighbours (k-NN)Both · added+

No training at all — it just stores the data. To classify a new point, it looks at the k closest known points and takes a vote.

Why it matters
The purest illustration of "learning by similarity", and the intuition behind modern vector search and recommendation systems. Worth knowing precisely because it makes the embeddings section later click.
Naïve BayesClassification · added+

Applies Bayes' theorem with a bold "naïve" assumption that features are independent. Wrong assumption, surprisingly good results — and blazingly fast.

In the wild
The classic spam filter and quick text-classification baseline. Cheap to train, so it's a great sanity check.
Random ForestBoth · added · important+

An ensemble: train hundreds of decision trees, each on a random slice of data and features, then average their votes. The randomness cancels out individual trees' overfitting.

▲ The workhorse most intros skip

Ensembles rarely make the beginner lists, yet they win a huge share of real-world tabular problems. If a data scientist mentions "the forest" or "bagging", this is it.

In the wild
Credit risk, churn, fraud — anywhere you have rows-and-columns data and want strong accuracy with minimal fuss.
Gradient Boosting (XGBoost / LightGBM / CatBoost)Both · added · important+

Also an ensemble of trees, but built sequentially: each new tree focuses on fixing the errors the previous ones made. Where a forest builds trees in parallel and averages, boosting builds them one after another and corrects.

◆ Insider knowledge

XGBoost and its cousins are the workhorse that wins most Kaggle competitions on structured data and quietly power much of fintech. If you remember one "advanced" name from this page, make it this one.

In the wild
Default choice for tabular prediction in banking, insurance, ad-tech. Strong out of the box, but has more hyperparameters to tune than a forest.

No labels. The model is handed raw data and asked to find structure on its own — natural groupings, or a simpler way to represent the data.

K-Means ClusteringClustering+

Splits data into K groups by repeatedly assigning points to the nearest centre and moving each centre to the mean of its points, minimising within-cluster spread.

◆ The catch to mention

You must choose K in advance, and it assumes roughly round, similar-sized clusters. The "elbow method" and silhouette score help pick K — dropping either term shows depth.

In the wild
Customer segmentation for marketing — grouping buyers by behaviour so campaigns can be tailored.
Hierarchical ClusteringClustering+

Builds a tree of nested clusters (a dendrogram) by repeatedly merging the closest groups. No need to pre-set K — you cut the tree at whatever height you like.

In the wild
Grouping genes with similar expression patterns in biology; taxonomy-style analysis where the nesting itself is informative.
DBSCANClustering · added+

Density-based clustering: it finds dense regions and, crucially, labels sparse points as noise/outliers rather than forcing them into a cluster. It also finds arbitrarily-shaped clusters that K-means can't.

Why it matters
The go-to when clusters are irregular or when outlier detection is the point — e.g. anomaly detection in transactions.
Principal Component Analysis (PCA)Dimensionality reduction+

Finds new axes (principal components) along the directions of greatest variance, then keeps only the top few — compressing many features into a handful while losing as little information as possible. It's a linear method.

In the wild
Compression, de-noising, and speeding up other models by shrinking the feature count. Often a preprocessing step, not the final answer.
t-SNE & UMAPVisualisation · sharpened+

t-SNE is a non-linear technique that squeezes high-dimensional data into 2-D so you can see the clusters, preserving local neighbourhoods.

✎ Two things to add

First: in a t-SNE plot the distances between clusters are not meaningful and cluster sizes are misleading — it's for eyeballing, not measuring. Second: UMAP is the modern alternative — faster, and it preserves more of the global structure. Data scientists reach for UMAP now.

In the wild
Visualising which cell types, documents, or user segments sit near each other — and, increasingly, plotting the embedding space of an LLM.

Learning by trial and reward. An agent acts in an environment, gets rewards or penalties, and learns a strategy (a policy) that maximises reward over time. No labelled answers — just consequences.

Q-LearningValue-based+

Learns a table (or network) estimating the future reward of taking each action in each state — the "Q-value". Act greedily on the highest Q-value and you have a policy. It's off-policy: it can learn the best strategy while exploring with a different one.

In the wild
A robot learning a maze; warehouse pick-and-place path optimisation. Deep Q-Networks (DQN) famously learned to play Atari from pixels.
Policy Gradient MethodsPolicy-based+

Skip the value table and optimise the policy directly, adjusting it toward actions that led to higher reward. Handles continuous actions (steering angle, throttle) that Q-learning struggles with. Modern variants: PPO, A2C.

In the wild
Robotics and autonomous driving control loops, where actions are smooth and continuous.
▲ The connection worth making

RL is no longer a niche corner. RLHF — reinforcement learning from human feedback — is how models like Claude and ChatGPT are aligned to be helpful. Policy-gradient methods (PPO) are the engine. Knowing RL feeds straight into understanding today's assistants.

04 — The make-or-break ideas

What separates a model that works from one that looks like it does

These concepts aren't algorithms, which is exactly why they're easy to skip — but they're what data scientists actually argue about. A model can score beautifully in the lab and fail completely in production for exactly these reasons.

Overfitting vs underfitting — the central tension

An overfit model memorises the training data, including its noise, and flops on new data. An underfit model is too simple to capture the real pattern and flops on everything. Every modelling decision is a negotiation between these two.

▲ The bias–variance tradeoff

Underfitting is high bias (too rigid). Overfitting is high variance (too sensitive to the exact training sample). You can't drive both to zero — the art is finding the sweet spot. This phrase comes up constantly; now it means something to you.

The three-way split — and why "test set" is sacred

You split your data into training (the model learns here), validation (you tune hyperparameters here), and test (touched once, at the very end, to estimate real-world performance). Keeping the test set untouched until the end is what makes your final number honest.

◆ Cross-validation, precisely

K-fold cross-validation splits the training data into K parts, trains K times each holding out a different part, and averages the scores — giving a far more reliable estimate than a single split, especially on smaller datasets.

Regularisation — deliberately handicapping the model

Techniques that penalise complexity to fight overfitting: L1 (Lasso) can zero out useless features entirely; L2 (Ridge) shrinks weights smoothly; dropout randomly switches off neurons during training; early stopping halts training before it starts memorising. Naming any of these signals real understanding.

◆ Data leakage — the silent killer

When information from the future (or from the test set) sneaks into training, your model looks brilliant and then collapses in production. Example: scaling your features using the whole dataset before splitting. Leakage is the number-one cause of "it worked in the notebook but not in prod." Mention it and you'll sound seasoned.

05 — Judging a model

Metrics — and the trap of accuracy

The metric definitions are the easy part. The single most important caveat in all of model evaluation is the one most people miss — so let's make you feel it with a live tool.

Live confusion matrix

Adjust the four counts and watch the metrics shift. Then hit the "rare disease" preset.

Predicted Positive
Predicted Negative
Actual Positive
True Positive
80
False Negative
20
Actual Negative
False Positive
30
True Negative
870
Accuracy
(TP+TN) / all
Precision
TP / (TP+FP)
Recall
TP / (TP+FN)
F1 score
harmonic mean of P & R
✎ The accuracy paradox — the caveat that matters most

Load the "predict all healthy" preset. A model that never flags anyone still scores 99% accuracy when only 1% are sick — while catching zero real cases (recall = 0). This is why on imbalanced problems — fraud, disease, churn — data scientists distrust accuracy and lean on precision, recall, F1, and ROC-AUC instead.

Precision vs recall — pick your poison

Precision answers "when the model says yes, how often is it right?" — you optimise it when false alarms are costly (flagging a legit transaction as fraud annoys customers). Recall answers "of all the real cases, how many did we catch?" — you optimise it when misses are dangerous (missing a cancer). You usually can't max both; F1 balances them.

▲ Two terms to bank

ROC-AUC: a single number (0.5 = random, 1.0 = perfect) summarising how well the model ranks positives above negatives across every threshold — the standard headline metric for classifiers. Confusion matrix: the 2×2 table you just played with, the source of all these numbers.

Regression metrics — beyond MSE

MAE (mean absolute error) is the average miss in plain units, robust to outliers. RMSE is MSE's square root, back in the original units but punishing big errors harder. tells you what fraction of the variance the model explains — 1.0 is perfect, 0 is no better than guessing the mean.

06 — Feature engineering

The unglamorous work that wins

There's a saying: models are commodities, features are the moat. Four techniques form the core — with one precision point worth making.

Scaling

Putting features on a comparable range so one big-numbered feature (income) doesn't drown a small one (age). Vital for distance- and gradient-based models (k-NN, SVM, neural nets); irrelevant to trees.

◆ Precision point

"Mean 0, standard deviation 1" is specifically standardisation (z-score) — one kind of scaling. The other common one is normalisation (min–max), which squeezes values into a 0–1 range. "Scaling" is the umbrella; know both children.

Encoding categorical variables

Turning categories into numbers. One-hot makes a 0/1 column per category (safe, but explodes width on high-cardinality fields). Ordinal maps to ranked integers (only when order is real). Target/embedding encoding handles high-cardinality cases like postcodes.

Handling missing data

Imputation fills gaps (mean/median, or a model-based guess); sometimes the fact that a value is missing is itself signal worth a flag column. Dropping rows is a last resort — it can quietly bias the data.

Generating new features

Creating features that expose the pattern more directly — moving averages, ratios, date parts (day-of-week, is-holiday), interactions between fields. This is where domain knowledge becomes accuracy, and where a strategist who understands the business often out-contributes a pure modeller.

07 — Deep learning architectures

From a single neuron to self-attention

Deep learning climbs a natural ladder, each rung solving a limitation of the one before. Here it is rung by rung — with the one transformer claim that gets garbled most often set straight.

A

Neural Network (the MLP)

The foundation

Layers of interconnected "neurons", each connection weighted. Data flows through, activation functions (like ReLU) add the non-linearity that lets it model curves, and backprop tunes the weights.

→ Recognising handwritten digits from raw pixels (OCR).
B

Convolutional Neural Network (CNN)

Built for grids & images

Slides small filters across an image to detect local patterns — edges, then textures, then whole objects as layers deepen. Vastly fewer weights than connecting every pixel to every neuron.

→ Spotting pedestrians and road signs in self-driving cars; medical imaging.
C

Recurrent Neural Network (RNN)

Built for sequences

Has a memory that carries information from earlier steps forward, so order matters — suited to language and time series. Its weakness: it forgets across long gaps (the vanishing gradient problem).

→ Time-series and language modelling. (The common stock-price example is illustrative — real markets are near-random-walk, so treat it as a teaching case, not a claim RNNs beat the market.)
D

LSTM & GRU

RNNs that remember

Add gates that decide what to keep, forget, and output — fixing the long-memory problem. LSTM uses three gates (input, forget, output); GRU simplifies to two (reset, update).

→ Machine translation before transformers took over; still used where data is limited.
E

Transformers

The architecture that changed everything (2017)

Ditches sequential processing entirely. Self-attention lets every word look at every other word at once and weigh how relevant each is — using queries, keys and values, scaled dot-products and a softmax. Multi-head attention does this several times in parallel to capture different relationships, and positional encoding re-injects word order (since nothing is processed in sequence).

→ Powers BERT, GPT, Claude, and essentially all modern language AI.
✎ The transformer claim to get right

It's tempting to assume BERT and GPT both come from the full encoder-decoder. More precisely: the original 2017 transformer was encoder–decoder (built for translation), but BERT is encoder-only (great at understanding — search, classification) and GPT is decoder-only (great at generating text). Getting this distinction right is a genuine credibility marker with ML people.

▲ Why transformers won

Parallelism (whole sequences at once, so they train fast on huge data), long-range memory (attention reaches across the entire input), and scalability (bigger models + more data kept getting better — the insight behind GPT-scale systems).

08 — The modern frontier

Where most intros stop, the conversation starts

Many overviews end at transformers. But that's exactly where today's most-discussed ideas begin — and where your strategy work lives. These are the terms that dominate current data-science and product conversations.

Foundation models & the pretrain → fine-tune shiftParadigm+

Instead of training a fresh model per task, you pretrain one enormous model on vast general data, then fine-tune or prompt it for specific jobs. This is transfer learning at scale — the reason a handful of labs can serve thousands of downstream applications.

EmbeddingsRepresentation+

Turning words, images, or users into vectors of numbers where closeness = similarity. This is the k-NN intuition from earlier, industrialised. Embeddings underpin semantic search, recommendations, and RAG.

Why you care
Personalisation and "nudge" engines are, under the hood, embedding-similarity plus ranking. This is the vocabulary your data scientists use for it.
RAG — Retrieval-Augmented GenerationLLM pattern+

Before an LLM answers, retrieve relevant documents (via embeddings) and feed them in as context. It grounds answers in your data and cuts hallucination — without retraining the model. The default enterprise pattern for "chat with our knowledge base."

Fine-tuning vs prompting vs RAGDecision+

Prompting: change the instructions, no training — fastest, cheapest. RAG: inject fresh/proprietary knowledge at query time. Fine-tuning: adjust the model's weights on your examples to change its behaviour or style. Knowing which lever to pull for which problem is a genuinely strategic skill.

RLHF & alignmentTraining+

Reinforcement Learning from Human Feedback: humans rank model outputs, a reward model learns those preferences, and policy-gradient RL (PPO) nudges the model toward them. It's how raw text-predictors became helpful, honest assistants — the direct bridge from Section 03's RL.

Diffusion modelsGenerative+

The engine behind AI image generation (Stable Diffusion, DALL·E, Midjourney). Train a model to remove noise step by step; run it in reverse from pure noise and a coherent image emerges. A different generative family from transformers — worth knowing they're not the same thing.

Agentic AISystems+

LLMs that don't just answer but plan, use tools, call APIs, and act in loops toward a goal — checking their own work along the way. The frontier of applied AI, and squarely your domain. The through-line: an agent pursuing a goal by taking actions is the same RL framing from Section 03, now wrapped around a language model.

◆ One honest caveat

Explainability and responsible AI matter more the more powerful models get — SHAP and LIME explain individual predictions, and in regulated fields like wealth management, "why did the model decide this?" is often a hard requirement, not a nice-to-have. Bringing this up unprompted marks you as someone who thinks past the demo.

09 — Talk like a data scientist

The quick-reference layer

A tight glossary, then a handful of phrases that make conversations flow. You don't need to build models to sound like you understand the people who do.

Feature
An input column the model learns from.
Label / target
The answer you're trying to predict.
Parameter (weight)
A number the model learns during training.
Hyperparameter
A setting you choose before training.
Loss function
The score of how wrong a prediction is.
Gradient descent
The step-by-step method that minimises loss.
Epoch
One full pass through the training data.
Overfitting
Memorising noise; great on train, poor on new data.
Regularisation
Penalising complexity to curb overfitting.
Ensemble
Combining many models to beat any single one.
Baseline
The simple model everything else must beat.
Inference
Using a trained model to make predictions.
Embedding
A vector where nearness means similarity.
Attention
Weighing which parts of the input matter most.
Fine-tuning
Further-training a base model on your data.
Hallucination
A confident but false LLM output.
"What's your baseline, and are we beating it meaningfully?"
Signals you care about real lift, not just a number in isolation.
"Is this an imbalanced problem? If so, accuracy's misleading — what's the recall?"
Shows you know the accuracy paradox cold.
"How are we splitting train/validation/test, and are we sure there's no leakage?"
The two questions that catch most silent failures.
"For this tabular problem, did we try gradient boosting before the neural net?"
Reflects how real practitioners actually sequence their tools.
"Is it overfitting, or is the signal just weak? What do the train vs val curves say?"
Frames the bias–variance question the way modellers do.
"Would RAG solve this before we consider fine-tuning?"
Shows you pick the cheapest effective lever first.
10 — Confidence check

Prove it to yourself

Eight questions across everything above. Pick an answer to lock it and see why. No pressure — this is just your mirror.

Answered 0 of 8
0 / 8