Lecture 1 Overview and Mathematical Framing

This lecture positions machine learning as a mathematical discipline for constructing predictors from data under uncertainty. The central object is a mapping selected from a hypothesis class , with performance evaluated relative to an unknown data-generating distribution .

Problem Formulation

Let with input space and label space . A training sample is

with the standard i.i.d. assumption. Learning is the task of selecting

such that generalisation to unseen draws from is good.

In the classification setting with 0-1 loss,

the true risk and empirical risk are

The course repeatedly studies the gap between these two quantities and conditions under which minimising controls .

Conceptual Position of Machine Learning

The opening slides place ML at the interface of statistics, optimisation, pattern recognition, data mining, and AI. A useful operational distinction is:

  • data mining emphasises extraction of structure from existing data;
  • machine learning emphasises construction of predictive rules with explicit generalisation goals.

This distinction is not absolute, but exam questions typically expect you to articulate learning in terms of hypotheses, loss, distributions, and guarantees.

Historical Arc and Methodological Consequence

The historical timeline (Bayes, Markov, perceptron, PAC, SVM, deep learning, transformers) motivates a recurring pattern: representational power, optimisation tractability, and statistical guarantees must be balanced. The modern toolkit is best understood as combinations of these three axes rather than as isolated algorithms.

Perceptron as Canonical Linear Learner

For binary labels and inputs , the perceptron predicts

Given example , the update is

Equivalent mistake form:

Interpretation: each mistake moves the separating hyperplane towards correct classification of the current point.

Noise, Plausible Hypotheses, and Margin Principle

The geometric sequence of slides illustrates:

  • with low noise, many linear separators can interpolate the sample;
  • with increasing noise, the set of plausible separators contracts;
  • maximum-margin selection yields a robust separator by maximising the minimum signed distance to training points.

This motivates support vector machines and, more generally, the role of inductive bias in choosing one predictor among many empirically adequate ones.

Expressivity Limits and Non-Linearity

Linear threshold functions can represent AND/OR-type concepts but fail on XOR in the original input space. Two standard remedies are introduced:

  1. Kernel lifting: linear separation in a feature space via inner products .
  2. Multi-layer perceptron composition: stacked affine maps and non-linear activations to realise non-linear decision boundaries.

This is the first appearance of the representation trick: make the task linearly simple in a transformed space.

Toy Generalisation Guarantee from Threshold Learning

The airport suitcase example instantiates one-dimensional threshold learning. Let denote the true threshold and the learned threshold from i.i.d. examples. Suppose the disagreement region between and has probability mass .

An error larger than occurs only if no training point falls inside that disagreement region. Hence

Using , it suffices to require

Therefore,

for above the bound. This is the core PAC-style sample-complexity template that recurs throughout the course.

Exam-Oriented Takeaways

You should be able to reconstruct without notes:

  1. the formal learning setup ;
  2. perceptron prediction and update equations;
  3. why linear models fail on XOR and how kernels/layers address this;
  4. the threshold-learning bound from .

These four items are the mathematical backbone of the introductory lecture and connect directly to later topics in PAC learning, sample complexity, generalisation bounds, and VC dimension.

Lecture 2 Data and (Pre-)Processing

This lecture formalises the pipeline from raw observations to vector representations suitable for learning algorithms. The core principle is that model quality is bounded by representation quality: if the data map is inadequate, no downstream optimiser can recover the lost structure.

Data Model and Data Types

Let a dataset be written as

with optional labels . The feature space may be heterogeneous, combining numeric, categorical, textual, image, or graph-valued attributes. In practice, most classical learners require an embedding

that preserves task-relevant structure.

Numeric attributes are either discrete or continuous. Categorical attributes are nominal (unordered) or ordinal (ordered). This distinction determines admissible pre-processing: ordinal variables may be relabelled monotonically, while nominal variables require non-ordinal encodings such as one-hot encoding.

Data Analysis Before Pre-Processing

Pre-processing starts with exploratory data analysis rather than immediate transformation. For each feature one should inspect scale, missingness, outliers, and empirical distribution. The minimal summary comprises median and quantiles (5-number summary), mean, variance/standard deviation, and pairwise dependency diagnostics (e.g. correlation matrices for numeric attributes).

The statistical purpose is to estimate whether a transformation will improve numerical conditioning and comparability across features.

Numeric Pre-Processing and Scaling Maps

Let denote feature of example . Scaling is performed per feature (column-wise), not globally across all coordinates.

For feature , define

The main transforms are:

Standardisation is typically preferred for gradient-based models and margin-based methods because it centres and rescales coordinates to comparable magnitudes.

Categorical and String Encodings

For a nominal feature with alphabet , one-hot encoding defines

where is the -th standard basis vector. Missing categories are represented either by a dedicated “unknown” symbol or by imputation before encoding.

The same principle extends to strings at symbol level: with alphabet , each symbol maps to a one-hot vector in . Concatenating symbol vectors yields a sparse representation. Word-level encodings in text follow the same algebraic idea, with vocabulary size replacing alphabet size.

Image and Text Feature Construction

For images, a traditional pipeline is: geometric/photometric pre-processing (resize, greyscale, augmentation), followed by feature extraction (e.g. HOG/SIFT/SURF). Deep architectures instead consume tensor-valued pixel arrays directly and learn feature maps end-to-end.

For text, a basic pipeline is token normalisation, stop-word handling, stemming/lemmatisation, then vectorisation (TF, TF-IDF, BM25, neural embeddings). The key geometric fact is sparsity: bag-of-words vectors live in high-dimensional spaces with mostly zero coordinates.

Distances as Inductive Geometry

Distance-based methods induce neighbourhood structure. A map is a metric if for all :

For vectors in :

For strings, the Levenshtein distance counts minimum edit operations (insert/delete/replace).

The cosine similarity

is a similarity, not a metric; it captures orientation rather than absolute magnitude.

Graph Data and Representation Dependence

A graph is , optionally augmented to

where stores vertex features and stores edge features. Common encodings are adjacency set, adjacency list, and adjacency matrix .

Two structural difficulties drive graph learning theory:

  1. permutation non-uniqueness: one graph admits many equivalent vertex orderings;
  2. variable size: and differ across instances.

Hence representation must be permutation-invariant or permutation-equivariant.

Weisfeiler-Leman Refinement and Graph Vectors

The Weisfeiler-Leman (WL) algorithm computes iterative colour refinements. Let be the colour of vertex at iteration . Initialisation is constant colouring . Update rule:

where denotes a multiset and HASH is injective on its input tuples. Iteration stops when the number of distinct colours stabilises.

A finite-dimensional graph feature vector is obtained by counting colour frequencies across iterations. If is the global colour index set, one graph-level representation is

Dot products between such vectors induce the Weisfeiler-Leman graph kernel.

Exam-Oriented Takeaways

For this lecture, you should be able to derive and explain:

  1. feature-wise scaling maps (min-max, mean normalisation, standardisation);
  2. formal metric axioms and the family;
  3. why cosine is a similarity measure rather than a metric;
  4. graph representation choices and permutation issues;
  5. the WL update equation and how colour histograms yield graph vectors.

This lecture underpins later choices of distance-based methods, feature engineering, kernel methods, and graph learning pipelines.

Lecture 3 Core Concepts of Machine Learning

This lecture consolidates the pipeline from learning paradigms to optimisation, then to statistical evaluation and complexity control. The unifying question is: how can a model fit observed data while maintaining predictive reliability on unseen data?

Learning Paradigms

Let denote the instance space and the target space. In supervised learning, we observe labelled samples

and learn a predictor . In unsupervised learning, only is observed and structure must be inferred without explicit labels.

The lecture also positions semi-supervised, self-supervised, active/passive, and online/batch settings as protocol variants that change information access or update timing, not the core objective of generalisable prediction.

Supervised Tasks and Loss Functions

Two canonical supervised tasks are:

Given loss , the empirical risk is

Typical losses from the lecture:

For linear regression with parameters and , training corresponds to minimising mean squared error on .

Empirical Risk Minimisation and Training Objective

Let be a hypothesis class. Empirical risk minimisation seeks

This is an optimisation problem over parameter space (for parametric models) or function space (more generally). The key caveat highlighted in the lecture: low training error alone is insufficient, because optimisation can over-adapt to sample idiosyncrasies.

Gradient Descent and Parameter Updates

For differentiable objective (e.g. empirical risk), gradient descent uses

with learning rate . Since points to steepest ascent, is a local steepest-descent direction.

In stochastic variants (SGD), the full gradient is replaced by a mini-batch estimate. This introduces gradient noise but improves scalability and often helps escape sharp local structures.

Risk, Empirical Risk, and Generalisation

With data-generating distribution , true risk is

The empirical risk is a sample estimate of . Their mismatch defines generalisation error:

Model selection must therefore target low true risk, not merely low training error.

Bias-Variance and Fit Regimes

As complexity increases, approximation error (bias) tends to decrease, while estimation sensitivity (variance) tends to increase. The resulting bias-variance trade-off explains:

  • underfitting at low complexity (high bias, low variance),
  • overfitting at high complexity (low bias, high variance),
  • an intermediate regime of best expected generalisation.

The “good fit” in the lecture corresponds to this intermediate region.

Regularisation as Complexity Control

Regularisation augments the data-fit term by a complexity penalty:

or dataset-level objective

For parameter vector :

tends to induce sparse solutions; shrinks weights smoothly. The hyperparameter controls the fit-complexity trade-off.

Exam-Oriented Takeaways

For this lecture, you should be able to state and manipulate:

  1. supervised setup and empirical risk definition;
  2. task-specific losses (0-1 and squared loss) and when they apply;
  3. ERM objective and gradient descent update equation;
  4. true risk vs empirical risk and the meaning of generalisation;
  5. regularised objective with penalties and the role of .

This lecture is the conceptual bridge from introductory examples to formal learning theory, optimisation analysis, and robust model selection.

Lecture 4 Basic Algorithms I

This lecture develops least-squares regression from first principles, then lifts the same optimisation pattern to polynomial and multivariate settings. The central message is that many seemingly different regressors are linear models in a transformed feature space.

Why Fit Models

Given data pairs, a fitted model serves four technical roles: compression of observations into a small parameter vector, interpolation/explanation of observed patterns, prediction on unseen inputs, and downstream decision support. In mathematical terms, we seek a map with low approximation error and acceptable generalisation behaviour while maintaining low representational complexity.

Linear Regression Setup

Assume training data

and a linear hypothesis

with parameters . A standard noise model is

The least-squares objective (empirical risk with squared loss) is

Optimisation by Gradient Descent

The gradient components are

With learning rate , gradient descent updates are

This is the iterative route used broadly in machine learning, but linear least squares also admits an exact solution.

Closed-Form Least-Squares Solution

Because is quadratic in , its minimiser is obtained by setting partial derivatives to zero. The scalar closed form is

where

Interpretation: is empirical covariance divided by empirical variance of the input coordinate.

Matrix Form and Normal Equations

Using the lecture orientation (samples as columns), define

Then and minimisation yields normal equations

hence

Equivalent row-sample notation gives the familiar .

Polynomial Regression as Linear Regression in Features

For degree , define

Introduce feature map

Then is linear in parameters. With design matrix

the same normal-equation solution applies:

Thus polynomial regression is not a different optimiser; it is a different representation.

Multiple Polynomial Regression

Now let and . The lecture writes

where denotes component-wise powers. This keeps linearity in parameter blocks and yields a stacked parameter vector in .

More generally, one may use any polynomial basis (including interaction monomials) and solve the same linear least-squares system in the induced feature space.

Numerical Remarks

The inverse in normal equations requires non-singularity of the Gram matrix ( or ). In ill-conditioned settings, one uses pseudoinverse or regularised least squares:

which connects directly to L2 regularisation from the previous lecture.

Exam-Oriented Takeaways

For this lecture, you should be able to derive and explain:

  1. least-squares objective for linear regression and its gradient;
  2. scalar closed-form parameters via vanishing derivatives;
  3. matrix normal equations and orientation-dependent formula forms;
  4. polynomial regression as linear regression after feature expansion;
  5. multivariate polynomial parameterisation and dimension counting.

This lecture establishes the algebraic template reused by many later linear-in-parameter models.

Lecture 5 Basic Algorithms II

This lecture extends linear modelling from regression to classification, then addresses two central limitations: non-linearly separable categorical patterns and model misspecification. The resulting toolkit combines discriminative linear models, tree-based symbolic partitioning, and ensemble aggregation.

Linear Classifiers and Hyperplane Geometry

Given

we seek a hypothesis of the form

with normal vector and threshold . The decision boundary is the hyperplane

Using augmented coordinates and , this becomes .

A Simple Linear Classifier via Least Squares

Direct optimisation of the sign loss is discontinuous. The lecture motivates a surrogate chain

near via the expansion . This yields a least-squares classifier:

with

When is invertible,

and prediction is performed by rather than by the raw linear score.

The Perceptron as Online Learning

The perceptron is presented as an online learning algorithm. At round , observe , predict , reveal , and update only on mistakes:

Thus the algorithm is mistake-driven and data-stream compatible, unlike closed-form least squares requiring a full batch and matrix inversion.

Novikoff Convergence Theorem and Mistake Bound

Assume there exist and a unit vector such that

Then the perceptron makes at most

mistakes.

Proof structure used in class:

hence after mistakes, . Conversely,

so and therefore . Combining both inequalities gives

Logistic Regression

Logistic regression models class probability by

Hence and , giving a confidence score in addition to a label.

With , one objective used in the lecture is

Equivalent Bernoulli negative log-likelihood form (for ):

The objective is convex, but there is no closed-form minimiser; optimisation is done with gradient methods.

Categorical Data, XOR, and Decision Trees

For Boolean attributes, linear separators can fail even after numeric encoding. The canonical obstruction is XOR-type behaviour, which is not linearly separable in the original two-bit space.

The lecture motivates decision trees via Boolean formula structure. Any Boolean function can be represented in disjunctive normal form (DNF):

Trees implement this logic as hierarchical tests: internal split nodes evaluate attributes; leaves store class outputs. A prediction follows one root-to-leaf path, so trees naturally classify unseen attribute combinations.

Split Quality, Top-Down Induction, and Stopping

To choose a split attribute , impurity is minimised. For class set ,

which is the Gini index criterion. Lower impurity indicates better class separation.

The induction pattern is recursive: start at the full sample, choose best split, partition into child subsets, remove/restrict used tests, and repeat. Without stopping, trees can memorise training data; practical constraints include maximum depth, maximum number of leaves, and minimum subset size. Impure terminal nodes typically predict the majority class.

Ensemble Methods: Bagging, Forests, and Boosting

Ensembling combines weak or unstable learners to improve predictive robustness.

For binary classifiers , majority voting is

Bagging creates diversity by bootstrap resampling: train base models on sampled subsets (with replacement), then aggregate votes. Random forests instantiate this with decision trees (often with feature subspace sampling at splits).

Boosting builds an additive model by sequential error correction. In regression form, with residuals ,

A fixed is common in simple derivations; practical variants use line search

The name gradient boosting reflects that approximates a descent direction in function space.

Exam-Oriented Takeaways

For this lecture, you should be able to reconstruct and justify:

  1. linear classifier geometry and augmented-vector form;
  2. least-squares linear classification as a surrogate for sign optimisation;
  3. perceptron mistake-driven update and Novikoff bound ;
  4. logistic regression objective, probabilistic interpretation, and convex optimisation properties;
  5. why XOR defeats linear separation and how decision trees solve this via hierarchical tests;
  6. Gini-based split selection, stopping criteria, and overfitting control;
  7. bagging/majority vote, random forests, and boosting as additive residual correction.

This lecture closes the transition from single-model linear methods to structured and ensemble predictors that trade interpretability, statistical robustness, and representational capacity.

Lecture 6 Experiment Design and Evaluation

This lecture formalises the end-to-end experimental protocol for machine learning: choose hyperparameters, train models, estimate generalisation, and verify that performance reflects intended behaviour rather than artefacts. The core principle is methodological separation of concerns: model fitting, model selection, and final assessment must use disjoint information.

Hyperparameters and Their Role

A hyperparameter is a configuration variable fixed before or outside parameter optimisation (for example, tree depth limits, number of estimators, regularisation strengths, or search budgets). If a model class is written as

then denotes trainable parameters, while denotes hyperparameters selected by an outer procedure.

The lecture stresses that predictive performance can vary strongly with , but the search space often scales combinatorially with the number of tuned dimensions.

Why Dataset Splitting Is Necessary

There are three logically distinct tasks:

  1. train model parameters;
  2. choose hyperparameters;
  3. estimate out-of-sample performance.

Hence one should separate a dataset into disjoint subsets:

Training uses , hyperparameter selection uses , and only the final locked model is evaluated on . Reusing test information during tuning biases the estimated generalisation error downward.

Holdout and k-fold Cross-Validation

For sufficiently large datasets, holdout splitting is often adequate. For smaller datasets, the variance of holdout estimates can be high due to small validation/test subsets.

k-fold cross-validation reduces estimator variance by partitioning data into folds and averaging fold scores:

where is trained on . Stratified splits are preferred in classification so label proportions remain approximately stable across folds.

Data Contamination and Preprocessing Order

Any preprocessing step whose statistics depend on data (for example standardisation parameters) must be fitted on training data only. For a transform with fitted state :

Fitting transforms on full data leaks information from validation/test into training and invalidates evaluation.

Evaluation Metrics by Task

Evaluation is a mapping from predictions and ground truth to a scalar criterion, and must match the task objective.

For regression :

For binary classification with confusion-matrix counts :

The lecture highlights that metric choice is application-dependent, because false positives and false negatives may have asymmetric costs.

Hyperparameter Tuning as Outer Optimisation

Let be a hyperparameter search space and the validation score of the model trained with . Tuning is

(or for loss metrics).

Two strategies discussed in class:

  • grid search: exhaustive over a finite grid ;
  • random search: sample for a fixed trial budget.

Grid search is simple but scales poorly in dimension; random search often uses budgets more efficiently when only a subset of hyperparameters strongly affects performance.

Baselines, Randomness, and Significance

Raw scores are uninterpretable without baselines. Typical baselines include majority-class prediction in classification and mean prediction in regression. A model should substantially exceed these references on unseen data.

Because many pipelines are stochastic (random splits, random forests, random search), reproducibility requires fixed seeds where possible. The lecture explicitly warns against tuning the random seed as if it were a model hyperparameter.

When comparing models across folds, apparent improvements may arise from sampling noise. The recommended protocol is to predefine a significance level (for example ), then test pairwise differences with a Student-t test on fold-wise scores.

Practical Reliability and Failure Modes

A high test score is necessary but not sufficient. Models may exploit spurious correlates (for example background artefacts) rather than task-causal structure. Therefore, evaluation must include sanity checks and targeted verification beyond aggregate metrics.

Practical guidance from the lecture:

  1. improve and inspect data quality before increasing model complexity;
  2. start with simple baselines and small prototypes;
  3. inspect raw inputs and transformed features;
  4. verify model behaviour under perturbations and plausible distribution shifts.

Exam-Oriented Takeaways

For this lecture, you should be able to reconstruct and justify:

  1. why train/validation/test separation is required for unbiased generalisation estimates;
  2. holdout versus k-fold cross-validation and when each is appropriate;
  3. leakage-safe preprocessing order (fit on train only, apply elsewhere);
  4. regression and classification metric formulas and their trade-offs;
  5. grid versus random search as hyperparameter optimisation strategies;
  6. the role of baselines, fixed seeds, and statistical significance testing;
  7. why good test metrics still require behavioural verification.

This lecture provides the experimental discipline needed to convert algorithmic knowledge into trustworthy, reproducible machine learning practice.

Lecture 7 Machine Learning Theory

This lecture introduces the statistical-learning-theory core of the course: a formal data-generating model, explicit assumptions, and finite-sample guarantees for generalisation. The central question is not whether a model fits observed data, but when fitting implies low true risk.

Formal Learning Setup

Let be the instance space, the label space, and an unknown distribution on . A sample of size is

For hypothesis class and loss

the empirical and true risks are

A hypothesis is consistent if . The theoretical objective is to guarantee small .

Hypothesis Classes and Learning Algorithms

The hypothesis class encodes representational bias (for example rectangles, linear separators, perceptrons, trees). It determines what can be learned in principle.

A learning algorithm is a map

returning . In particular, an ERM algorithm outputs

Core Assumptions

Two assumptions are made explicit:

  1. i.i.d. assumption: examples are independent draws from one fixed distribution ;
  2. realisability assumption: there exists with .

Realisability means no irreducible label noise relative to and perfect class-model alignment.

Realisable PAC Learning

PAC learning asks for probabilistic approximate correctness. A class is realisable PAC-learnable if there exists an algorithm and sample-complexity function such that for all , for all realisable , and all ,

Here is the target error and the failure probability.

Finite-Class Mistake Bound

If and realisability holds, returning any consistent hypothesis yields PAC learnability with

Proof skeleton from the lecture:

For a bad with ,

Applying a union bound over all bad hypotheses,

Imposing this probability to be at most gives the stated bound.

Papaya Example and Sample Complexity Interpretation

The lecture’s papaya toy calculation instantiates the bound numerically. With , , and a finite class size estimate :

Interpretation: about 124 i.i.d. labelled examples suffice to guarantee error at most with confidence at least under realisability.

Infinite Classes, Shattering, and VC Dimension

Finite-cardinality bounds do not directly control infinite classes. The structural replacement is shattering.

For , class shatters if for every label vector there exists with

The VC dimension is

with value if arbitrarily large finite sets are shattered.

Standard examples from class:

VC Dimension and PAC Learnability

For classes with finite VC dimension , ERM is PAC-learnable with sample complexity of order

Thus capacity control moves from counting hypotheses to measuring combinatorial expressiveness via shattering.

Exam-Oriented Takeaways

For this lecture, you should be able to reconstruct and justify:

  1. the formal tuple and definitions of and ;
  2. i.i.d. and realisability assumptions and why each is needed in guarantees;
  3. the realisable PAC statement with quantifiers;
  4. the finite-class sample-complexity derivation via consistency probability, union bound, and ;
  5. shattering and VC dimension definitions and canonical examples;
  6. the qualitative VC-based bound and its dependence on , , and .

This lecture establishes the theoretical bridge from empirical training success to explicit, distribution-level generalisation guarantees.

Lecture 8 Support Vector Machines and Kernel Methods

This lecture develops the max-margin principle for linear classification, then shows how kernelisation transfers linear methods to non-linear feature spaces without explicit coordinate lifting. The unifying theme is geometric control of generalisation through margin and function-class complexity.

From Linear Classifiers to Max-Margin Separation

For binary labels and inputs , a linear decision function is

Max-margin geometry introduces a margin parameter and normalised constraints

equivalently . The corresponding margin hyperplanes are

Points attaining equality are support vectors; they determine the boundary.

SVM Optimisation View

Under separability, the hard-margin SVM can be written (after standard scaling) as

For non-separable data, slack variables yield the soft-margin form

This objective corresponds to regularised minimisation with hinge loss

which is a convex upper bound on classification error.

Why Perceptrons Fail on XOR and How to Fix It

The lecture revisits the XOR obstruction: single linear separators cannot represent certain Boolean patterns in original coordinates. Two remedies are contrasted:

  1. layering (multi-layer compositions) to increase representational depth;
  2. mapping (feature lifting) so the problem becomes linear in transformed space.

Kernel methods implement the second route while avoiding explicit high-dimensional coordinates.

Kernel Perceptron and the Kernel Trick

Perceptron-style predictors admit an expansion

where are update-dependent coefficients. Replacing inner products by a kernel function gives

If for some feature map , then this is linear learning in feature space without computing explicitly.

Example Kernel Construction

For , consider

Expanding,

with one valid map

This illustrates polynomial lifting through kernel evaluation alone.

Common Kernels and Inductive Bias

The lecture highlights standard families:

These correspond to different smoothness/locality assumptions and therefore different generalisation behaviour.

Kernel Matrices and PSD Structure

Given data , the kernel matrix (Gram matrix)

must be symmetric and positive semidefinite:

Equivalent PSD characterisations used in the appendix:

  1. for all ;
  2. factorisation ;
  3. eigendecomposition with diagonal .

Closure example: if , then , so sums of valid kernels remain valid kernels.

A Small Learning-Theory Bridge

The lecture connects kernel methods to generalisation bounds of the form

Because direct 0-1 risk minimisation is non-convex/intractable, one minimises a convex surrogate (hinge-type objective) plus norm control. In RKHS formulations, restricting controls complexity (linked to Rademacher complexity bounds).

Applications and Structured Data

Kernel methods are presented as a generic similarity-learning framework beyond vectors: spectra, spatial statistics, and graphs. For graph kernels, naive subgraph-based kernels can be computationally hard; practical work uses tractable embeddings or restricted graph classes.

Exam-Oriented Takeaways

For this lecture, you should be able to reconstruct and justify:

  1. max-margin constraints and the role of support vectors;
  2. hard-margin versus soft-margin SVM objectives and the effect of ;
  3. kernel perceptron form ;
  4. explicit feature-map recovery for simple polynomial kernels;
  5. PSD kernel-matrix criteria and their equivalent formulations;
  6. why convex surrogate minimisation (hinge) is used instead of direct 0-1 loss;
  7. how kernels extend linear methods to non-linear and structured domains.

This lecture completes the line from linear separators to high-capacity similarity-based methods with explicit geometric and statistical control.

Lecture 9 Probabilistic Aspects of Machine Learning

This lecture shifts from deterministic label prediction to probabilistic inference. The central objective is to model uncertainty, incorporate prior beliefs, and exploit distributional structure beyond pure empirical-risk language.

Why Probabilistic Modelling

Compared with strict point prediction, a probabilistic model additionally provides confidence and calibrated uncertainty for decisions. It also enables prior-informed inference when data are scarce and allows modelling assumptions on the joint distribution rather than only worst-case distribution-free guarantees.

Bayes Optimal Classifier

Given data-generating distribution over , the Bayes-optimal classifier is

For 0-1 loss it minimises true risk among all measurable classifiers :

Two modelling routes follow:

  1. discriminative learning: model directly;
  2. generative learning: model (or ), then infer posteriors.

Probability Identities Used for Inference

For random variables :

Conditioning follows

Bayes Theorem and Coin-Type Example

For hypothesis variable and observed data ,

Interpretation in the urn example: prior over coin types is updated by toss outcomes into a posterior over coin types. Sequential evidence is incorporated recursively by reusing posterior-as-prior.

MLE, MAP, and Full Bayesian Inference

Three inference levels are distinguished:

  1. MLE

which ignores priors;

  1. MAP

which selects the posterior mode;

  1. full Bayesian inference: retain the complete posterior rather than a point estimate.

Posterior Predictive Distribution

For observed data and future datum , the posterior predictive distribution is

or an integral in continuous-parameter models. It averages predictions across hypotheses weighted by posterior plausibility and therefore propagates parameter uncertainty into predictions.

Bayesian Networks and Factorised Joint Models

A Bayesian network is a DAG over variables with factorisation

The graph encodes conditional independences that reduce representation size and inference cost. Without structure, a joint over binary variables needs parameters; conditional-independence factorisations can be exponentially more compact.

For chain-like structures, marginals can be computed by ordered elimination instead of brute-force summation over all assignments, reducing practical complexity substantially.

Naive Bayes as a Special Bayesian Network

In Naive Bayes, class variable is a parent of all features , and features are conditionally independent given class:

Prediction is

since does not depend on for argmax classification.

Empirical estimators from labelled data:

Exam-Oriented Takeaways

For this lecture, you should be able to reconstruct and justify:

  1. Bayes-optimal decision rule and why it minimises 0-1 risk;
  2. discriminative versus generative modelling viewpoints;
  3. Bayes theorem derivation and prior-likelihood-posterior decomposition;
  4. conceptual and mathematical differences between MLE, MAP, and full posterior inference;
  5. posterior predictive averaging over hypotheses;
  6. Bayesian-network factorisation and why it improves representational/inference efficiency;
  7. Naive Bayes assumptions, classification rule, and parameter estimation from counts.

This lecture introduces the probabilistic foundation for uncertainty-aware machine learning and structured probabilistic modelling.

Lecture 10 Dimensionality Reduction and Distance-Based Algorithms

This lecture studies two connected themes: reducing high-dimensional representations while preserving useful structure, and learning directly from distances in feature space. The practical motivation is that many real datasets are high-dimensional, noisy, and geometrically sparse.

Why Dimensionality Reduction

High-dimensional geometry behaves counterintuitively. A standard concentration intuition is that, as dimension grows, volume mass shifts in ways that make naive neighbourhood reasoning brittle (often called the curse of dimensionality). Consequently, reducing dimension can improve computation, denoising, and visual interpretability.

The lecture frames reduction as a trade-off between:

  1. retaining informative variance/geometry;
  2. minimising reconstruction or neighbourhood distortion;
  3. reducing computational cost.

Principal Component Analysis

Let centred data matrix be and covariance

For a unit direction (), one-dimensional projection is . PCA chooses maximising projected variance:

Equivalent viewpoint: minimise rank-1 reconstruction error

Using the Lagrangian

stationarity gives , so the first principal component is the eigenvector of with largest eigenvalue. Higher components are orthogonal eigenvectors ordered by eigenvalue magnitude.

Random Projection and the Johnson-Lindenstrauss Principle

When is very large, PCA may be costly (eigendecomposition typically scales poorly with ). Random projection uses a random linear map to dimension with complexity roughly .

The Johnson-Lindenstrauss guarantee states that for points, one can choose

so that pairwise distances are preserved up to multiplicative distortion with high probability.

Proof sketch idea in class: with Gaussian random matrix and map

the squared norm of projected difference vectors concentrates sharply around the original norm; then a union bound over all pairs yields the global preservation result.

t-SNE

t-SNE is a non-linear embedding method emphasising local neighbourhood preservation for visualisation. It converts distances into neighbour probabilities in high-dimensional space, then finds a low-dimensional configuration whose induced probabilities are close (via divergence minimisation).

Operational properties stressed in lecture:

  1. non-linear;
  2. stochastic/non-deterministic;
  3. hyperparameter-sensitive (not parameter-free);
  4. typically strong for visual cluster separation, but not a faithful global metric map.

k-Nearest Neighbours

k-NN predicts by local majority vote (classification) or local averaging (regression) among the closest training points under a chosen metric .

For binary classification,

where is the set of nearest neighbours of . The hyperparameter controls bias-variance behaviour: small gives high variance/local sensitivity, large gives smoother but potentially biased decisions.

k-Means Clustering

k-means partitions points into clusters by minimising within-cluster squared distances:

Lloyd-style iteration:

  1. initialise centroids (often from random data points);
  2. assign each point to nearest centroid;
  3. recompute centroids as cluster means;
  4. repeat until assignments stabilise.

The algorithm monotonically decreases objective value but can converge to local minima; initialisation therefore matters.

Exam-Oriented Takeaways

For this lecture, you should be able to reconstruct and justify:

  1. why high-dimensional settings motivate dimension reduction;
  2. PCA objective, covariance-eigenvector solution, and variance/reconstruction equivalence;
  3. random projection complexity and JL scaling ;
  4. conceptual difference between PCA and t-SNE (linear-global vs non-linear-local focus);
  5. k-NN decision rule and effect of ;
  6. k-means objective and alternating optimisation steps.

This lecture links geometric representation learning with simple, powerful distance-based prediction and clustering methods.

Lecture 11 Deep Neural Networks and Backpropagation

This lecture extends perceptron models to deep compositions of affine maps and non-linear activations. The central result is that depth increases representational capacity, but efficient training requires structured gradient computation via backpropagation.

From Linear Separation to Deep Non-Linear Models

Stacking purely linear layers collapses to one linear map, so depth alone does not resolve non-linearly separable tasks such as XOR. Let

Then for , hence no additional expressive class over a single linear classifier.

Introducing elementwise activation functions yields a non-linear hypothesis class:

Typical activations discussed in lecture are sigmoid, tanh, and ReLU.

Multi-Layer Perceptron Notation and Forward Pass

For layers (input , output ), define:

Here is the input, is the pre-activation vector, and the activation vector. For a supervised target , prediction is .

This gives the standard multi-layer perceptron forward recursion used throughout deep learning architectures.

Universal Approximation Perspective

The lecture states the universal approximation theorem intuition: for suitable non-linear activations, a feed-forward network with at least one hidden layer and finitely many parameters can approximate continuous functions on compact domains arbitrarily well.

A representative form is:

This is an expressivity statement, not an optimisation guarantee: approximation existence does not imply easy training or strong generalisation.

Learning Objective and Loss Design

Training minimises a differentiable empirical objective

Lecture emphasis:

  1. for classification, cross-entropy is standard;
  2. for regression, mean squared error is standard;
  3. differentiability of the computational path is required for gradient-based learning.

From Gradient Descent to Backpropagation

Vanilla gradient descent updates parameters by

but naive symbolic differentiation of a deep composite is computationally redundant. Backpropagation exploits chain-rule factor reuse by traversing the network in reverse topological order.

For a scalar example , write , . Then

The same decomposition principle scales to full neural networks.

Error Signals, Jacobians, and Parameter Gradients

Define layer error (pre-activation gradient)

Backward recursion for hidden layers (vector form):

which is the Jacobian-chain-rule form highlighted in lecture. Parameter gradients then become

Hence one training step is: forward pass, compute loss, backward pass for all , then gradient update for all .

Building-Block View of Deep Architectures

The lecture reframes deep learning as composition of modules with forward and backward interfaces. A linear feed-forward layer is one block; recurrent or attention/convolutional modules are alternative blocks. Architectures are formed by:

  1. stacking blocks (depth);
  2. adding skip connections;
  3. branching into multiple outputs.

This abstraction explains how MLPs, CNNs, RNNs, transformers, and generative architectures share the same optimisation principle while differing in structural priors.

Exam-Oriented Takeaways

For this lecture, you should be able to reconstruct and justify:

  1. why linear-layer stacking without activations is still linear;
  2. forward equations and ;
  3. role of differentiable loss functions and typical choices by task;
  4. backpropagation as efficient chain-rule reuse rather than a different optimiser;
  5. error recursion ;
  6. gradient formulas for weights and biases;
  7. modular building-block view and its connection to modern deep architectures.

This lecture provides the computational core that makes high-capacity non-linear models trainable in practice.

Lecture 12 Deep Learning Architectures as Composable Building Blocks

This lecture reframes deep learning implementation as composition of reusable computational modules. The key abstraction is that each module exposes a forward map and a backward gradient map, so complex networks can be assembled while preserving end-to-end trainability.

Building-Block Abstraction

Let a block be a parametric map

with local Jacobian and parameter gradient . During backpropagation, upstream error induces

Hence block internals are hidden once these interfaces are available.

Composition Patterns for Network Design

The lecture identifies three core composition patterns:

  1. depth by stacking blocks sequentially (standard feed-forward composition);
  2. skip connections by routing an earlier representation into a later block;
  3. branching by producing multiple outputs from shared intermediate features.

A residual-style skip pattern can be written as

illustrating that architecture design is fundamentally graph construction over differentiable operators.

Canonical Block Families

A linear feed-forward layer (MLP block) is the baseline module:

The lecture then positions additional families by inductive bias:

  1. recurrent blocks for sequential dependencies;
  2. convolutional blocks for local spatial structure;
  3. attention-based blocks for content-dependent interactions.

All remain trainable with the same gradient-flow principle from Lecture 11.

Architecture-Level Taxonomy

The closing overview maps tasks to common deep architectures:

  1. MLP for generic tabular/feed-forward settings;
  2. RNN for sequential data;
  3. CNN for vision-like local structure;
  4. transformer models for attention-centric sequence modelling;
  5. generative families including auto-encoder (AE), variational auto-encoder (VAE), and generative adversarial network (GAN);
  6. graph neural architectures for relational/graph-structured data.

The common theme is not the optimisation algorithm, but the chosen structural prior encoded by block topology.

Differentiability and Practical Constraint

A direct implementation requirement is that optimisation by backpropagation needs differentiable computational paths. The lecture notes that non-differentiable deep models can exist, but then standard backpropagation is not directly applicable and alternative optimisation schemes are required.

Exam-Oriented Takeaways

For this lecture, you should be able to reconstruct and justify:

  1. the forward/backward interface view of a neural block;
  2. why stacking, skipping, and branching are the core architecture operators;
  3. how different architecture families encode different inductive biases;
  4. why all differentiable architectures share the same backpropagation machinery;
  5. when differentiability assumptions fail and what that implies for training.

This lecture bridges mathematical training rules and practical neural-network system design via a unified compositional perspective.

Lecture 13 Bias and Fairness in AI

This lecture formalises fairness questions for machine-learning systems that directly affect human decisions. The core message is that fairness is not a single mathematical property but a family of partially incompatible constraints that must be selected with domain-specific policy judgement.

Decision Setting and Error Decomposition

Assume binary classification with predicted label , true label , and protected attribute . For each group , fairness analysis starts from confusion-matrix quantities:

Overall error,

is often insufficient because two systems with similar total error can distribute harms differently across groups.

COMPAS as a Motivating Case

The COMPAS recidivism-risk system illustrates that close aggregate error rates do not imply comparable group-level treatment. In the lecture data, error rates are numerically similar across groups, but false-positive and false-negative rates differ substantially between Black and White defendants. Hence fairness auditing must inspect conditional error profiles, not only aggregate accuracy.

This is a canonical example where stakeholders value different error types: defendants are disproportionately affected by high false-positive risk assignments, while judicial institutions may focus on false negatives related to missed high-risk cases.

Fairness Through Unawareness Is Insufficient

Removing protected attributes from the input does not generally remove discriminatory effects. Let denote non-sensitive features and protected status; in practice may contain proxies with high mutual information with (for example through location, spending, or administrative history). A learner can therefore reconstruct group information implicitly and reproduce disparate outcomes even when is omitted.

Group Fairness Criteria

The lecture contrasts three standard criteria.

  1. Demographic parity (naive statistical parity):

This equalises acceptance rates but ignores label prevalence and can be satisfied by trivial predictors.

  1. Calibration of risk scores :

This requires equal semantic meaning of the score across groups, but does not force equal error rates.

  1. Error-rate balance:

This enforces parity of false-positive and false-negative rates across groups.

Impossibility and Policy Choice

A central theoretical result is that, except for special cases (notably perfect prediction or equal base rates ), one cannot in general satisfy calibration and error-rate balance simultaneously. Therefore fairness design is not a purely technical optimisation target with a unique solution; it is a constrained policy choice requiring explicit normative priorities.

Individual Fairness Perspective

Group criteria can be complemented by individual fairness: similar individuals should receive similar predictions. If is a task-relevant metric on feature space, one seeks score mappings with controlled Lipschitz behaviour, informally

The major practical difficulty is defining a defensible similarity metric .

Fair Regression Construction

For linear regression with sensitive variable ,

the lecture presents a simple post-estimation adjustment:

where a group-invariant constant replaces the sensitive term. Typical choices include matching one reference group (for example or depending on coding) or preserving the training-set mean effect via . This is an average correction, not a full guarantee of non-discrimination.

Bias, Cost Asymmetry, and Transparency

Dataset bias propagates into learned predictors and may even be amplified by modelling choices. In deployment, false positives and false negatives often carry asymmetric costs, so objective design should weight them according to domain risk rather than default symmetric error minimisation.

To support accountability, the lecture highlights model cards as structured documentation of intended use, evaluation setting, limitations, and ethical considerations.

Human Decision Makers and Risk Scores

The Kentucky Pretrial Risk Assessment (KPRA) example shows that “human in the loop” does not automatically neutralise bias. After a policy change that made non-financial bonds the default for low/moderate risk categories, evidence indicates stronger judicial deviation from recommendations for moderate-risk Black defendants than for comparable White defendants. Thus unequal outcomes can emerge from interaction between model outputs, policy defaults, and human discretion.

Exam-Oriented Takeaways

For this lecture, you should be able to reconstruct and justify:

  1. why fairness analysis must separate aggregate error from group-conditional error;
  2. formal definitions and trade-offs of demographic parity, calibration, and error-rate balance;
  3. why fairness through unawareness is insufficient under proxy features;
  4. the incompatibility insight linking base rates, calibration, and error-rate parity;
  5. individual fairness as a metric-based constraint and its practical bottleneck;
  6. the fair-regression constant-replacement construction and its limits;
  7. why transparency artefacts and human-in-the-loop deployment are necessary but not sufficient safeguards.

This lecture shifts machine learning from pure predictive performance to socio-technical system design under explicit fairness constraints.

Lecture 14 Reinforcement Learning

This lecture introduces reinforcement learning (RL) as a sequential decision framework in which an agent interacts with an environment, receives rewards, and learns a policy that optimises long-run return rather than one-step prediction accuracy.

Core Agent-Environment Formalism

At time step , the agent observes state , chooses action , receives reward , and transitions to . For discount factor , return is

The objective is to find policy maximising

Hence RL optimisation is dynamic and trajectory-level, not i.i.d. sample-level as in supervised learning.

Value Functions and Bellman Structure

For a fixed policy , the state-action value function is

Control methods approximate optimal action values and derive greedy or near-greedy policies. The lecture emphasises that Bellman operators provide the structural recursion behind update rules.

Q-Learning

Given transition sample , tabular Q-learning updates only the visited pair:

with learning rate . This is a stochastic approximation / semi-gradient form with temporal-difference target

Speedy Q-Learning

The lecture discusses Speedy Q-learning, which introduces a correction using both and under the empirical Bellman operator to accelerate convergence behaviour. Conceptually, it modifies the basic TD recursion by adding a term that compensates for drift between successive iterates.

Distributional Reinforcement Learning

Instead of learning only expected return, distributional RL models the full return random variable

This yields risk-sensitive information (tail behaviour, spread, multimodality) unavailable from expectation-only methods. In categorical distributional RL, one discretises return support and studies contraction of projected Bellman updates in suitable metrics (here, Cramer-type distance).

PAC-Style Guarantees for Distributional RL

A key theoretical block in the lecture is a Probably Approximately Correct (PAC) analysis for a speedy categorical distributional update under assumptions including finite state-action space, bounded rewards, , and Robbins-Monro style step-size conditions.

The resulting high-probability bound has the canonical form

with probability at least , where is the iterate and the fixed point of the projected distributional Bellman operator. The first term captures contraction bias decay; the second captures stochastic estimation error.

Proof Architecture and Concentration

The proof strategy presented in the lecture follows five components: stability of iterates as probability measures, martingale-difference representation of error processes, inductive recursion bounds, maximal Hoeffding-Azuma concentration at atom level, and inversion to obtain explicit confidence-style guarantees.

This connects RL convergence analysis to the same probability toolkit used in generalisation theory: concentration inequalities translate random-sample effects into explicit confidence bounds.

Policy Evaluation and Off-Policy Difficulty

After learning a policy, independent evaluation is essential. In particular, off-policy evaluation (estimating performance of a target policy from data generated by another behaviour policy) is highlighted as intrinsically difficult and variance-sensitive, motivating robust lower-confidence validation procedures in high-stakes applications.

Empirical Scope and Application Cases

The lecture situates RL across game domains (Atari, chess, Go), control (autonomous driving, industrial automation), and scientific/medical decision support. AlphaGo/AlphaZero-style results are used to illustrate that a single RL framework with minimal domain priors can achieve superhuman performance in complex sequential tasks.

Applied case studies from autonomous driving, cryogenic detector control, and sepsis treatment are used to motivate distributional RL and policy-evaluation methodology in safety-critical settings.

Exam-Oriented Takeaways

For this lecture, you should be able to reconstruct and justify:

  1. the agent-environment loop and discounted return objective;
  2. definitions of , Bellman-style targets, and the Q-learning update;
  3. why Speedy Q-learning modifies standard temporal-difference recursion;
  4. expectation-based versus distributional RL, including and ;
  5. the structure of PAC-style high-probability error bounds in distributional RL;
  6. where martingale concentration (Hoeffding-Azuma) enters the analysis;
  7. why off-policy evaluation is difficult and central for reliable deployment.

This lecture extends machine learning from static prediction to sequential optimisation under uncertainty, where both asymptotic convergence and finite-sample reliability must be analysed.