Understand machine learning by seeing it move.
Machine learning and deep learning, explained visually, from basic math to LLMs. Drag vectors, roll a ball down a loss curve, step through backpropagation one number at a time.
Welcome back. Continue “” →
- Free forever. No paywall, no sign-up.
- Works on your phone, even on slow data. Turn on Lite Mode in settings.
- Private. Your progress stays on your device.
- Three depths in every lesson: Intuition, Math and Code.
Try a lesson
Good places to start. Each one stands on its own and links back to what it builds on.
P0.2How a machine "learns"The learning loop in five words - data, model, prediction, loss, update. Watch a line fit itself to points one step at a time, and see why this same loop trains everything from a straight line to a chatbot.P1.B3Dot product and cosine similarityOne number that says how much two vectors point the same way. It powers search, recommendations and the attention inside every LLM.P1.C3The chain ruleA function inside a function changes through two steps, and the two rates multiply. See why with gears and nudges, use the rule on e^(2x), ln(1+x^2), the sigmoid, tanh and two losses, then follow a long chain backward, which is exactly what backpropagation does.P1.F3Gradient descentWalk downhill one step at a time. The algorithm that trains nearly every neural network, and why the step size matters so much.P4.8Backpropagation: step by step with numbersFollow every number through a forward pass, a backward pass and one weight update, and see the local rules that make backprop work, then learn how to check it.P1.B13Singular Value DecompositionSee every matrix as rotate, stretch, rotate. Learn singular values and the SVD, keep only the biggest layers to compress a picture or a weight matrix, build the pseudo-inverse, and read the condition number and numerical rank off the singular values.
Show all 138 ready lessons
P0.1What are AI, ML and Deep Learning?Three terms that get mixed up, as three nested circles. See the difference between writing rules and learning from data, learn the key vocabulary, and tour more than 70 years of AI history, including its two "winters".P0.3Kinds of learningSupervised, unsupervised, self-supervised and reinforcement learning, side by side. Learn what data each one needs, what it learns from, and how real systems such as chatbots combine them. Then test yourself with a game.P0.4Your toolkitWhere you will run code in this course, and how. Run your first Python and NumPy cells right here in the browser, learn what a notebook is, how to read an error message, and when to use Google Colab or your own computer. No install and no GPU needed to start.P0.5How to use this siteA guided tour of a lesson page (tabs, widgets, quizzes), how your progress is saved on your own device, how to save data with Lite Mode, how to pick a learning path, study habits that research supports, and how to report a mistake.P1.A1Functions and graphsA function turns an input into exactly one output. Learn to read formulas, tables and graphs, and to recognise the lines, parabolas and exponentials that machine learning is built from.P1.A2Exponents and logarithmsPowers multiply, logarithms undo them. Learn the exponent and log rules, the number e, log scales, and why machine learning turns products into sums with logs.P1.A3Summation, products and indicesRead and write Σ (sum) and Π (product) notation, unroll them into plain additions, use the rules for sums, handle double sums, and avoid the classic off-by-one bug between math and Python.P1.A4Sets, notation and reading mathLearn the small set of symbols that papers and textbooks use (sets, ∈, ℝⁿ, ∀, argmax, hats, ∝, ∼) and a step-by-step method for reading any formula, with an interactive, printable cheat sheet.P1.A5The sigmoid, tanh and other squashing functionsBuild the sigmoid and tanh from e^(−z), see why they squash any number into a fixed range, watch them saturate (go flat) for large inputs, and meet the step, softsign and hard sigmoid. Includes the logit, stretching and shifting, and safe code.P1.B1Scalars, vectors and spacesA vector is one object with three faces (an arrow, a list of numbers and a point). Learn to move between them, and see why images, words, houses and model weights are all vectors.P1.B2Vector operationsAdd vectors, stretch them, subtract them and combine them. The few moves behind every gradient step, every average of embeddings and every residual connection.P1.B4Norms and distancesHow long is a vector, and how far apart are two of them? Three ways to measure (L1, L2, L∞), the shapes of their unit balls, and why the choice changes which point counts as nearest.P1.B5Matrices as data and as transformationsA matrix is a rectangle of numbers with two jobs in machine learning. It stores data (one row per example) and it acts on vectors, warping space. Learn to read both.P1.B6Matrix multiplicationMultiply two matrices as row times column, check shapes before you start, and see the product as "first one map, then the other". Learn why the order matters, what a product costs, and where it appears in neural networks.P1.B7Span, independence, basis and rankWhich vectors can you make from a few vectors, and which of them are redundant? Learn span, independence, basis, subspaces and rank, see why a matrix can squash the plane, and where redundancy shows up in machine learning.P1.B8The determinantHow much does a matrix stretch area? Learn the determinant as a signed area and volume, what its sign and zero mean, the rules it obeys, how computers calculate it, and where it appears in machine learning.P1.B9Inverse and linear systemsUndo a matrix with its inverse, learn when no inverse exists, and solve Ax = b by elimination. See one, no and infinitely many solutions as lines and as columns, and learn why code solves instead of inverting and what a nearly singular system does to errors.P1.B10Transpose, symmetric and orthogonal matricesFlip a matrix across its diagonal, see what the transpose really does to a dot product, meet symmetric matrices, and learn why rotations and reflections (orthogonal matrices) keep every length and angle and are undone by their transpose.P1.B11Projections and least squaresDrop a point straight onto a line or a plane, see why the error meets the plane at a right angle, and use that picture to derive the normal equations, fit a line to data, and understand what NumPy's least-squares routine does.P1.B12Eigenvalues and eigenvectorsFind the directions a matrix only stretches, flips or squashes. Learn eigenvalues and eigenvectors as the way to see what a matrix really does, how to find them, why repeated multiplication is ruled by the biggest one, and where they appear in machine learning.P1.B14Tensors, shapes and broadcastingCount the axes of an array, index and reshape it without scrambling it, add up along the right axis, and learn the one rule NumPy uses to combine arrays of different shapes, including the silent shape bug that turns a loss into the wrong number.P1.B15Linear algebra in neural nets: a mapSee where the tools of the linear algebra module live inside a neural network, from a dense layer to a tiny attention example worked by hand, and which later lesson teaches each piece.P1.C1Rates of change and the derivativeStart with average speed, shrink the time interval until you get the speed at one instant, and meet the derivative as the slope of a curve. Zoom into curves until they look straight, estimate slopes with finite differences, and see where a derivative does not exist.P1.C2Derivative rulesReplace the limit with shortcuts. Learn the constant, sum, power, exponential, logarithm, product and quotient rules, see why each one is true, check every rule against a finite difference, and use them to get the slopes of the sigmoid, tanh and a squared-error loss.P1.C4Partial derivativesA loss depends on many numbers at once. Nudge one input while the others stay put, and the ordinary derivative of P1.C1 becomes a partial derivative. Slice a 3-D surface, compute partials with the rules of P1.C2, find both slopes of the P0.2 loss, and see why one partial per weight is what training needs.P1.C5The gradientPut the partial derivatives of P1.C4 into one vector, the gradient. See it on a contour map, check the first-order approximation with numbers, and learn why the gradient points uphill, is perpendicular to the contour lines, and has a length equal to the steepest slope. Then step against it, which is gradient descent.P1.C6Directional derivativesCut a surface along a straight line and read the slope of the cut. See the directional derivative as a limit, prove that it equals the gradient dotted with the direction, handle vectors that are not unit vectors, and learn where the formula fails.P1.C7Vector functions and the JacobianA layer of a neural network turns many numbers into many numbers. Collect all its slopes into one matrix, the Jacobian, see that near a point the curved map acts like that matrix (a tiny square becomes a parallelogram), and use it for the chain rule, area scaling, and the products that backpropagation computes.P1.C8The Hessian, curvature and Taylor approximationLearn how the ground bends. Build Taylor polynomials one term at a time, see where they stop working, then collect all second derivatives in the Hessian matrix. Its eigenvalues tell a bowl from a hill or a saddle, set the largest safe learning rate, and give Newton's step.P1.C9Integrals as accumulationAdd up a rate to get a total, see that this is the area under a curve, build it from thinner and thinner rectangles (Riemann sums), and meet the integral, the fundamental theorem of calculus, antiderivatives, and the way probability densities use all of it.P1.C10Computational graphs and automatic differentiationDraw a calculation as a graph of simple steps, run it forward for the values, then run it backward once to get the slope with respect to every input. Compare reverse mode with forward mode, finite differences and symbolic formulas, and write a tiny autodiff engine in Python.P1.C11Matrix calculus for MLThe short list of rules for gradients of vectors and matrices, with a shape check for each. Derive the gradients of a dense layer, a batch, xᵀAx, a squared norm, least squares and softmax with cross-entropy, check them by nudging, and learn to spot the common shape bugs.P1.D1Probability basicsBuild probability from scratch. Outcomes, sample spaces and events, the three rules every probability must obey, counting equally likely outcomes, and the difference between a probability and the frequency you see in a short run. A coin and dice simulator lets you watch frequencies settle.P1.D2Random variablesTurn the outcomes of a random experiment into numbers. Meet discrete and continuous random variables, the PMF, the density (PDF) and the CDF, see them linked by one draggable point, and read probabilities, intervals and quantiles from them.P1.D3Common distributionsMeet the six distributions behind most of machine learning, Bernoulli, binomial, categorical, uniform, Gaussian and Poisson. For each one you see what it models, its formula, its mean and variance, and where it appears in a loss function. A gallery with parameter sliders lets you change each one and read off probabilities.P1.D4Expectation and varianceSummarise a whole distribution with two numbers. The expected value is its balance point and its long-run average; the variance and standard deviation say how far values stray from it. Drag a histogram on a fulcrum, learn linearity of expectation, the rules for variance, why an average of n draws has spread σ/√n, and why the mean is the best constant guess under squared error.P1.D5Joint, marginal and conditional probabilityDescribe two random quantities at once. Read a joint probability table, add up its rows and columns to get marginals, slice and renormalize it to get conditional probabilities, and test whether the two quantities are independent. Click a heatmap to condition on a row or a column, then meet the product rule, the chain rule, the law of total probability, conditional independence and the i.i.d. assumption behind most of machine learning.P1.D6Bayes' theoremUpdate a probability when evidence arrives. Count 1000 people to see why a positive result from a good medical test is often a false alarm, derive Bayes' theorem from the product rule, learn prior, likelihood and posterior, the odds form, updating with several results and several hypotheses, and what it means for classifiers, precision and spam filters.P1.D7Covariance and the multivariate GaussianMeasure how two quantities move together with covariance and correlation, collect all the pairs into a covariance matrix, and see the multivariate Gaussian as a cloud whose outline is an ellipse. Drag the ellipse and watch the matrix, its eigenvalues and eigenvectors, the conditional mean and the sample covariance update, then meet marginals, conditionals, sampling with a Cholesky factor and Mahalanobis distance.P1.D8Law of large numbers and the Central Limit TheoremWhy averages settle and what shape their wobble has. Prove from Chebyshev's inequality that the average of many independent draws gets close to the mean, watch a Galton board turn coin steps into a bell curve, and see in a sample-mean histogram that the average of n draws from almost any population is close to Gaussian with spread σ/√n, and where that fails.P1.D9Sampling and Monte CarloEstimate a probability, an average or an integral by drawing random samples. Throw darts at a square to estimate π, see why the error shrinks like 1/√n in any dimension, and learn how computers turn uniform random numbers into draws from other distributions, by table lookup, the inverse CDF, Box–Muller and rejection.P1.D10Maximum Likelihood EstimationHow to fit a model's parameters to data. Write the probability of the data as a function of the parameters, take its log, and find the maximum. Slide a Gaussian over data and watch the log-likelihood peak at the sample mean, derive the coin and Gaussian estimates, and see why the same recipe gives mean squared error, binary cross-entropy and cross-entropy.P1.D11MAP estimation and priorsKeep the prior that maximum likelihood throws away. See how prior × likelihood gives a posterior for a coin, how a Beta prior acts like imagined flips, why the prior fades as data arrive, and why a Gaussian prior on weights is L2 regularization (weight decay) and a Laplace prior is L1.P1.D12Descriptive statistics and visualizationSummarize a data set with a few numbers and a few pictures. Compare mean, median and mode, see which spread measures survive an outlier, read percentiles and box plots, standardize features, and learn why a summary can hide the shape of the data. Add outliers to a data set and watch the mean move while the median stays.P1.D13Statistical thinking for MLA number measured on a sample is an estimate, not the truth. Learn standard errors and confidence intervals, hypothesis tests and p-values, power, multiple comparisons, and why correlation is not causation. Run thousands of simulated experiments and see how often two identical models look different.P1.E1Information and surpriseHow to measure how surprising an event is. Rarer events carry more news, and the logarithm is the function that makes the surprise of independent events add up. Slide a probability along the curve, switch between bits and nats, and see why the loss of a classifier or a language model is a surprise.P1.E2EntropyEntropy is the average surprise of a source, one number for how hard its next outcome is to predict. Reshape a distribution and watch the entropy move, see why the uniform distribution is the most uncertain, and learn why entropy is also the limit for lossless compression and the quantity behind decision-tree splits, model confidence and temperature.P1.E3Cross-entropyCross-entropy is the average surprise of outcomes from the true distribution p when they are measured with a model q. See why it is the standard loss for classification and language models, how it splits into the entropy plus an extra cost for a wrong model, and how to reshape a prediction and watch the loss change live.P1.E4KL divergenceThe KL divergence is the extra cost of using a model q when the data come from p. See why it is at least 0, why it is not symmetric, how to compute it for two Gaussians, and why minimizing it in the two directions gives a broad fit that covers every peak or a narrow fit that locks onto one.P1.E5Mutual information and perplexityMutual information is how much one variable tells you about another, and perplexity is the number of equally likely choices a model is effectively unsure among. Learn joint and conditional entropy, the Venn picture and where it breaks, why correlation can miss a dependence that mutual information sees, how a decision tree scores a split, and how to read and not misread the perplexity of a language model.P1.F1What is optimization?Training a model means choosing parameters that make one number, the loss, as small as possible. Turn a loss landscape around, find its lowest point, and learn why a lowest point may be hard to find, not unique, or missing.P1.F2Convex vs. non-convexSome loss landscapes have a single valley, so rolling downhill finds the best point from any start. Others have many valleys, saddles and plateaus. Learn the chord test that tells them apart, and roll a ball into different valleys from different starts.P1.F4Stochastic and mini-batch gradient descentEstimate the slope from a few random examples instead of all of them. Each step is cheaper and a little noisy, and that trade is how nearly every neural network is trained.P1.F5Momentum and adaptive steps (preview)In a long, narrow valley plain gradient descent zig-zags across it and crawls along it. Momentum remembers recent steps, and adaptive methods give every parameter its own step size. A first look at the ideas inside Adam.P1.F6Second-order methodsGradient descent uses only the slope. Newton's method also uses the curvature, and on a quadratic it jumps straight to the minimum. It can also be sent to a maximum or a saddle, and it is too expensive for large networks.P1.F7Constrained optimization and Lagrange multipliersSometimes the best point must stay on a curve or inside a region. See the contour of the objective touch the constraint, turn that picture into the Lagrange conditions, read the multiplier as a price, and meet inequality constraints and the KKT conditions.P1.G1How computers store numbersA computer keeps every number in a fixed number of bits. This lesson shows how integers and floating-point numbers (fp32, fp16, bf16, fp8) use those bits, why 0.1 is never stored exactly, and what that means for precision, range, rounding and memory.P1.G2Numerical stabilityComputers store numbers with a largest and a smallest size. Softmax, log-probabilities and sigmoids can fall outside that range even when the maths is fine. The cure is a shift of the scores and a few rewritten formulas, such as log-sum-exp, log1p and softplus.P1.G3Randomness, seeds and reproducibilityComputers make random-looking numbers with a formula and a starting number, the seed. Learn how that works, how to repeat a run exactly, why GPU runs can still differ, and why the spread between seeds is real information.P1.G4Big-O and compute costHow to count the work a program does, why only the growth rate matters for large inputs, and how FLOPs, memory and the n² of attention decide what is affordable in machine learning.P2.1Python essentials for MLThe parts of Python that machine-learning code uses every day, taught with runnable cells. Values and types, lists, dictionaries, loops, functions, comprehensions, classes, errors and imports, plus the traps (copies, default arguments) that cause real bugs.P2.2NumPy: arrays and vectorizationWhat a NumPy array is, why one array operation beats a Python loop, and the everyday toolkit of dtypes, slicing, views and copies, reshaping, axis reductions, masks, stacking and sorting, with the bugs that catch beginners.P2.3NumPy broadcasting and einsumUse broadcasting for the jobs you meet in real ML code (standardising columns, normalising rows, distance tables, one-hot labels, masks), catch the silent shape bugs, and learn einsum, the notation that names every axis so a dot product, a matrix product and attention scores all look alike.P2.4Plotting with MatplotlibDraw the plots that machine learning uses every day with Matplotlib - loss curves on a log axis, scatter plots coloured by class, histograms whose bins change the story, images and confusion matrices with imshow, grids of subplots - in the Figure and Axes style, and learn to save them and to keep them honest. Run and edit real Matplotlib code in your browser.P2.5Data wrangling with PandasLoad a table with pandas, look at it, pick rows and columns, filter, group, fill missing values, clean it and turn it into the arrays X and y that a model trains on. Walk through the Titanic passenger data in code that runs in your browser.P2.6PyTorch tensors and autogradMeet the PyTorch tensor (a NumPy-like array with a dtype, a device and a memory of how it was computed), then let autograd find gradients for you, avoid the classic bugs, and run gradient descent by hand on the line from P0.2.P2.7The PyTorch training loopWrite the loop that trains almost every neural network, in PyTorch. Build a model with nn.Module, feed it batches with Dataset and DataLoader, and run the five-line step of forward, loss, zero_grad, backward and step. Then add validation, devices and the bugs that catch everyone once.P2.8Tooling: Git, environments, Hugging Face HubThe three tools that turn a notebook into a project you can reproduce and share. Virtual environments (venv, conda, uv) and pinned packages, Git for history and teamwork, and the Hugging Face Hub for loading a small pretrained model in five lines, safely.P3.A1The supervised learning setupEvery supervised learning problem has the same parts. Learn them once, with small numbers: examples and features, labels, the data set, the model and its hypothesis class, the loss and the risk, training and inference, and why a low training loss is not the goal. Then walk through the pipeline from collecting data to monitoring a model.P3.A2Linear regressionFit a straight line (or a flat plane) to data. Measure the error with the mean squared error, find the best weights in one step with the normal equations or step by step with gradient descent, and learn when each is the better tool, what R² says, and where a linear fit misleads.P3.A3Polynomial regression, underfitting and overfittingTurn linear regression into a curve fitter by adding powers of x, then watch a degree slider show the central trade-off of machine learning. A too simple model underfits, a too flexible one memorises noise, and only data the model has not seen tells them apart.P3.A4Train, validation and test setsWhy a model must be judged on data it has not seen, what the training, validation and test sets are each for, how to cut the data fairly (random, stratified, grouped, in time order), and how k-fold cross-validation uses small data well.P3.A5The bias–variance trade-offWhy a model that is too simple and a model that is too flexible both fail on new data. Split the expected squared error into bias, variance and noise, watch many fits to resampled training sets, and see why test error is U-shaped.P3.A6Regularization: L1 and L2Add a price on large weights to the loss. See how the L2 penalty (ridge) shrinks every weight and always has a solution, how the L1 penalty (lasso) switches weights off exactly, and why the corners of the L1 diamond are the reason.P3.A7Logistic regressionTurn a weighted sum into a probability with the sigmoid, draw the line that separates two classes, learn it by minimizing the binary cross-entropy, and see why it is convex, what the weights mean as odds, and why unregularized weights grow without bound on separable data.P3.A8Softmax regressionClassify into many classes with one linear score per class. Turn the scores (logits) into probabilities with the softmax, see why only the differences between logits matter, find the linear decision regions, and train the model with the cross-entropy loss and its simple gradient p − y.P3.A9Evaluation metricsHow to score a classifier honestly. Count the four kinds of outcome in a confusion matrix, then read accuracy, precision, recall, F1, ROC curves, AUC and precision-recall curves from it, move a threshold to see the trade-off, average over many classes, and pick the metric that matches the cost of each kind of mistake.P3.A10Calibration and class imbalanceWhen a classifier says 0.9, does it turn out right about 90% of the time? Build a reliability diagram, measure the gap with ECE, the Brier score and log loss, fix it with Platt or temperature scaling, and see how rare classes, class weights and resampling shift the probabilities.P3.A11Features, scaling and data leakageTurn raw columns into numbers a model can use. Build a few features, rescale them with standardization, min–max or robust scaling, encode categories with one-hot codes, and learn the leaks (a feature built from the answer, preprocessing fitted on test rows, duplicates, groups and time) that make a test score too good to be true.P3.B1k-Nearest NeighborsPredict by looking up the k most similar stored examples and letting them vote or average. See how k sets the flexibility of the model, why feature scale and distance choice decide who the neighbors are, what it costs to search, and why neighbors stop being near in many dimensions.P3.B2Naive BayesTurn word counts into a probability that an email is spam. Apply Bayes’ rule to a classifier, state the naive independence assumption exactly, train by counting, fix zero counts with smoothing, work in log space, and build the filter step by step on the eight emails of P0.1.P3.B3Decision treesHow a decision tree predicts with a chain of yes/no questions, how it is grown one greedy split at a time using Gini impurity or entropy, why an unlimited tree memorizes its training data, and what trees are good and bad at.P3.B4Bagging and random forestsOne deep decision tree overfits, but the average of many slightly different trees does not. Draw bootstrap samples, average the trees, see why trees must differ from one another, and use the leftover data as a free validation set.P3.B5BoostingBuild a strong model by adding many weak ones one at a time, each aimed at what the earlier ones got wrong. Work AdaBoost through by hand, see gradient boosting as gradient descent on the predictions, watch trees fix residuals round by round, and learn the settings and libraries that matter in practice.P3.B6Support Vector MachinesMany lines separate two classes, so which one should a classifier pick? A support vector machine takes the line with the widest empty street. See why only the points on the edge of the street matter, how the penalty C lets a few points break the rules, and how the hinge loss turns all of it into a loss you can train.P3.B7The kernel trickSome data no straight line can separate, but lifting it into more dimensions can make it easy. The kernel trick gets the benefit of the lift without ever building the new coordinates, by replacing dot products with a similarity function.P3.C1k-means clusteringFind groups in data that has no labels. Alternate between assigning each point to its nearest centre and moving each centre to the mean of its points, see why this never makes the objective worse, why the start matters, how k-means++ and restarts help, and how to choose the number of clusters.P3.C2Gaussian mixtures and EMCluster data with soft labels. Describe the data as a mixture of Gaussians, fit it with the expectation-maximization loop (responsibilities, then weighted means, covariances and weights), watch the ellipses move, and learn what can go wrong: local optima, collapsing components, and how many components to use.P3.C3Principal Component AnalysisData with many features often vary along only a few directions. Principal component analysis finds those directions, in order of how much the data spread along them. See a line rotate to catch the most variance, find the same direction by three routes, and learn how many components to keep.P3.C4t-SNE and UMAPDraw high-dimensional data as a flat map that keeps neighbours together, even when the data lie on a curve that PCA cannot flatten. See how the perplexity setting changes the picture, and learn the ways these maps are easy to misread.P3.C5Anomaly detectionFind the examples that do not fit. Turn every method into a score, see how the alarm threshold (the contamination setting) sets how many points are flagged, and compare a Gaussian model, nearest-neighbor distances and an isolation forest on the same data.P3.C6Hierarchical and density clusteringTwo ways to find groups without choosing k first. Hierarchical clustering merges the closest clusters one at a time and draws the result as a tree, and DBSCAN grows clusters through crowded regions and labels the rest as noise. Build a dendrogram step by step, cut it, and watch core, border and noise points change with the radius.P4.1From neurons to the perceptronMeet the artificial neuron, a weighted sum of its inputs followed by a decision. See where the idea came from and where the brain analogy stops, build AND, OR and NOT gates by hand, see why the boundary of a neuron is a straight line, and learn what a single neuron cannot do.P4.2The perceptron learning rule and the XOR problemTeach a perceptron by letting it make mistakes and nudging the line after each one. Follow a full run by hand, see why the rule stops when the classes can be split by a line, and why on XOR it never stops. Then meet the history and the two ways out.P4.3Multi-layer perceptronsStack layers of neurons so that a hidden layer bends the plane until a straight line can finish the job. Build a network for XOR by hand, count parameters, see why the squashing step is essential, and watch a small network train.P4.4Activation functionsWhy a neural network needs a nonlinear step after every layer, and how the step, sigmoid, tanh, ReLU, Leaky ReLU, softplus, ELU, GELU and SiLU compare. Their formulas, slopes, saturation, dead units, a table of values, and what each does to a tiny network.P4.5The forward pass in matrix formWrite a layer as one matrix product, run a whole batch of examples through a network at once, track the shape of every matrix, count parameters and multiply-adds, and learn the shape bugs that make a network silently compute the wrong thing.P4.6Loss functionsA loss function turns a prediction and the right answer into one number that training can shrink. Compare mean squared error, absolute error and Huber loss for numbers, and binary and multi-class cross-entropy for labels. See how each one prices a mistake, how it pushes the model, and how each comes from a guess about the noise (maximum likelihood).P4.7Backpropagation: intuitionA network makes one mistake and has millions of weights. Learn how the blame for the loss can be handed back to every weight in a single backward sweep, and why that beats nudging each weight and re-running the network.P4.9Build an autograd engine from scratchWrite about 100 lines of Python that record a calculation as a graph and run backpropagation on it. Check the result against P4.8's hand numbers, finite differences and PyTorch, then train a tiny neural network with it.P4.10Build an MLP from scratch (NumPy)Write a complete neural network in about 50 lines of NumPy, with no framework. Initialize it, run the forward pass and keep its values, write the backward pass layer by layer with every shape, check it against finite differences, train it with mini-batch SGD on handwritten digits, and read the learning curves and the confusion matrix.P4.11Universal approximationBuild a ramp from two ReLU units and a hat from three, add hats to follow any curve on an interval, and see the error shrink as units are added. Then the theorem, what it does not promise, and why depth can need far fewer units than width.P4.12Weight initializationHow to choose the starting weights of a neural network. Why all zeros fails, why weights that are too small or too large make signals vanish or explode layer by layer, and how the variance rules of LeCun, Xavier (Glorot), He (Kaiming) and orthogonal initialization keep the scale steady. A widget shows the activations of a 10-layer network for each choice.P4.13OptimizersBackpropagation gives the gradients. An optimizer decides the step. Compare SGD, momentum, Nesterov, AdaGrad, RMSProp, Adam and AdamW on a loss surface and in a training loop, and see what each one remembers and costs.P4.14Learning-rate schedulesThe best learning rate is not the same at the start and at the end of training. Compare constant, step, exponential, cosine, warmup and one-cycle schedules, and find a starting rate with the learning-rate range test.P4.15Batch size and training dynamicsThe batch size sets how noisy each step is, how many steps an epoch has, and how much memory a step needs. See how the learning rate must move with it, where larger batches stop paying off, what is and is not known about generalization, and how gradient accumulation fakes a bigger batch.P4.16Vanishing and exploding gradientsWhy the gradient that reaches the early layers of a deep network is a long product of factors that can fade to nothing or blow up, how to see it layer by layer, and how activations, initialization, normalization, skip connections, gating and gradient clipping deal with it. A widget shows the gradient length at every layer of a deep stack.P4.17Regularization for neural netsA big network can memorize its training set, noise and all. See how weight decay, dropout, early stopping and label smoothing hold it back, watch dropout draw a new random mask at every step, and learn why dropout does nothing at test time.P4.18Data augmentationMake new training examples from the ones you have, by changes that should not change the label. See flips, crops, rotations, colour changes, noise, cutout and mixup on real digits, which changes break the label, why the transformations are a statement about what the model should ignore, and what a small experiment shows.P4.19Normalization layersLayers that standardize the numbers inside a network. The one recipe (subtract a mean, divide by a spread, then a learned scale and shift) and the only thing that changes between BatchNorm, LayerNorm, GroupNorm, InstanceNorm and RMSNorm, which is the set of numbers that share one statistic. A tensor-cube widget shows which cells are grouped, and a measured demo shows what normalization does to a deep network.P4.20Residual connectionsWhy adding a layer's input to its output lets very deep networks train. The degradation problem, the residual block, the identity term in the backward pass, and the ways real networks keep the sum of paths under control (zero-initialized last layers, scaled branches, normalization). A widget shows the gradient at every depth with and without skips, then trains both stacks.P4.21Embedding layersHow a network turns a category, such as a word, a token or a user ID, into a vector. An embedding table is a matrix with one row per category, a lookup picks a row (the same as a one-hot vector times the table, but done by indexing), and the rows are learned by backpropagation, with gradient only for the rows that were used. A widget shows the lookup, the gradient step and the similarity of rows.P4.22The training recipe and debuggingA practical routine for training a network and for finding out why it does not train. Check the data, the baseline and the first loss, overfit one small batch, then read the loss curves, with a gallery of eight real runs and what each shape means, and finish with sanity checks and a debugging checklist ordered from cheap to expensive.P4.23Hyperparameter tuningChoose the settings that training does not learn. Compare grid, random and Bayesian search, learn which settings matter most, search the learning rate on a log scale, and see why the best score of many tries is too good to be true.P4.24Modern generalization puzzlesWhy big networks that fit their training data exactly can still do well on new data, and what researchers have measured. Networks can memorize random labels, so size alone does not explain generalization. Test error can fall, rise to a peak where the model can just fit the training points, and fall again (double descent). Gradient descent has a built-in preference among the many exact fits (implicit regularization), and a network can start to generalize long after its training error reached zero (grokking). A widget sweeps the model size on a small made-up task.P5.1Images as tensorsHow a picture becomes numbers a network can read. Pixels, channels, the shapes (H, W, C) and (C, H, W), uint8 versus float values, memory size, per-channel normalization, grayscale and HSV, and why flattening an image for an MLP loses the neighbours. A widget lets you zoom into a picture until every pixel shows its numbers.P5.2The convolution operationHow a small grid of weights, the kernel, slides over an image and takes a dot product at every position to make a feature map. The hand calculation, the output size, the bias, cross-correlation versus true convolution, weight sharing and the parameter count against a dense layer, translation equivariance and where it breaks at the border, and the gradient of the kernel. Three widgets let you edit a kernel, shift an object and pick a kernel entry.P5.3Kernels as feature detectorsWhat a 3 by 3 kernel does depends on its nine numbers. Blur, sharpen, Prewitt, Sobel, gradient magnitude and direction, and the Laplacian, with the rule that explains them (what the weights add up to), separable kernels, noise, and the link to the kernels a CNN learns. A widget applies every kernel to a test scene or your own photo and shows the arithmetic at any pixel.P5.4Padding, stride and dilationThe three settings that decide the size of every feature map in a CNN. Zero padding and why borders need it, "same" padding, padding modes, stride and the rows a strided convolution skips, dilation and the effective kernel, one output-size formula checked against PyTorch, and what each setting does to the parameters and the multiply-adds. A calculator draws the padded input, the kernel's taps and the unread rows.P5.5Multi-channel convolutions and 1×1 convsHow a convolution layer handles colour images and the stacks of feature maps inside a network. A kernel is a block that spans every input channel, the products of all channels are added into one number, and many kernels give many output channels. The weight shape and parameter count, the multiply-add count, the 1 by 1 convolution as a per-pixel linear layer, and grouped and depthwise-separable convolutions. Two widgets let you step a kernel block through a volume and apply a 1 by 1 convolution pixel by pixel.P5.6Pooling and receptive fieldsHow a CNN shrinks its feature maps and how far each neuron can see. Max and average pooling with the window and stride, the output size, no learned weights, the small shift tolerance of max pooling and where it fails, the gradient of each, global average pooling, and strided convolution as the alternative. Then the receptive field, the recursion that grows it through a stack with the jump, why two 3×3 layers beat one 5×5, how stride, pooling and dilation grow it, and the effective receptive field. A widget draws a stack of layers and highlights what a chosen neuron sees.P5.7Build a CNNTraining a small convolutional network on CIFAR-10 in PyTorch, from the data to the confusion matrix. The dataset, per-channel normalization, crop and flip augmentation, a layer-by-layer shape and parameter table, a comparison with an MLP, BatchNorm placement, the training loop, the first-loss and overfit-one-batch checks, reading the curves, and the mistakes the trained network makes. A Colab notebook runs everything; a widget builds the network and shows every shape.P5.8What do CNNs learn?Open up a small trained CNN and look. Its first-layer kernels drawn as pictures, the feature maps of each layer, saliency maps (the gradient of a class score with respect to the pixels), Grad-CAM with a hand calculation, and occlusion sensitivity. Then the limits of these explanations, including a randomised-weights sanity check. A widget lets you explore every layer and every heat map of a network trained by code.P5.9The CNN architecture tourNine convolutional network designs in order, from LeNet in 1998 to ConvNeXt in 2022. For each one, the problem it addressed, the one idea it added, its block drawn with tensor shapes, its paper and its parameter count. Then global average pooling, the trends, and how to choose a backbone. A widget shows the nine blocks and compares their sizes.P5.10Transfer learning and fine-tuningHow to start from a network trained on a large dataset instead of random weights. Why early layers transfer and later ones are task-specific, the three options (feature extraction, fine-tuning, training from scratch) and a rule of thumb for choosing by dataset size and similarity, replacing the classifier head and its shapes, using the preprocessing that goes with the weights, BatchNorm in train and eval mode, learning rates and discriminative learning rates, augmentation, overfitting and forgetting on a small dataset, and licences and inherited bias. A widget freezes blocks of a ResNet-18 and shows the trainable parameters and the cost, and a chart shows a real CPU experiment with three seeds.P5.11Object detection basicsWhat an object detector outputs and how it is built and scored. A detection is a box, a class and a score. The box formats and how to convert them, intersection over union (IoU) with its edge cases and why 0.5 is a common threshold, box regression targets measured from an anchor with a log scale for width and height, anchors and how they are labelled positive or negative by IoU, confidence scores, non-maximum suppression (NMS) with its per-class form and its failure on crowds, and the evaluation with precision, recall, average precision, mAP and the PASCAL VOC and COCO conventions. Two widgets let you drag boxes to see the IoU and step through NMS on a drawn scene.P5.12Detection architecturesHow the parts of P5.11 are put into networks. The R-CNN family (R-CNN, Fast R-CNN, Faster R-CNN), the one-stage detectors YOLO and SSD, feature pyramids, anchor-free detectors, the class imbalance problem and the focal loss of RetinaNet, and DETR with its set prediction and Hungarian matching. A widget steps through six pipelines on one scene.P5.13Semantic and instance segmentationGiving every pixel a label. Semantic, instance and panoptic segmentation, the per-pixel output and its loss, transposed convolution (scattering, the output-size formula with output padding, checkerboard artifacts) and bilinear upsampling, FCN, U-Net and its skip connections, dilated convolutions and DeepLab, Mask R-CNN and RoIAlign, the Dice loss, and the metrics (pixel accuracy, IoU, mean IoU) with an example of why pixel accuracy misleads. A diagram steps through a U-Net with switchable skips, and a second widget draws a transposed convolution.P5.14Foundation models for visionModels trained once on very large, broad data and steered by prompts. Segment Anything (SAM), with its image encoder, prompt encoder and mask decoder, three masks for an ambiguous click and the SA-1B data engine; and open-vocabulary detection with OWL-ViT and Grounding DINO, where text replaces the fixed class list. A widget imitates SAM's click-to-segment interface on a drawn scene, and real runs of the three models are shown.P5.15Vision TransformersHow a Transformer reads an image. Cut the picture into patches, turn each patch into a token, add a class token and position embeddings, and run a standard encoder. The sizes of ViT-B/16, the cost of attention as the number of patches grows, what the ViT, DeiT, Swin and ConvNeXt papers found about data and design, and Swin's windows. A widget cuts a picture into patches.P5.16Self-supervised visionHow to learn image features from unlabelled pictures. Two augmented views of one image are a positive pair, and the NT-Xent (InfoNCE) loss pulls them together and pushes other images apart, with a worked example at two temperatures and what the temperature does. SimCLR (augmentations, projection head, batch size), MoCo (a queue of negatives and a momentum encoder), why a loss with only positives collapses, DINO (a self-distilling teacher, centring and sharpening, multi-crop, attention maps) and MAE (mask 75% of the patches and reconstruct pixels), each with the conditions of its published numbers. A widget trains a tiny contrastive encoder with and without negatives, and a second widget masks patches.P5.17Adversarial examples and robustnessA small, targeted change to every pixel, far too small to matter to a person, can make a trained network change its answer. What an adversarial example is (an L-infinity budget epsilon), why a network that is almost linear in its many inputs is easy to push, the fast gradient sign method (FGSM) with hand numbers, stronger iterative attacks (PGD), white-box and black-box settings and transfer, defences and why many failed, and robustness to ordinary corruptions. A widget attacks a digit network in your browser.
The course
From basic math all the way to how modern LLMs are trained, aligned and served. New lessons are added regularly.
- 0Start Here
- 1Math Foundations
- 2Programming Toolkit
- 3Classical Machine Learning
- 4Neural Network Foundations
- 5Computer Vision and CNNs
- 6Sequences and Language Foundations
- 7Transformers
- 8Generative Models
- 9Reinforcement Learning Essentials
- 10Large Language Models
- 11Electives and Advanced Topics
- 12Practical ML Engineering
Pick a path
Nobody has to take every lesson. Each path lists its route on the curriculum page.