Shelves / AI and ML Foundations
AI·143
AI Foundations
The map of the field before the details: what "intelligence" means for machines, AI versus machine learning versus deep learning, learning as function approximation from data, the learning paradigms (supervised, unsupervised, self-supervised, semi-supervised, reinforcement learning) with concrete examples and code, discriminative versus generative models, generative AI and how it differs from earlier ML, foundation models and the scaling laws behind them, a short history explaining why things happened when they did, and what software engineers need to know to build with AI responsibly.
Start here: the map before the territory
Artificial intelligence is the broad goal of machines doing things we'd call intelligent. Machine learning (ML) is the dominant way of getting there: learning behaviour from data instead of writing rules. Deep learning is the part of ML that uses many-layered neural networks, and large language models are deep networks trained on text. Underneath all of them is one idea from the Start Here chapter: learning is approximating a function from examples, then checking it on examples it hasn't seen.
Different learners, different assumptions
Five standard learners on two problems. Each learner assumes something different about what the function looks like:
two interleaved half-moons (a curved boundary), 1,000 points train test
logistic regression (assumes a straight line) 86.3% 82.7%
k-nearest neighbours, k = 15 (assumes nearby points agree) 94.1% 94.3%
decision tree, unlimited depth (axis-aligned splits) 100.0% 91.0%
random forest (many trees voting) 100.0% 95.3%
neural network, 2 × 32 units (flexible smooth functions) 93.7% 93.7%
20 features, only 3 informative, 2 clusters per class
logistic regression 72.6% 74.3%
k-nearest neighbours 83.6% 80.7%
decision tree 100.0% 86.0%
random forest 100.0% 88.3%
neural network 100.0% 84.7%
The straight line was too simple for both problems (underfitting: poor even on training data). The single unlimited tree memorised its training data (100%) but generalised worse than a forest of 200 trees. No learner won everywhere, a result formalised as the no free lunch theorem: a learner is good for a kind of problem, because its built-in assumptions (its inductive bias) match that problem.
More data helps, until it doesn't
The random forest on the half-moons, trained on more and more examples, always tested on the same 1,000 new points:
20 examples → 72.4% 50 → 87.7% 200 → 93.0% 1,000 → 93.9% 5,000 → 93.2%
Accuracy rose steeply at first and then flattened near 93–94%: the noise in this data puts a ceiling on what any model can reach. A learning curve like this tells you whether to collect more data (still rising) or to change the model or features (flat).
The kinds of learning
| Paradigm | Learns from | Example at the tiffin centre |
|---|---|---|
| supervised | inputs with correct answers (labels) | predict tomorrow's orders from weather and day |
| unsupervised | inputs only | group customers by ordering habits |
| self-supervised | data that labels itself (next word, masked word) | how LLMs are pre-trained |
| reinforcement | rewards for actions | learning a delivery-routing policy |
How deep to go in AI foundations
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Place AI, ML, deep learning and LLMs on one map and name the learning paradigms |
| L2 | Train and compare standard learners with a proper train/test split |
| L3 | Explain inductive bias, bias–variance, generalisation and no free lunch |
| L4 | Diagnose under- and overfitting with learning curves and choose what to change |
| L5 | Frame a business problem as an ML problem (or decide it shouldn't be one) |
| L6 | Set an organisation's AI strategy, risk posture and capability investments |
What we mean by AI
Artificial intelligence is the broad goal of building systems that perform tasks we associate with intelligence: perceiving, reasoning, planning, learning, communicating, acting. The field has always mixed two approaches:
- Symbolic AI ("good old-fashioned AI"): intelligence from explicit rules and knowledge representations: expert systems, logic programming (Prolog), search and planning (chess engines, route planners), constraint solvers, knowledge graphs. Behaviour is programmed.
- Statistical / learning-based AI: intelligence from patterns learned from data: machine learning and its subfield deep learning. Behaviour is learned.
Modern systems combine both: an LLM (learned) calls a SQL database, a calculator or a theorem prover (symbolic) through tools; a route planner (search) uses learned travel-time predictions.
Machine learning: learning a function from data
Traditional programming: you write the rules; the computer applies them to data to produce answers. Machine learning inverts it: you provide data and (often) answers; an algorithm finds rules (a model) that map one to the other, which then generalise to new data.
Formally, most of ML is function approximation. There's an unknown function f relating inputs x (features: pixels, words, sensor readings, transaction attributes) to outputs y (labels, values, next tokens). We choose a model family f_θ with parameters θ (weights), a loss function L(f_θ(x), y) measuring how wrong predictions are, and an optimisation algorithm that adjusts θ to minimise average loss on training data:
θ* = argmin_θ (1/N) Σᵢ L(f_θ(xᵢ), yᵢ) + λ·R(θ)
where R(θ) is a regulariser discouraging overly complex models. The goal is not to fit the training data perfectly but to generalise: perform well on data the model hasn't seen. Everything in Volumes 14A and 14B elaborates this one idea:
| Ingredient | Questions | Chapters |
|---|---|---|
| Data | What inputs and outputs? How collected, cleaned, labelled, split? | 150 |
| Representation / features | How are inputs encoded as numbers? | 145, 148, 155, 159 |
| Model family | Linear? Trees? Neural network? Transformer? | 148, 151, 153, 154 |
| Loss | What counts as wrong, and how wrong? | 147, 151 |
| Optimisation | How are parameters adjusted? | 146, 151, 152 |
| Evaluation | Does it generalise? On which metrics? | 149, 175 |
| Deployment and operations | How is it served, monitored, updated? | 166, 178, 179 |
# The whole idea in 12 lines: fit y ≈ w·x + b by gradient descent on mean squared error
import numpy as np
rng = np.random.default_rng(0)
x = rng.uniform(0, 10, size=200)
y = 3.0 * x + 2.0 + rng.normal(0, 1.0, size=200) # unknown "true" function + noise
w, b, lr = 0.0, 0.0, 0.01
for step in range(2000):
pred = w * x + b
err = pred - y
w -= lr * 2 * np.mean(err * x) # ∂MSE/∂w
b -= lr * 2 * np.mean(err) # ∂MSE/∂b
print(round(w, 2), round(b, 2)) # ≈ 3.0, ≈ 2.0: rules recovered from data
Learning paradigms
ML methods differ by what supervision signal they learn from.
Supervised learning
Learn from labelled examples (x, y) to predict y for new x.
- Classification: y is a category: spam/not spam, fraud/legit, digit 0–9, sentiment, disease present. Binary, multi-class (one of many) or multi-label (several at once).
- Regression: y is a number: house price, delivery time, demand next week, temperature.
- Structured prediction: y is a structure: a sequence of tags (named entities), a bounding box, a translation.
Labels are expensive (human annotation, chapter 150) and their quality caps model quality. Most commercial ML until ~2020 was supervised: credit scoring, churn prediction, recommendation ranking, image classification.
Unsupervised learning
Learn structure from inputs without labels:
- Clustering: group similar items (customer segments, document topics): k-means, DBSCAN, hierarchical clustering, Gaussian mixtures.
- Dimensionality reduction: compress many features into a few that preserve structure (PCA, t-SNE, UMAP) for visualisation, denoising, speed.
- Density estimation and anomaly detection: what's typical, what's unusual (fraud, intrusion, sensor faults): isolation forests, one-class SVM, autoencoder reconstruction error.
- Association rules: items bought together.
Self-supervised learning
A form of learning where the labels are generated from the data itself, so unlimited unlabelled data becomes training signal. This is the engine of modern AI:
- Next-token prediction: given "The capital of France is", predict "Paris". Every sentence on the web provides millions of free training examples. This is how GPT-style LLMs are pretrained (chapter 156).
- Masked prediction: hide 15% of words (BERT) or image patches (masked autoencoders) and predict them.
- Contrastive learning: pull together representations of two views of the same thing (two crops of an image; an image and its caption, as in CLIP) and push apart different things; produces embeddings (chapter 159).
Self-supervised pretraining learns general-purpose representations that are then adapted to specific tasks with little labelled data.
Semi-supervised and weak supervision
Combine a small labelled set with lots of unlabelled data (pseudo-labelling: train on labels, label the unlabelled data with confident predictions, retrain; consistency regularisation), or use weak supervision: noisy labels from heuristics, distant supervision, or other models (including LLMs labelling data, chapter 150).
Reinforcement learning
An agent takes actions in an environment, receives rewards, and learns a policy (state → action) maximising cumulative reward. There are no correct labels per step, only delayed, sparse feedback, so the agent must explore and solve credit assignment (which actions caused the reward?).
- Classic successes: games (Atari, Go with AlphaGo/AlphaZero), robotics control, recommendation and ad bidding, data-centre cooling, chip floorplanning.
- In LLMs: RLHF (reinforcement learning from human feedback) and RL with verifiable rewards (maths, code that passes tests) shape models to follow instructions and reason better (chapters 158, 164 in 14B).
- Key concepts: Markov decision process (states, actions, transition probabilities, rewards, discount γ), value functions, policy gradients, exploration vs exploitation.
# A tiny reinforcement learning example: ε-greedy multi-armed bandit (explore vs exploit)
import numpy as np
rng = np.random.default_rng(1)
true_ctr = np.array([0.02, 0.05, 0.03]) # unknown click-through rates of 3 ad variants
counts, values, eps = np.zeros(3), np.zeros(3), 0.1
for t in range(20_000):
arm = rng.integers(3) if rng.random() < eps else int(np.argmax(values)) # explore or exploit
reward = rng.random() < true_ctr[arm]
counts[arm] += 1
values[arm] += (reward - values[arm]) / counts[arm] # incremental mean
print(values.round(3), counts.astype(int)) # learns that arm 1 is best and plays it most
Discriminative vs generative models
- A discriminative model learns p(y | x) (or a direct mapping x → y): given an email, how likely is it spam? Logistic regression, most classifiers, BERT-style classifiers.
- A generative model learns the distribution of the data itself, p(x) or p(x, y), so it can sample new data: new text, images, audio, molecules. Naive Bayes is a simple generative classifier; LLMs model p(next token | previous tokens) and thereby the probability of whole texts; diffusion models learn to turn noise into images.
The distinction matters because generative models can do many tasks by framing them as generation ("Classify this email as spam or not: …" → the model generates "spam"), which is what makes foundation models so general.
Generative AI
Generative AI refers to models that produce new content (text, code, images, audio, video, 3D, molecules) from prompts or other inputs. What changed around 2020–2023:
- Scale: models with billions to trillions of parameters, trained on trillions of tokens, using massive GPU/TPU clusters.
- Architecture: the Transformer (2017, chapter 154) parallelises training and scales smoothly.
- Self-supervision: web-scale unlabelled data becomes training signal.
- Alignment: instruction tuning and preference optimisation make raw models helpful, conversational and (more) safe.
- Interfaces: natural-language prompts make capabilities accessible to everyone, and tool use connects models to software.
| Modality | Typical model family | Examples of tasks |
|---|---|---|
| Text, code | Decoder-only Transformers (LLMs) | Chat, summarisation, coding, extraction, reasoning |
| Images | Diffusion / flow-matching models, autoregressive image models | Text-to-image, editing, inpainting |
| Audio | Transformers over audio tokens, diffusion | Speech recognition, text-to-speech, music |
| Video | Diffusion transformers over spatio-temporal patches | Text/image-to-video |
| Multimodal | Vision-language models, any-to-any models | Image Q&A, document understanding, OCR-free parsing |
Foundation models
A foundation model (term from Stanford's CRFM, 2021) is a large model trained on broad data (usually self-supervised) that can be adapted to a wide range of downstream tasks: by prompting, retrieval-augmented generation, fine-tuning, or tool use (chapter 158). Examples: LLMs (Claude, GPT, Gemini, Llama, Mistral, Qwen, DeepSeek families), vision-language models, CLIP-style embedding models, speech models (Whisper), image models.
Implications for engineering:
- One model, many tasks: instead of training a separate classifier per problem, you often prompt or lightly adapt a foundation model.
- Capabilities emerge from scale and are not fully predictable or specified; behaviour must be evaluated empirically (chapter 175), not assumed from design.
- Homogenisation: many products depend on the same few models, so their flaws (biases, failure modes, security weaknesses) propagate widely.
- Build vs buy shifts: most teams consume models via APIs or open-weight checkpoints rather than training from scratch, and invest in data, retrieval, evaluation, guardrails and integration (14B).
Scaling laws
Empirical scaling laws (Kaplan et al., 2020; Hoffmann et al. "Chinchilla", 2022) found that a language model's loss decreases as a smooth power law in model parameters N, training tokens D and compute C, over many orders of magnitude. Chinchilla showed that for a fixed compute budget, parameters and data should grow roughly in proportion (on the order of ~20 tokens per parameter at compute-optimal training); many later models are trained on far more tokens than that because smaller, longer-trained models are cheaper to serve.
Scaling laws made AI progress partly predictable and justified enormous investments; they also show diminishing returns per unit of compute, motivating better data, algorithms, inference-time compute ("thinking" longer before answering) and efficiency work.
A short history (why now?)
| Period | Developments |
|---|---|
| 1950s–60s | Turing test (1950); "artificial intelligence" coined at Dartmouth (1956); perceptron (Rosenblatt, 1958); early optimism |
| 1970s–80s | Symbolic AI, expert systems; perceptron limits (Minsky & Papert, 1969) and AI winters; backpropagation popularised (Rumelhart, Hinton, Williams, 1986) |
| 1990s–2000s | Statistical ML: SVMs, decision trees and ensembles, Bayesian methods; Deep Blue beats Kasparov (1997, search); LSTMs (1997) |
| 2012 | AlexNet wins ImageNet by a wide margin using GPUs and deep CNNs: deep learning era begins |
| 2014–2016 | GANs, sequence-to-sequence, attention for translation; AlphaGo (2016) |
| 2017 | Transformer ("Attention Is All You Need") |
| 2018–2020 | BERT, GPT-2, GPT-3: pretraining at scale; scaling laws |
| 2021–2022 | CLIP, diffusion models (DALL·E 2, Stable Diffusion), instruction tuning, RLHF; ChatGPT (Nov 2022) |
| 2023–2026 | Multimodal frontier models, open-weight models, long context, tool use and agents, reasoning models trained with RL, coding agents, Model Context Protocol, AI in mainstream software engineering |
Why now: data (the web, digitised everything), compute (GPUs/TPUs, cloud), algorithms (backprop + good architectures + optimisation tricks), software (PyTorch, JAX, open-source ecosystems), and money (scaling laws justified investment).
AI in software engineering practice
For engineers, the practical landscape divides into layers:
Skills that transfer from Volumes 1–13: API design, distributed systems, data engineering, testing (now evaluation), observability, security (now including prompt injection), cost engineering, and architecture. The new parts are understanding how models behave (probabilistic, non-deterministic, capable but fallible) and designing systems that are useful despite errors.
Properties of ML systems that differ from ordinary software
| Ordinary software | ML/AI systems |
|---|---|
| Behaviour specified by code | Behaviour learned from data; specified indirectly by data, objective and prompts |
| Deterministic given inputs | Often stochastic (sampling), sensitive to small input changes |
| Correctness testable with exact assertions | Quality measured statistically on evaluation sets |
| Bugs in code | Also bugs in data, labels, distribution shift, prompts |
| Degrades only when code/environment changes | Degrades silently as the world changes (drift) |
| Explainable by reading code | Opaque internal representations; interpretability is a research field |
| Security boundary = code and inputs | Inputs can carry instructions (prompt injection) |
These differences shape every later chapter: evaluation instead of only unit tests, monitoring for drift and quality, human oversight for consequential actions, and defence in depth for security.
Limitations and responsible AI
Engineers building with AI should understand core limitations:
- Errors and hallucinations: generative models produce fluent but false content; classifiers misclassify; confidence is not correctness (calibration, chapter 149).
- Distribution shift: performance drops when real inputs differ from training data.
- Bias and fairness: models reproduce and can amplify biases in data; outcomes can differ across groups (loan approvals, hiring, face recognition error rates).
- Privacy: training data can be memorised and leaked; user data sent to models must be governed.
- Security: adversarial examples, prompt injection, data poisoning, model theft (chapter 176).
- Transparency and accountability: who is responsible for automated decisions? Can users contest them?
- Regulation: the EU AI Act (in force since August 2024, obligations phasing in through 2026–2027, risk-based: prohibited practices, high-risk systems with conformity requirements, transparency obligations for generative AI, general-purpose model obligations), sector rules (finance, health), data protection laws (GDPR, India's DPDP Act), and AI management standards (ISO/IEC 42001, NIST AI Risk Management Framework).
Responsible practice: define intended use and misuse, evaluate across subgroups, keep humans in the loop for high-stakes decisions, document models and data (model cards, datasheets), monitor in production, and provide recourse.
Lab: inductive bias and learning curves
scikit-learn 1.9.1 on the lab machine (2 vCPUs). Datasets are synthetic, so the "true" difficulty is known: make_moons (two interleaved half-circles, noise 0.25) and make_classification (20 features, 3 informative, 2 clusters per class, 5% flipped labels). 70/30 train/test split, fixed seeds.
Experiment 1: five learners, two problems
| Learner | Moons train | Moons test | 20-feature train | 20-feature test | Fit time (moons) |
|---|---|---|---|---|---|
| logistic regression | 86.3% | 82.7% | 72.6% | 74.3% | 223 ms |
| k-NN (k=15) | 94.1% | 94.3% | 83.6% | 80.7% | 17 ms |
| decision tree (no depth limit) | 100.0% | 91.0% | 100.0% | 86.0% | 5 ms |
| random forest (200 trees) | 100.0% | 95.3% | 100.0% | 88.3% | 325 ms |
| MLP 2×32 | 93.7% | 93.7% | 100.0% | 84.7% | 530 ms |
Read the gaps, not just the scores. Logistic regression's train and test are close and both low: high bias. The unlimited tree's gap (100% → 91%) is high variance. The random forest also fits training data perfectly, yet generalises best; averaging de-correlated trees reduces variance without adding bias, which is why "train accuracy 100%" isn't automatically a red flag for ensembles. On the 20-feature problem, k-NN degrades: with 17 irrelevant features, "nearby" points in 20 dimensions are no longer similar, a mild case of the curse of dimensionality.
Experiment 2: a learning curve
| Training examples | 20 | 50 | 200 | 1,000 | 5,000 |
|---|---|---|---|---|---|
| Test accuracy (random forest) | 72.4% | 87.7% | 93.0% | 93.9% | 93.2% |
The ceiling is set by the label noise in the data: with noise 0.25, the two moons overlap near the boundary and the best possible (Bayes) accuracy is in the low-to-mid 90s. The 0.7-point dip from 1,000 to 5,000 is sampling noise in a 1,000-point test set (±1.5% at 95% confidence, chapter 147). In practice, plot this curve before arguing about models: it shows whether you're data-limited or model-limited.
Experiment 3: choosing the paradigm
For each tiffin-centre problem, the paradigm follows from what data you have:
| Problem | Data available | Paradigm |
|---|---|---|
| forecast tomorrow's orders per dish | past orders with weather and dates | supervised regression |
| flag likely fraudulent orders | some confirmed fraud cases | supervised classification (heavily imbalanced, chapter 149) |
| discover customer segments | order histories, no labels | unsupervised clustering |
| answer customer questions about the menu | menu text and FAQs | an LLM with retrieval (Volumes 14b, 15) |
| decide rider dispatch | simulator or live feedback | reinforcement learning (or a heuristic first) |
Try it yourself
- Limit the decision tree's depth to 3, 6 and 10 and plot train and test accuracy against depth.
- Add 50 random noise features to the moons data and rerun k-NN and random forest.
- Compute the learning curve for logistic regression on the moons. Why does it flatten so early?
- Pick one problem at your workplace and fill in the paradigm table for it, including "no ML needed" as an option.
Revision sheet: AI foundations
Key ideas
- AI ⊃ ML ⊃ deep learning ⊃ LLMs (roughly); symbolic AI and search still matter in places.
- Learning = function approximation from data, judged on unseen data (generalisation).
- Paradigms: supervised, unsupervised, self-supervised, reinforcement (and semi-supervised, weak supervision).
- Inductive bias: each learner's built-in assumptions; no free lunch.
- Bias–variance: too simple (underfit) vs too flexible (overfit); ensembles and regularisation trade between them.
- Learning curves show whether more data or a better model is the lever.
- Curse of dimensionality: distance-based reasoning degrades with many irrelevant features.
- When not to use ML: clear rules, little data, no tolerance for errors, no way to measure success.
Numbers to remember
- Lab: logistic regression 82.7% vs random forest 95.3% on half-moons.
- Lab: learning curve 72% at 20 examples → 93% at 200 → flat.
- A 1,000-example test set measures accuracy to about ±1.5 points (95%).
Pitfalls
- Judging models by training accuracy.
- Assuming deep learning beats everything (tabular data often favours tree ensembles).
- Collecting more data when the learning curve is flat (or tuning models when it's still rising).
- Framing a problem as ML when a rule or a heuristic would do.
- Ignoring label noise that caps achievable accuracy.
Glossary
- Inductive bias: assumptions that let a learner generalise.
- Bias / variance: systematic error / sensitivity to the training sample.
- Bayes error: the lowest error any model could achieve on the data.
- Learning curve: performance vs amount of training data.
- Self-supervised learning: labels derived from the data itself.