BS Artificial Intelligence, BSCS and MS machine learning students can use this guide to study Probabilistic Machine Learning: An Introduction by Kevin P. Murphy. It is the 2022 MIT Press textbook that many universities use for Machine Learning and Deep Learning courses, and the author keeps a free online PDF (dated 18 April 2025) on his official book page under a Creative Commons licence. It is the first of two volumes; the sequel, Advanced Topics, is a separate book.
The book treats machine learning as probabilistic modelling combined with decision theory. It begins with probability, statistics, decision theory, information theory, linear algebra and optimization, then moves through linear models, deep neural networks (MLPs, CNNs, RNNs and transformers) and nonparametric methods such as nearest neighbors, kernels, trees and boosting. The last part looks beyond supervised learning: transfer and semi-supervised learning, PCA and autoencoders, clustering, recommender systems and graph embeddings. It is a mathematical book, so expect to use calculus, linear algebra and probability throughout.
Book Overview
| Course | Machine Learning |
| Degree Programs | BS Artificial Intelligence, BSCS, MS (machine learning) |
| Level | Advanced undergraduate / graduate (mathematical) |
| Edition | MIT Press, March 2022 (second printing April 2023, third printing January 2025); free online version dated 18 April 2025 on the author’s page |
| Author | Kevin P. Murphy |
| Publisher | MIT Press |
| Language | English |
| Total Chapters | 23 chapters in five parts, plus Appendix A (Notation) |
| Length | About 860 pages in the online PDF, including the preface, index and bibliography |
| Exercises | Exercises at the end of 14 chapters (2 to 11, 13, 17, 19 and 20); solutions to the exercises without a dagger mark are posted online |
| Code | Python notebooks for most figures (NumPy, scikit-learn, JAX, PyTorch, TensorFlow, PyMC) |
| License | CC BY-NC-ND (as stated on the author’s book page) |
| Format | Free online PDF from the author’s page; print edition from MIT Press |
Chapter List
Chapter 1: Introduction
Difficulty: Easy · Key topics: supervised learning, Iris data, empirical risk, uncertainty and softmax, maximum likelihood, overfitting, no free lunch theorem, unsupervised learning, reinforcement learning, datasets, missing data
Chapter 1 defines learning as improving at a task with experience, and explains why the book treats every unknown quantity as a random variable. Supervised learning is taught through the Iris data: 150 flowers, four measurements, a small decision tree, the misclassification rate and empirical risk with unequal costs. The chapter then adds uncertainty with softmax outputs, fits models by maximum likelihood, and moves to regression with least squares, polynomial features and deep networks. Overfitting, the generalization gap and the no free lunch theorem follow, then unsupervised and reinforcement learning, common datasets and preprocessing, and a closing discussion of ML versus statistics and caveats such as reward hacking.
Key Points:
- Supervised learning learns a mapping from inputs x to outputs y from a training set of N input-output pairs; the Iris design matrix has N = 150 rows and D = 4 columns.
- Empirical risk is the average loss on the training set; with zero-one loss it equals the misclassification rate, and unequal costs can be expressed with a loss matrix.
- Classifiers output a probability distribution over classes; a softmax turns real-valued logits into probabilities that sum to 1.
- The negative log likelihood is the standard loss for probabilistic models, and under Gaussian noise it is proportional to the mean squared error.
- A model that fits the training data perfectly can have a large generalization gap (population risk minus training loss); this is overfitting.
- Self-supervised learning builds a proxy prediction task, such as filling in masked words, from unlabeled data.
- Reinforcement learning receives only an occasional reward signal, not the correct action for each input.
Memory Tip: Supervised learning has a teacher who gives answers, unsupervised learning has no teacher, and reinforcement learning only tells you a score afterwards.
Common Mistake: Judging a model by its accuracy on the data it was trained on. A flexible model can reach zero training loss by memorizing, so always report a score on held-out test data.
Important Questions:
- What is the generalization gap? The difference between the expected loss on new data (population risk) and the loss on the training set. A large gap signals overfitting, and it is estimated by measuring loss on a separate test set.
- What does the no free lunch theorem tell us? No model is best on every problem, because each model carries assumptions (inductive bias) that suit some domains and not others. The choice must come from domain knowledge or model selection such as cross-validation.
Chapter 2: Probability: Univariate Models
Part I: Foundations · Difficulty: Medium · Key topics: random variables, independence, moments, Bayes’ rule, Bernoulli, categorical, Gaussian, Student t, change of variables, central limit theorem, Monte Carlo
Chapter 2 builds the probability toolkit for one variable at a time. It first asks what probability means, separates kinds of uncertainty, and treats probability as an extension of logic. Discrete and continuous random variables, independence and conditional independence, and moments such as the mean and variance follow, with a warning that summary statistics can hide the shape of a distribution. Bayes’ rule is worked through medical testing and the Monty Hall problem. The chapter then studies the Bernoulli, binomial, categorical and Gaussian families, links them to the sigmoid, softmax and regression, covers other common densities, and finishes with transformations of variables, the central limit theorem and Monte Carlo approximation.
Key Points:
- Bayes’ rule: p(H|y) = p(y|H) p(H) / p(y), the posterior is likelihood times prior, normalized.
- The sigmoid
1/(1+exp(-a))maps a real number to a Bernoulli probability and gives binary logistic regression. - The softmax turns a vector of scores into categorical probabilities for multiclass logistic regression.
- The log-sum-exp trick computes log-probabilities without numerical overflow.
- The Student t distribution has heavier tails than the Gaussian and is more robust to outliers.
- The central limit theorem says sums of many independent variables look Gaussian.
- Monte Carlo approximation estimates an expectation by averaging over random samples.
Practice Tip: Simulate the Monty Hall game 100,000 times in a few lines of NumPy. The win rate for switching settles near two thirds, which is more convincing than any argument.
Common Mistake: Confusing p(A|B) with p(B|A). A positive test result is not the same as a high chance of having the disease unless the base rate is also taken into account.
Important Questions:
- State Bayes’ rule and name its terms. The posterior equals the likelihood times the prior divided by the evidence (marginal likelihood), which normalizes the result.
- Why is the log-sum-exp trick used? Exponentiating large scores overflows, so the largest score is subtracted first, which keeps softmax and log-likelihood computations stable.
Chapter 3: Probability: Multivariate Models
Part I: Foundations · Difficulty: Medium · Key topics: covariance, correlation, Simpson’s paradox, multivariate Gaussian, Mahalanobis distance, linear Gaussian systems, exponential family, mixture models, graphical models
Chapter 3 extends probability to many variables. It starts with joint distributions, covariance and correlation, and warns that uncorrelated does not mean independent and correlation does not mean causation, using Simpson’s paradox as the example. The multivariate Gaussian gets a full treatment: its definition, Mahalanobis distance, marginals and conditionals, conditioning a 2d Gaussian and imputing missing values. Linear Gaussian systems show Bayes’ rule for Gaussians through scalar, vector and sensor fusion examples. The chapter then introduces the exponential family, mixture models such as Gaussian mixtures, and a short overview of probabilistic graphical models.
Key Points:
- The correlation coefficient always lies between -1 and +1.
- Uncorrelated variables need not be independent (it does hold for jointly Gaussian variables).
- Simpson’s paradox: a trend in every subgroup can reverse when the groups are combined.
- Marginals and conditionals of a multivariate Gaussian are again Gaussian.
- Mahalanobis distance measures distance in units of the data’s own covariance.
- A mixture model writes the density as a weighted sum of component densities.
- Exponential family members share one form and have a convenient log partition function.
Memory Tip: Mahalanobis distance is ordinary Euclidean distance measured after the data has been stretched so that its covariance becomes the identity.
Common Mistake: Reading a correlation of zero as proof that two variables are unrelated. They can depend on each other in a nonlinear way.
Important Questions:
- Does zero correlation imply independence? No. Independence implies zero correlation, but variables can be uncorrelated and still dependent, except in the special case of jointly Gaussian variables.
- What is Simpson’s paradox? A relationship that appears within every subgroup disappears or reverses in the pooled data because of a confounding grouping variable.
Chapter 4: Statistics
Part I: Foundations · Difficulty: Hard · Key topics: maximum likelihood, empirical risk, surrogate loss, regularization, MAP, cross-validation, conjugate priors, beta-binomial, Laplace and variational approximation, bootstrap, bias-variance
Chapter 4 explains how models are fitted to data. Maximum likelihood is defined under the iid assumption, justified as the best match to the empirical distribution, and worked out for the Bernoulli, categorical, Gaussian and linear regression models. Empirical risk minimization swaps the log loss for other losses, using convex surrogates such as the hinge loss because the zero-one loss is hard to optimize. Regularization starts from the zero-count problem in coin tossing and leads to MAP estimation, validation sets and K-fold cross-validation. The starred sections cover Bayesian inference, with conjugate priors and four ways to approximate a posterior (grid, Laplace, variational and MCMC), and frequentist statistics with the bootstrap, confidence intervals and the bias-variance tradeoff.
Key Points:
- Under the iid assumption the likelihood factorizes, so the MLE minimizes the average negative log likelihood; for linear regression with Gaussian noise this is least squares.
- The zero-one loss is a non-smooth step function, so classifiers are trained on convex surrogates such as the log loss or the hinge loss.
- MAP estimation adds the negative log prior as a penalty; a beta prior cures the zero-count problem when only a few coin tosses have been seen.
- K-fold cross-validation trains on K-1 folds and tests on the remaining one in turn, which gives a more reliable estimate than a single small validation set.
- In the beta-binomial model the posterior simply adds the observed head and tail counts to the prior pseudo-counts.
- Section 4.6.8 approximates intractable posteriors with a grid, a Gaussian (Laplace) approximation, variational inference or MCMC; the grid does not scale beyond a few dimensions.
- Expected squared error splits into bias squared plus variance, so a slightly biased estimator such as MAP can beat the MLE if it cuts variance enough.
Memory Tip: MLE trusts the data only; MAP lets a prior vote as well. As the amount of data grows, the data outvotes the prior.
Common Mistake: Reading a 95% confidence interval as a 95% chance that the parameter lies inside it. The book has a section called Caution: confidence intervals are not credible.
Important Questions:
- How is MAP estimation related to regularization? The negative log prior is added to the loss as a penalty, so a Gaussian prior gives an L2 penalty (weight decay) and a prior that favors simple values discourages extreme estimates such as a coin probability of exactly 1.
- What is the bias-variance tradeoff? Simple models have high bias and low variance, flexible models the reverse, and the lowest expected error comes from balancing the two; the MAP example in the chapter shows a biased estimator beating the MLE on small samples.
Chapter 5: Decision Theory
Part I: Foundations · Difficulty: Hard · Key topics: loss function, posterior expected loss, ROC curve, precision-recall, Bayesian model selection, Occam’s razor, information criteria, risk, hypothesis testing, p-values
Chapter 5 turns probabilistic predictions into decisions. Bayesian decision theory picks the action with the lowest expected loss, and the chapter applies it to classification (with ROC and precision-recall curves), regression and probabilistic prediction. Bayesian hypothesis testing and model selection follow, including the Occam’s razor effect of the marginal likelihood, its link to cross-validation and information criteria. Frequentist decision theory evaluates estimators by risk, consistency and admissibility, and empirical and structural risk lead to a short look at statistical learning theory. The last section covers likelihood ratio tests, p-values and the case against over-relying on them.
Key Points:
- The optimal action minimizes the posterior expected loss.
- Under 0-1 loss the best prediction is the most probable class; under squared error it is the posterior mean; under absolute error it is the posterior median.
- An ROC curve plots true positive rate against false positive rate as the threshold varies.
- Precision-recall curves are more informative than ROC curves when positives are rare.
- The marginal likelihood automatically penalizes needlessly complex models (Occam’s razor).
- A p-value is the probability of data at least this extreme if the null hypothesis were true.
Memory Tip: Match the loss to the summary: squared error to the mean, absolute error to the median, 0-1 loss to the mode.
Common Mistake: Treating a p-value as the probability that the null hypothesis is true. It is a statement about the data, not about the hypothesis.
Important Questions:
- What is the optimal decision rule in Bayesian decision theory? Choose the action that minimizes the expected loss under the posterior distribution over the unknown state.
- When is a precision-recall curve preferred over an ROC curve? When the classes are highly imbalanced, because precision reacts to false positives relative to the few true positives while the false positive rate barely moves.
Chapter 6: Information Theory
Part I: Foundations · Difficulty: Medium · Key topics: entropy, cross entropy, perplexity, KL divergence, mutual information, data processing inequality, sufficient statistics
Chapter 6 introduces the quantities used to measure information and compare distributions. Entropy of discrete variables is defined first, followed by cross entropy, joint and conditional entropy, perplexity and differential entropy for continuous variables. Relative entropy (KL divergence) gets a full section covering its interpretation, a Gaussian example, non-negativity, its link to maximum likelihood and the difference between forward and reverse KL. Mutual information is then defined and developed as a generalized correlation measure, with normalized and maximal information coefficients, the data processing inequality, sufficient statistics and Fano’s inequality.
Key Points:
- Entropy H(p) = -sum p(x) log p(x) measures uncertainty and is largest for the uniform distribution.
- Cross entropy is the average code length when data from p is encoded with a model q.
- KL(p||q) = cross entropy minus entropy, is never negative and is not symmetric.
- Minimizing KL from the empirical distribution to a model is the same as maximum likelihood.
- Mutual information is zero exactly when two variables are independent.
- Processing data cannot increase the information it holds about the source (data processing inequality).
Memory Tip: KL divergence is the extra cost, in nats or bits, of describing data from p with a code built for q.
Common Mistake: Treating KL divergence as a distance. It is not symmetric, so KL(p||q) and KL(q||p) behave differently.
Important Questions:
- How are cross entropy, entropy and KL divergence related? Cross entropy H(p,q) equals H(p) plus KL(p||q), so for a fixed p, minimizing cross entropy minimizes KL.
- What does mutual information measure? The reduction in uncertainty about one variable from knowing the other; it equals the KL divergence between the joint distribution and the product of the marginals.
Chapter 7: Linear Algebra
Part I: Foundations · Difficulty: Medium · Key topics: vector spaces, norms, matrix multiplication, matrix inverse, eigenvalue decomposition, SVD, pseudo inverse, least squares, Jacobian, Hessian
Chapter 7 is the linear algebra reference that the rest of the book leans on. It sets up notation, vector spaces, norms and the properties and special types of matrices, then treats matrix multiplication from vector products up to manipulating data matrices, with Kronecker products and Einstein summation as extras. Matrix inversion covers the inverse, Schur complements and the matrix inversion and determinant lemmas, applied to the conditionals of a multivariate Gaussian. Eigenvalue and singular value decompositions are developed with whitening, the power method and the pseudo inverse, followed by LU, QR and Cholesky factorizations, linear systems and matrix calculus with gradients, Jacobians and Hessians.
Key Points:
- An eigenvector of A satisfies Av = λv; symmetric matrices have real eigenvalues and orthogonal eigenvectors.
- Every matrix has an SVD, X = U S V transposed, with non-negative singular values.
- The truncated SVD gives the best low-rank approximation of a matrix.
- The pseudo inverse solves least squares and least norm problems.
- Cholesky factorization is the standard tool for positive definite matrices such as covariances.
- The gradient collects first derivatives, the Jacobian is the matrix of derivatives of a vector function, and the Hessian holds second derivatives.
Practice Tip: Run np.linalg.svd and np.linalg.eigh on a small covariance matrix and confirm that the squared singular values match the eigenvalues.
Common Mistake: Computing an explicit inverse to solve Ax = b. Use a solver such as np.linalg.solve, which is faster and numerically safer.
Important Questions:
- How are the SVD and the eigenvalue decomposition related? The squared singular values of X are the eigenvalues of X transposed times X, and the right singular vectors are its eigenvectors.
- What is the Hessian and why does it matter? It is the matrix of second derivatives of a scalar function; its definiteness tells you about curvature and is used by Newton-type optimizers.
Chapter 8: Optimization
Part I: Foundations · Difficulty: Hard · Key topics: convexity, gradient descent, momentum, Newton’s method, stochastic gradient descent, Lagrange multipliers, KKT conditions, proximal methods, EM algorithm
Chapter 8 surveys the optimization methods used to fit models. It begins by sorting problems into local or global, constrained or unconstrained, convex or nonconvex and smooth or nonsmooth. First-order methods follow, covering descent directions, step size, convergence rates and momentum, then second-order methods such as Newton’s method, BFGS and trust regions. Stochastic gradient descent gets its own section, including step size choices, iterate averaging and preconditioning. The chapter also covers constrained optimization (Lagrange multipliers, KKT, linear and quadratic programming), proximal gradient methods, bound optimization with the EM algorithm for Gaussian mixtures, and derivative-free search.
Key Points:
- For a convex problem every local minimum is a global minimum.
- Gradient descent updates parameters by subtracting the step size times the gradient.
- A step size that is too large diverges; one that is too small crawls.
- Newton’s method uses the Hessian and converges faster near a solution but costs more per step.
- SGD estimates the gradient from a minibatch, which makes training on large datasets feasible.
- KKT conditions characterize optima of constrained problems.
- EM alternates an E step and an M step and never decreases the likelihood.
Practice Tip: Run gradient descent on a simple two-variable quadratic with three different learning rates and plot the path. You will see slow, good and divergent behaviour side by side.
Common Mistake: Assuming gradient descent always finds the global minimum. That is guaranteed only for convex objectives; neural networks are nonconvex.
Important Questions:
- Why is stochastic gradient descent used in machine learning? Each update uses a small random batch, so the cost per step does not grow with the dataset size and noisy steps often still reach a good solution.
- How does the EM algorithm work? It repeatedly computes the expected hidden-variable assignments under the current parameters (E step) and then re-estimates the parameters to maximize a lower bound on the likelihood (M step).
Chapter 9: Linear Discriminant Analysis
Part II: Linear Models · Difficulty: Medium · Key topics: Gaussian discriminant analysis, QDA, LDA, nearest centroid, Fisher’s discriminant, naive Bayes, generative vs discriminative
Chapter 9 introduces generative classifiers that model each class and then apply Bayes’ rule. Gaussian discriminant analysis is presented first, showing how quadratic decision boundaries arise from class-specific covariances and linear boundaries from a shared covariance, with the connection between LDA and logistic regression, model fitting, the nearest centroid classifier and Fisher’s linear discriminant. Naive Bayes classifiers follow, with example models, fitting, a Bayesian version and their link to logistic regression. The chapter closes by weighing generative against discriminative classifiers, including what each is good at and how to handle missing features.
Key Points:
- Generative classifiers model p(x|y) and p(y), then compute p(y|x) with Bayes’ rule.
- Class-specific covariances give a quadratic decision boundary (QDA); a shared covariance gives a linear one (LDA).
- The posterior of LDA has the same form as softmax regression, so the two are closely connected.
- Naive Bayes assumes features are independent given the class, which keeps the number of parameters small.
- Discriminative classifiers model p(y|x) directly and are usually more accurate with plenty of data.
- Generative models cope naturally with missing features.
Memory Tip: Generative means it could generate data (it models x); discriminative only draws the line between classes.
Common Mistake: Dismissing naive Bayes because its independence assumption is false. It can still classify well, because it only needs the right class to score highest.
Important Questions:
- What is the difference between generative and discriminative classifiers? A generative classifier models the joint distribution of inputs and labels, whereas a discriminative classifier models the conditional p(y|x) directly.
- When does QDA reduce to LDA? When all classes share the same covariance matrix, the quadratic terms cancel and the decision boundary becomes linear.
Chapter 10: Logistic Regression
Part II: Linear Models · Difficulty: Medium · Key topics: binary and multinomial logistic regression, MLE, perceptron, IRLS, MAP, softmax, maximum entropy, robust loss, Laplace approximation
Chapter 10 develops logistic regression, the workhorse discriminative classifier. For binary problems it explains linear and nonlinear classifiers, maximum likelihood estimation, stochastic gradient descent, the perceptron, iteratively reweighted least squares, MAP estimation and standardization. The multinomial case follows with its own likelihood, gradient-based and bound optimization, MAP estimation, maximum entropy classifiers and ways to handle hierarchical classes and very large numbers of classes. The starred sections add robust logistic regression, with a mixture likelihood and a bi-tempered loss, and Bayesian logistic regression through the Laplace approximation.
Key Points:
- The model is p(y=1|x) = sigmoid(w transposed x + b), a linear decision boundary.
- The negative log likelihood is the cross entropy loss and is convex, but has no closed-form minimizer.
- The gradient has the simple form of features times (predicted probability minus label).
- IRLS is Newton’s method specialized to logistic regression.
- An L2 penalty (a Gaussian prior) keeps weights finite and controls overfitting.
- Multiclass logistic regression uses the softmax; it is also called a maximum entropy classifier.
Practice Tip: Fit scikit-learn’s LogisticRegression on a small dataset for several values of C and watch the weights shrink as regularization gets stronger.
Common Mistake: Forgetting regularization on linearly separable data. The likelihood keeps improving as the weights grow, so unregularized weights diverge.
Important Questions:
- Why is logistic regression a linear classifier? The decision boundary where the probability equals 0.5 is the set of points with w transposed x + b = 0, which is a hyperplane.
- How is the model trained? By minimizing the negative log likelihood with gradient-based or second-order methods such as SGD or IRLS, usually with a regularization term.
Chapter 11: Linear Regression
Part II: Linear Models · Difficulty: Medium · Key topics: least squares, normal equations, ridge, lasso, sparsity, elastic net, splines, robust regression, Bayesian linear regression
Chapter 11 covers the most basic regression model and its many variations. Least squares comes first, with terminology, estimation, alternative ways to compute the MLE and goodness of fit. Ridge regression adds an L2 penalty and is linked to PCA, and lasso regression adds an L1 penalty, with sections on why it produces sparse solutions, soft thresholding, regularization paths, group lasso and elastic net. The starred sections cover regression splines and generalized additive models, robust regression (Laplace and Student likelihoods, Huber loss, RANSAC) and Bayesian linear regression with priors, posteriors, centering, multicollinearity and automatic relevance determination.
Key Points:
- Least squares minimizes the residual sum of squares and has the closed-form normal equations solution.
- Ridge regression shrinks all weights toward zero and remains solvable when features are correlated.
- Lasso uses an L1 penalty, which sets many weights exactly to zero and so selects features.
- Elastic net combines the ridge and lasso penalties.
- The Huber loss is quadratic for small errors and linear for large ones, which reduces the effect of outliers.
- Bayesian linear regression returns a distribution over weights and predictions with uncertainty.
Practice Tip: Fit lasso for a range of regularization strengths on a dataset with many features and plot the weights against the strength. The regularization path shows features entering one by one.
Common Mistake: Applying ridge or lasso to features measured on very different scales. Standardize the inputs first, or the penalty treats features unfairly.
Important Questions:
- Why does L1 regularization give sparse solutions while L2 does not? The L1 constraint region has corners on the axes, so the optimum often lands where some weights are exactly zero; the L2 ball is smooth and only shrinks weights.
- What is the ridge regression solution? Solve (X transposed X + λI) w = X transposed y; the added λI makes the matrix invertible and shrinks the weights.
Chapter 12: Generalized Linear Models *
Part II: Linear Models · Difficulty: Medium · Key topics: exponential family response, natural parameter, link and mean function, binomial regression, Poisson regression, canonical link, probit, convex log likelihood, deviance, insurance claims
Chapter 12 is a short starred chapter of about eight pages. It starts from the fact that logistic and linear regression both make the mean of the output depend on a linear score, and defines a generalized linear model as a conditional exponential family distribution whose natural parameter is the linear score. The link function and its inverse, the mean function, connect that score to the mean, and the mean and variance follow from the log normalizer. Linear, binomial and Poisson regression are derived as special cases, non-canonical links such as probit and complementary log-log are described, and the gradient and Hessian show that the negative log likelihood is convex. A worked example predicts car insurance claims.
Key Points:
- A GLM is a conditional exponential family distribution whose natural parameter is the linear score
w·x; the mean is the inverse link (mean function) applied to that score. - The mean and variance of the response come from the log normalizer A: the mean is its first derivative and the variance is its second derivative times the dispersion.
- Linear regression has the identity link, and binomial regression uses the logit link with variance
N·mu·(1 - mu); binary logistic regression is the special case N = 1. - Poisson regression models integer counts with a log link, so the mean exp(w·x) is always positive and equals the variance.
- The canonical link satisfies theta = eta (the logit for the Bernoulli); other links such as probit and complementary log-log are allowed.
- For every GLM the gradient has the form (y – mean) times x, and the Hessian is positive definite, so the negative log likelihood is convex and the MLE is unique.
- Deviance, not MSE or MAE, is the preferred yardstick for Poisson models, and a calibration plot checks that predicted rates match observed rates.
Practice Tip: Fit scikit-learn’s PoissonRegressor and Ridge on any count dataset, then compare MSE, Poisson deviance and a calibration plot. The plot shows what the single error number hides.
Common Mistake: Judging a count model by MSE or MAE alone. In the book’s insurance example ridge regression looks as good as or better than Poisson regression on both, yet it can predict negative rates and misses the long tail.
Important Questions:
- What makes a model a generalized linear model? The response comes from an exponential family distribution, and its mean is the inverse link function applied to a linear predictor w·x. Linear, logistic and Poisson regression are all examples.
- Why does the insurance example prefer Poisson regression although ridge scores well on MSE and MAE? About 94% of policies have no claim, so the data are skewed counts. Deviance and calibration expose the difference: the Poisson model predicts 11,930 total claims against 11,935 observed, while ridge predicts only 10,693.
Chapter 13: Neural Networks for Tabular Data
Part III: Deep Neural Networks · Difficulty: Hard · Key topics: multilayer perceptron, XOR problem, activation functions, universal approximation, backpropagation, reverse mode differentiation, vanishing gradients, ReLU variants, residual connections, initialization, dropout, mixtures of experts
Chapter 13 explains why linear models need hand-made features and how stacking learnable layers removes that need. It shows the XOR problem that defeated perceptrons, then differentiable MLPs and activation functions, with worked examples: two concentric circles, MNIST digits (two hidden layers of 128 units, 97.1% test accuracy after two epochs), IMDB reviews (86% validation accuracy) and heteroskedastic regression. A short history of the deep learning revolution and a comparison with biological neurons follow. Backpropagation is derived with reverse mode differentiation and vector-Jacobian products, the training section covers vanishing gradients, ReLU variants, residual connections and initialization, and regularization covers early stopping, dropout and Bayesian neural networks.
Key Points:
- A perceptron has a linear decision boundary and cannot compute XOR; an MLP with hidden AND and OR units can.
- If every activation is linear, a deep stack collapses into one linear map, so nonlinear activations are essential.
- One hidden layer is a universal function approximator, but deep networks learn compositional features more efficiently.
- Reverse mode differentiation (backpropagation) gives the gradient of a scalar loss for all parameters in one backward pass, using a vector-Jacobian product for each layer.
- Sigmoid and tanh saturate and cause vanishing gradients; ReLU helps but can leave units permanently off, which leaky ReLU, ELU, GELU and swish avoid.
- Gradient clipping tames exploding gradients, residual connections give gradients a direct path, and Glorot or He initialization keeps activation variance stable.
- Dropout, weight decay and early stopping regularize networks, and the loss is non-convex, so SGD finds a good solution but not a guaranteed global optimum.
Practice Tip: Write a one-hidden-layer MLP in NumPy with hand-coded backpropagation, then compare its gradients with a finite-difference estimate. If they agree, your backward pass is right.
Common Mistake: Stacking layers and forgetting the activation function between them. Depth adds no power until a nonlinearity is placed in between.
Important Questions:
- Why is reverse mode differentiation used for training networks? The loss is a single scalar and the parameters are numerous, so one backward pass gives all the gradients at a cost comparable to one forward pass.
- What causes vanishing gradients and how are they reduced? Repeatedly multiplying small derivatives (for example from saturating sigmoids) shrinks the signal; non-saturating activations such as ReLU, residual connections and careful initialization help.
Chapter 14: Neural Networks for Images
Part III: Deep Neural Networks · Difficulty: Hard · Key topics: convolution, pooling, normalization layers, LeNet, AlexNet, Inception, ResNet, DenseNet, dilated and transposed convolution, object detection, segmentation, style transfer
Chapter 14 shows how convolutional neural networks handle images. It explains the common layers (convolution, pooling and normalization) and how they are combined. Classic image classification architectures are reviewed in order: LeNet, AlexNet, GoogLeNet (Inception), ResNet and DenseNet, plus neural architecture search. Starred sections cover other forms of convolution (dilated, transposed and depthwise separable), other vision tasks such as object detection, instance and semantic segmentation and human pose estimation, and ways of generating images by inverting a trained CNN, including Deep Dream and neural style transfer.
Key Points:
- Convolution shares weights across positions and connects each unit only to a local patch, so it needs far fewer parameters than a dense layer.
- Convolution is translation equivariant; pooling adds some local invariance and reduces resolution.
- Normalization layers stabilize and speed up training.
- ResNet adds skip connections so that each block learns a residual on top of its input.
- Inception modules apply several filter sizes in parallel.
- Transposed convolution upsamples feature maps; depthwise separable convolution cuts computation.
- Segmentation labels every pixel, while detection places boxes around objects.
Practice Tip: Count the parameters of a 3×3 convolution with 64 filters on a 32×32 image and compare with a dense layer mapping the same image to the same output size. The gap shows why convolutions scale.
Common Mistake: Saying that convolutional layers are translation invariant. The feature maps shift with the input (equivariance); invariance comes later from pooling and the classifier.
Important Questions:
- Why do CNNs work well on images? Local connectivity and weight sharing build in the assumption that useful patterns are local and can appear anywhere, which cuts parameters and improves generalization.
- What problem do residual connections solve? They make very deep networks trainable by giving gradients a short path back through the identity connection.
Chapter 15: Neural Networks for Sequences
Part III: Deep Neural Networks · Difficulty: Hard · Key topics: RNN, LSTM and gating, seq2seq, teacher forcing, backpropagation through time, beam search, attention, transformer, positional encoding, BERT, GPT, T5
Chapter 15 covers models for text and other sequences. Recurrent neural networks are presented in their vec2seq, seq2vec and seq2seq forms, with teacher forcing, backpropagation through time, vanishing and exploding gradients, gating for long-term memory and beam search. One-dimensional CNNs offer an alternative for classification and causal generation. Attention is introduced as a soft dictionary lookup, related to kernel regression, and used in seq2seq models and text classification. Transformers follow, with self-attention, multi-head attention, positional encoding and a comparison with CNNs and RNNs, then efficient transformers, and a closing section on language models and pretraining: ELMo, BERT, GPT and T5.
Key Points:
- An RNN reuses the same weights at every time step and carries a hidden state forward.
- Teacher forcing trains a sequence generator by feeding it the true previous token.
- LSTM and GRU gates let the network keep or discard information over long spans.
- Beam search keeps several best partial sequences instead of choosing greedily.
- Attention computes a weighted average of values, with weights from query-key similarity.
- Self-attention ignores word order, so transformers add positional encodings.
- BERT is an encoder-style model, GPT a decoder-style generative model, and T5 an encoder-decoder.
Memory Tip: Attention is a soft database lookup: a query is compared with keys and the answer is a blend of the matching values.
Common Mistake: Assuming a transformer knows word order automatically. Without positional information, self-attention treats the input as an unordered set.
Important Questions:
- Why did transformers largely replace RNNs for language tasks? Self-attention processes all positions in parallel and links distant tokens directly, avoiding the long-range gradient problems and the sequential bottleneck of RNNs.
- What is multi-head attention? Several attention operations run in parallel on different learned projections, so the model can attend to different kinds of relationships at once.
Chapter 16: Exemplar-based Methods
Part IV: Nonparametric Models · Difficulty: Easy · Key topics: K nearest neighbors, curse of dimensionality, distance metric learning, ranking loss, kernel density estimation, Parzen window, kernel regression
Chapter 16 opens Part IV with models that keep the training examples instead of fitting a fixed set of parameters. It introduces K nearest neighbor classification with an example, the curse of dimensionality, ways to reduce speed and memory costs and open set recognition. It then covers learning distance metrics, from linear and convex methods to deep metric learning with classification and ranking losses and training tricks. The final section presents kernel density estimation with density kernels, the Parzen window estimator, bandwidth selection, the step from KDE to KNN classification, and kernel regression.
Key Points:
- KNN predicts by majority vote (or averaging) over the K closest training points.
- Small K gives a jagged, high-variance boundary; large K gives a smooth, high-bias one.
- In high dimensions distances become less informative (curse of dimensionality).
- Distance metric learning learns an embedding where similar items lie close together.
- A kernel density estimate averages a small kernel bump placed on every data point.
- The bandwidth controls smoothness: too small overfits, too large over-smooths.
Practice Tip: Fit KNN with scikit-learn on a dataset with and without feature scaling and compare accuracy. The difference shows how much the distance function matters.
Common Mistake: Using KNN on features with very different scales. The feature with the largest range dominates the distance.
Important Questions:
- What is the curse of dimensionality for KNN? As the number of dimensions grows, data becomes sparse and nearest neighbors are almost as far away as any other points, so neighbourhood information loses meaning.
- What does the bandwidth do in kernel density estimation? It sets the width of each kernel and therefore the smoothness of the estimated density.
Chapter 17: Kernel Methods *
Part IV: Nonparametric Models · Difficulty: Hard · Key topics: Mercer kernels, RBF and Matern kernels, ARD, kernel composition, Gaussian processes, marginal likelihood, support vector machines, soft margin, kernel trick, relevance vector machine
Chapter 17 is a starred chapter about predicting from the similarity between a new input and the training points instead of from a fixed set of weights. A Mercer kernel is a symmetric function whose Gram matrix is positive definite; the chapter covers the squared exponential and Matern kernels, the ARD kernel with one length scale per input, new kernels built by adding or multiplying old ones, and kernels for strings and graphs. Gaussian processes use a kernel as a prior over functions, with noise-free and noisy prediction, kernel hyperparameters chosen by empirical Bayes, classification, and sparse or random-feature methods for big data. Support vector machines maximize the margin through the dual problem, soft margins and the kernel trick, and the RVM closes the chapter.
Key Points:
- A Mercer kernel gives a positive definite Gram matrix for any set of points; the RBF kernel’s length scale sets the distance over which differences matter.
- The ARD kernel gives each input its own length scale, so an irrelevant input can be ignored by letting its length scale grow without limit.
- Sums and products of valid kernels are valid kernels, which is how the polynomial and Gaussian kernels are derived from the linear one.
- A Gaussian process says function values at any set of inputs are jointly Gaussian, with covariance given by the kernel; exact GP regression costs
O(N^3)because of the Cholesky step, so inducing-point approximations are used for large data. - GP hyperparameters (length scale, signal and noise level) are set by maximizing the marginal likelihood, which can have several local optima.
- An SVM maximizes the margin; the soft-margin version adds slack variables controlled by C, and only the support vectors (dual weight above zero) affect predictions.
- SVM outputs are not calibrated probabilities (Platt scaling fits a sigmoid to them), and multiclass SVMs use one-versus-rest or one-versus-one schemes.
Memory Tip: A kernel answers one question: how similar are these two inputs? Everything else in the method is built from that answer.
Common Mistake: Expecting SVM scores to be probabilities. Raw SVM outputs are signed distances from the boundary and need calibration, which the chapter explains.
Important Questions:
- What is the kernel trick? An algorithm that touches the data only through inner products can swap them for a kernel function, which gives nonlinear models at the cost of one similarity evaluation per pair of points.
- What are support vectors? The training points with non-zero dual weight: those on the margin and, in the soft-margin case, those inside the margin or on the wrong side. They alone determine the SVM solution.
Chapter 18: Trees, Forests, Bagging, and Boosting
Part IV: Nonparametric Models · Difficulty: Medium · Key topics: CART, Gini index, pruning, surrogate splits, stacking, bagging, out-of-bag error, random forests, AdaBoost, gradient boosting, XGBoost, feature importance, partial dependence
Chapter 18 builds from one tree to ensembles. A CART model splits the input space with axis-parallel thresholds and stores a simple prediction in each leaf. Finding the best tree is NP-complete, so trees are grown greedily using a node cost such as squared error, the Gini index or entropy, then limited or pruned, with surrogate splits for missing inputs. Trees are unstable, so averaging helps: stacking learns combination weights, bagging averages models trained on bootstrap samples, and random forests also choose random features at each split. Boosting adds weak learners in sequence, from least squares boosting and AdaBoost to LogitBoost, gradient boosting and XGBoost, and an email spam example shows feature importance and partial dependence plots.
Key Points:
- Trees are grown greedily by choosing the feature and threshold that most reduce the node cost; squared error is used for regression and the Gini index, entropy or error rate for classification.
- Trees ignore monotone transformations of the inputs but are unstable: removing a single training point can change the tree dramatically.
- A deep tree overfits, so growth is stopped early or the full tree is pruned back; greedy top-down growth would never split on XOR data.
- Averaging an ensemble keeps the bias of the base models but lowers variance; stacking learns the weights on separate data, and an ensemble is not Bayes model averaging.
- Bagging trains on bootstrap samples; each sample leaves out about 37% of the data, and these out-of-bag points give a free estimate of performance.
- Random forests also pick a random subset of features at every split, which decorrelates the trees and beat plain bagging on the spam data.
- Boosting cuts bias by fitting each new weak learner to what the ensemble still gets wrong: residuals for least squares boosting, reweighted examples for AdaBoost, the negative gradient for gradient boosting.
Memory Tip: Bagging builds trees in parallel to cut variance; boosting builds them in sequence to cut bias.
Common Mistake: Trusting the feature importance of a forest as a causal statement. It reports how much the model used a feature, not what would happen if you changed it.
Important Questions:
- How does a random forest differ from bagging? Both average trees fitted on bootstrap samples, but a random forest also restricts each split to a random subset of features, so the trees are less correlated and the average has lower variance.
- How does boosting work? It builds a model in stages, where each new weak learner is fitted to the errors (or the negative gradient of the loss) of the current ensemble and added with a small weight.
Chapter 19: Learning with Fewer Labeled Examples
Part V: Beyond Supervised Learning · Difficulty: Medium · Key topics: data augmentation, fine-tuning, adapters, self-supervised pre-training, SimCLR, domain adaptation, pseudo-labeling, consistency regularization, active learning, MAML, few-shot learning
Chapter 19 starts from the problem that large models overfit small labeled sets (a 50-layer ResNet has about 23 million parameters). Data augmentation is justified as minimizing risk in the neighborhood of each training point. Transfer learning pre-trains on a large source dataset such as ImageNet (1.28 million images, 1,000 classes) and fine-tunes with a new output head or small adapter modules; self-supervised pre-training uses imputation, proxy and contrastive tasks, with SimCLR as the main example. Semi-supervised learning uses unlabeled data through self-training, entropy minimization, co-training, label propagation and consistency regularization. The chapter closes with active learning, meta-learning with MAML, few-shot learning and weakly supervised learning.
Key Points:
- Augmentation creates label-preserving variants (random crops, flips, added noise); it can be seen as vicinal risk minimization, which measures risk around each training point.
- Fine-tuning chops off the final layer of a pretrained network, adds a new head for the new labels and trains with a small learning rate; with the features frozen the problem is convex.
- Adapters insert small bottleneck modules, initialized to the identity, into a frozen pretrained network, so each new task trains only a few parameters.
- Self-supervised pre-training uses imputation (fill in the blank), proxy tasks (predict a rotation) or contrastive tasks, where SimCLR pulls two augmented views of an image together and pushes other examples apart.
- Domain adaptation can train features so that source and target inputs cannot be told apart, using a gradient sign reversal trick related to GANs.
- Self-training keeps only confident pseudo-labels, and entropy minimization pushes decision boundaries into low-density regions (the cluster assumption).
- Consistency regularization asks for the same prediction on perturbed copies of an input, with the weight on the unlabeled loss increased gradually from zero.
Memory Tip: Ask which resource you lack: labels (semi-supervised), labeling budget (active learning), or training data for a new task (transfer and few-shot).
Common Mistake: Augmenting in a way that changes the label, for example flipping digits or letters where orientation matters.
Important Questions:
- What is transfer learning? Reusing a model pre-trained on a large source dataset as the starting point for a related target task that has little labeled data; the pre-trained layers are fine-tuned or kept frozen with adapters.
- How does self-training use unlabeled data? A model trained on the labeled set predicts labels for unlabeled examples, only confident predictions are kept as pseudo-labels, and the model is retrained on the enlarged set. Errors can reinforce themselves, which is why the confidence threshold matters.
Chapter 20: Dimensionality Reduction
Part V: Beyond Supervised Learning · Difficulty: Hard · Key topics: PCA, scree plot, factor analysis, probabilistic PCA, autoencoders, variational autoencoder, manifold learning, MDS, t-SNE, word2vec, GloVe
Chapter 20 looks for compact descriptions of high-dimensional data. PCA is derived as the projection that keeps the most variance, computed from the eigenvectors of the covariance or correlation matrix or from the SVD, with digit and face examples and ways to choose the number of dimensions. Factor analysis and probabilistic PCA give PCA a generative model fitted with EM. Autoencoders compress through a bottleneck and come in denoising, contractive, sparse and variational forms. Manifold learning starts from the manifold hypothesis and covers classical MDS, Isomap, kernel PCA, LLE, Laplacian eigenmaps and t-SNE, with a note on UMAP. The chapter ends with word embeddings: latent semantic analysis, PMI, word2vec with negative sampling, GloVe and contextual embeddings.
Key Points:
- The first principal component is the top eigenvector of the data covariance matrix, which is also the direction of maximal variance of the projected data.
- Use the correlation matrix (standardized features) when features have different scales, otherwise PCA follows the largest-scale direction.
- Reconstruction error always falls as components are added, so pick the number of dimensions from a knee in the scree plot, the explained variance or profile likelihood.
- Probabilistic PCA is factor analysis with equal noise in every direction; the only stable fixed point of its EM algorithm is the global optimum.
- A linear bottleneck autoencoder spans the same subspace as PCA; a variational autoencoder maximizes the ELBO and uses the reparameterization trick to pass gradients through sampling.
- t-SNE turns distances into neighbor probabilities and uses a heavy-tailed Student t in the map; the perplexity setting matters, and cluster sizes and gaps in the plot should not be over-read.
- word2vec (CBOW and skip-gram with negative sampling) and GloVe learn vectors in which words that share contexts lie close together.
Practice Tip: Run PCA on a digits dataset, plot the first two components coloured by label, then make the same plot with t-SNE and compare how well the classes separate.
Common Mistake: Running PCA without centering (and without scaling when features have different units). The first component then just follows the mean or the largest-scale feature.
Important Questions:
- How does PCA choose its directions? It picks orthogonal directions in order of decreasing variance, which are the eigenvectors of the data covariance with the largest eigenvalues.
- What is the manifold hypothesis? The assumption that most naturally occurring high-dimensional data lies near a much lower-dimensional manifold, which manifold learning methods try to unfold.
Chapter 21: Clustering
Part V: Beyond Supervised Learning · Difficulty: Medium · Key topics: purity, Rand index, hierarchical clustering, single, complete and average link, K-means, vector quantization, K-means++, K-medoids, choosing K, Gaussian mixtures, spectral clustering
Chapter 21 begins with the difficulty of judging a clustering without ground truth, and introduces external measures: purity, the Rand index and mutual information. Agglomerative clustering repeatedly merges the closest groups into a dendrogram and compares single, complete and average linkage, with a yeast gene-expression example of 300 time series. K-means alternates assignments and centroid updates to reduce distortion, is run on 2d points and the same yeast data, and is linked to vector quantization for image compression; K-means++ initialization, K-medoids, speedups and ways to choose K are discussed. Mixture models give soft clusters, and the starred sections cover spectral clustering through the graph Laplacian and biclustering.
Key Points:
- Purity is the fraction of points that belong to the majority class of their cluster, but it reaches 1 trivially if every point gets its own cluster.
- The Rand index is the fraction of point pairs on which a clustering and a reference agree; an adjusted version corrects for chance.
- Naive agglomerative clustering takes
O(N^3)time, reduced toO(N^2 log N)with a priority queue. - Single link builds a minimum spanning tree and can chain clusters together, complete link favors compact clusters, and average link is the usual compromise but is sensitive to the measurement scale.
- K-means minimizes distortion by alternating minimization; it is non-convex, so scikit-learn by default combines K-means++ with 10 restarts and keeps the lowest distortion.
- K-means++ picks each new center with probability proportional to its squared distance from the nearest center already chosen.
- K-medoids uses an actual data point as each center, so it resists outliers and works with any dissimilarity.
Practice Tip: Run K-means for K from 2 to 10 on a dataset and plot the inertia and the silhouette score. See whether the two choices of K agree.
Common Mistake: Running K-means once and trusting the answer. Different random starts give different clusters, so use several restarts or K-means++.
Important Questions:
- How does the K-means algorithm work? Initialize K centroids, assign each point to its nearest centroid, recompute each centroid as the mean of its points, and repeat until assignments stop changing.
- How do Gaussian mixtures differ from K-means? They give each point a probability of belonging to each cluster and allow different covariances, whereas K-means makes hard assignments to spherical clusters.
Chapter 22: Recommender Systems
Part V: Beyond Supervised Learning · Difficulty: Medium · Key topics: explicit feedback, collaborative filtering, matrix factorization, probabilistic matrix factorization, AutoRec, implicit feedback, Bayesian personalized ranking, factorization machines, cold start, exploration-exploitation
Chapter 22 treats recommendation as filling in a huge, sparse user-by-item matrix. With explicit ratings, the Netflix Prize data and the public MovieLens data set the scene. Collaborative filtering predicts a rating as a similarity-weighted average over other users, while matrix factorization learns low-rank user and item vectors with user and item biases, fitted by alternating least squares or SGD and extended to probabilistic matrix factorization. AutoRec swaps the factorization for an autoencoder. For implicit feedback, Bayesian personalized ranking learns to rank chosen items above the rest, and factorization machines and neural matrix factorization add feature interactions. Side information tackles cold start, and the last section explains the feedback loop behind exploration versus exploitation.
Key Points:
- The ratings matrix has M users and N items and is very sparse; the Netflix data held about 100 million ratings and was still 99% unknown.
- Matrix factorization predicts a rating as a global mean plus a user bias plus an item bias plus the dot product of a user vector and an item vector, fitted with L2 regularization.
- The model can be optimized with alternating least squares (solve for U given V, then V given U) or with SGD on the observed entries, and the objective is non-convex.
- AutoRec predicts a whole column of ratings with an autoencoder; its item-based version did better than the user-based one on MovieLens and Netflix.
- Bayesian personalized ranking trains on triples (u, i, j), where user u chose item i but not j, and rewards f(u, i) being larger than f(u, j); negatives are subsampled.
- A factorization machine models all pairwise feature interactions and can be computed in
O(KD)rather thanO(KD^2)time after rewriting the sum. - New users and items (cold start) need side information, and because the training data come from earlier recommendations the system must sometimes explore.
Memory Tip: Matrix factorization gives every user and every item a short vector, and the predicted rating is just their dot product (plus biases).
Common Mistake: Treating every unrated item as one the user dislikes. The user may simply never have seen it; the chapter assumes data are missing at random only for simplicity.
Important Questions:
- What is matrix factorization in recommendation? The sparse user-item matrix is approximated by the product of a user factor matrix and an item factor matrix of low rank, and missing ratings are predicted from the learned vectors.
- What is the exploration-exploitation tradeoff in recommender systems? The system is trained on data produced by its own earlier recommendations, so showing only the currently best items never reveals whether something better exists. Occasionally showing uncertain items explores and gathers information for later recommendations.
Chapter 23: Graph Embeddings *
Part V: Beyond Supervised Learning · Difficulty: Hard · Key topics: graph representation learning, encoder-decoder framework, shallow embeddings, DeepWalk, label propagation, message-passing GNNs, GCN, GraphSAGE, graph attention, graph autoencoders, link prediction
Chapter 23, coauthored with Bryan Perozzi, Sami Abu-El-Haija and Ines Chami, asks how to learn low-dimensional vectors for the nodes of a graph. It explains why convolutions designed for grids do not carry over to irregular graphs, separates unsupervised from supervised and transductive from inductive settings, and organizes methods in one encoder-decoder framework called GraphEDM. Shallow embeddings use a lookup table of vectors trained with distance-based losses, matrix factorization or skip-gram on random walks (DeepWalk), and label propagation is the simple supervised case. Graph neural networks follow, with message passing, spectral and spatial convolutions, GraphSAGE, attention and hyperbolic variants, then graph autoencoders and deep graph infomax, and applications from link prediction to graph classification.
Key Points:
- A graph is given by an adjacency matrix and optional node features; nodes have no fixed ordering or neighborhood shape, so grid convolutions cannot be applied directly.
- In the GraphEDM view an encoder maps the graph and features to embeddings, a decoder rebuilds similarities or predicts labels, and the loss combines supervised, graph reconstruction and weight regularization terms.
- Shallow embeddings learn one free vector per node (an embedding lookup), so they are transductive and cannot embed a node unseen in training.
- DeepWalk treats truncated random walks as sentences and trains skip-gram on them, which behaves like an implicit matrix factorization.
- In a message-passing GNN each layer aggregates messages from neighbors; GraphSAGE samples fixed-size neighborhoods so it can work inductively, and graph attention networks weight neighbors by learned scores.
- Spectral graph convolutions are defined through the graph Laplacian, and the spectrum-based kind cannot transfer to a new graph, while spatial convolutions work directly on neighborhoods.
- Graph autoencoders (GAE, VGAE) pair a GCN encoder with an inner-product decoder, and deep graph infomax contrasts real node features with shuffled ones.
Memory Tip: A GNN layer is neighbourhood gossip: every node collects what its neighbours know, combines it with its own state and passes it on.
Common Mistake: Treating link prediction as the same task as graph reconstruction. Reconstruction only checks that embeddings preserve edges that were seen; link prediction hides some edges and tests whether the model can recover them.
Important Questions:
- What is a graph neural network? A neural network that updates node representations by repeatedly aggregating information from neighboring nodes, so predictions respect the graph structure and can use node features.
- How do shallow and deep graph embeddings differ? Shallow methods learn a lookup table of vectors, ignore node features and cannot embed unseen nodes. Deep methods compute embeddings with a neural network over node features and graph structure, so they can generalize to new nodes and graphs.
Appendix A: Notation
Appendix · Difficulty: Easy · Key topics: mathematical symbols, vector and matrix notation, matrix calculus, probability notation, information theory, supervised and unsupervised learning, abbreviations
Appendix A is the book’s notation reference. It opens by admitting that no single notation fits machine learning, statistics and optimization, so a symbol can change meaning with context. It lists common symbols such as the defined-as and proportional-to signs, the probability simplex and the cone of positive definite matrices, then functions of one, two and more arguments, from the indicator and Dirac delta to the sigmoid, beta and gamma functions and softmax. The linear algebra part fixes conventions: bold lowercase vectors that are columns by default, bold uppercase matrices, and the gradient and Hessian. Later parts give notation for optimization, probability, information theory and learning, and a table of abbreviations ends the appendix.
Key Points:
- Vectors are bold lowercase and are column vectors unless stated otherwise; matrices are bold uppercase and scalars are plain lowercase.
- A hat marks an estimate or prediction, a star marks a true but usually unknown value, and an overline marks a mean.
- A pdf or pmf is written
p, a cdf isP, the probability of a binary event isPr, and X ~ p means X is distributed according to p. - Information theory uses H for entropy, D_KL(p || q) for KL divergence and I(X; Y) for mutual information.
- Supervised learning uses inputs x in a space X, outputs y, and a training set D of N pairs stored as an N x D design matrix.
- Unsupervised learning is written as density estimation p(x | theta) with latent variables z, and Bayesian inference writes a prior p(theta | xi) with hyperparameters xi.
- The abbreviations table expands terms such as MLE, MAP, EM, SGD, SVM, KL, MCMC and wrt.
Practice Tip: Keep the appendix open beside Chapters 7 and 8, and before starting each chapter skim the lines for the quantities it uses.
Common Mistake: Assuming a symbol means the same thing as in another textbook. The appendix itself warns that conventions differ between fields and books, so check it first.
Important Questions:
- What do a hat and a star on a symbol mean in this book? A hat denotes an estimate or prediction, such as theta-hat or y-hat, and a star denotes the true but usually unknown value, such as theta-star.
- Where do you find the meaning of an abbreviation such as MLE or EM? In the abbreviations list in Section A.9 at the end of Appendix A.
How to Study This Book
The book has an introduction (Chapter 1) and five parts: Foundations (Chapters 2 to 8), Linear Models (9 to 12), Deep Neural Networks (13 to 15), Nonparametric Models (16 to 18) and Beyond Supervised Learning (19 to 23). The preface explains that advanced material is marked with an asterisk in the section or chapter title and can be skipped in an introductory course. Chapters 12, 17 and 23 are starred as a whole, and many sections inside other chapters are too. Read Chapter 1 first; it is easy and gives you the vocabulary for everything else.
Be honest about the maths. The book expects calculus, linear algebra and probability at university level, and Chapters 2 to 8 revise them quickly rather than teach them from scratch. If probability is new to you, work through Chapters 2 and 3 slowly with a pencil. If you already know it, skim them and slow down at Chapter 4 (maximum likelihood, MAP and regularization) and Chapter 5 (decisions and model selection), because the rest of the book keeps returning to those ideas. Chapter 6 on information theory is short; read at least the cross entropy and KL divergence sections before the neural network chapters.
Use Chapters 7 and 8 as reference chapters. Before you reach Chapter 20, make sure you understand the eigenvalue decomposition and SVD in Sections 7.4 and 7.5. Before Chapter 10 and Chapter 13, read the gradient descent and SGD sections of Chapter 8 (Sections 8.2 and 8.4). The EM algorithm in Section 8.7 is needed again for Gaussian mixtures in Chapters 20 and 21.
For a standard first machine learning course, a sensible core is Chapter 1, Sections 2.1 to 2.6, 3.1 and 3.2, 4.2 to 4.5, 5.1, 8.1 to 8.4, then Chapters 9 to 11, 13, 16 and 18, with Section 20.1 on PCA and Chapter 21 on clustering. For a deep learning course, read Chapter 13 closely (work through backpropagation in Section 13.3 by hand), then Chapter 14 for images and Chapter 15 for sequences, where Sections 15.4 and 15.5 on attention and transformers and Section 15.7 on pretrained language models matter most. Chapter 17 (kernels, Gaussian processes, SVMs) is optional unless your syllabus names SVMs.
Do the exercises. Fourteen chapters end with exercises (Chapters 2 to 11, 13, 17, 19 and 20). The author publishes solutions to the exercises without a dagger mark on the book page, and the solutions to the dagger-marked ones are for qualified instructors through MIT Press. Attempt each exercise before opening the solutions. The book’s figures also have Python notebooks (in the pyprobml repository) built on NumPy, scikit-learn, JAX, PyTorch and TensorFlow, so run a notebook whenever a chapter introduces a model.
Know what is left out. The book has no dedicated chapter on reinforcement learning (only the short introduction in Section 1.4 and a note in Section 22.4). It also treats approximate Bayesian inference briefly: Section 4.6.8 sketches grid, Laplace, variational and MCMC approximations and Section 20.3.5 covers variational autoencoders, but a full treatment of MCMC and variational inference is left to the sequel. The author wrote a separate sequel, Probabilistic Machine Learning: Advanced Topics, for more advanced material. If your syllabus includes those topics, plan a second source for them.
Used In These Programs
This book is used for the Machine Learning course in: BS Computer Science and BS Artificial Intelligence, and for MS-level machine learning courses. Browse all Machine Learning books or all Computer Science books.
Who Should Read This
This book is written for advanced undergraduate and graduate students: BS AI and BSCS students in a machine learning or deep learning course (typically in the later semesters) and MS students who want a rigorous probabilistic foundation. You should be comfortable with calculus, linear algebra, basic probability and Python before you start. It is a good fit if you want one coherent view that connects classical methods such as regression, SVMs and trees with deep learning, and want the maths behind each model. It is not a first programming book, it is not a quick recipe collection for tools, and it is not an entry-test book. If probability or statistics feels shaky, pair it with Think Stats and Think Bayes, and for the proof style and discrete maths behind the theory use Mathematics for Computer Science.
Applicable Universities
This book is useful for students at Pakistani universities offering BS Artificial Intelligence, BS Computer Science and MS-level machine learning courses, including Punjab University, Virtual University, COMSATS, FAST, UET, NUST, and other HEC-recognized institutions.
Official Copy of Probabilistic Machine Learning: An Introduction
The author offers the book free of charge. Click the button below to open his official book page, where the latest online PDF and the exercise solutions are available. He asks readers to cite the MIT Press edition.
→ Visit Official PageFAQs
Is Probabilistic Machine Learning: An Introduction free?
Yes. The author offers a free PDF on his official book page, and the PDF’s copyright page says the work is subject to a Creative Commons CC-BY-NC-ND license. In plain terms you may read and share it with credit for non-commercial use, but you may not change it. The printed MIT Press edition is sold separately. This page links to the official site and does not host the file.
Which edition is this?
The book was published by MIT Press in March 2022. The PDF on the author’s page is labelled Online version, April 18, 2025, and its changelog lists printings in March 2022, April 2023 and January 2025. The author asks readers to cite the MIT Press reference.
How many chapters and exercises does it have?
There are 23 chapters in five parts, plus Appendix A on notation. Fourteen chapters end with exercises (Chapters 2 to 11, 13, 17, 19 and 20). Solutions to the exercises without a dagger mark are posted on the book page, while the solutions to the dagger-marked exercises are available to qualified instructors from MIT Press.
Is it good for complete beginners?
No. It is written for advanced undergraduates and graduate students. You should already be comfortable with calculus, linear algebra, probability and some Python. Chapters 2 to 8 revise the maths, but they move quickly. A beginner should start with a gentler text and use this book as the next step.
Does it cover deep learning, transformers and reinforcement learning?
Part III covers multilayer perceptrons, backpropagation, convolutional networks, recurrent networks, attention, transformers and pretrained language models such as BERT, GPT and T5. Reinforcement learning only gets a short introduction in Chapter 1 in this volume, and the author wrote a separate sequel, Probabilistic Machine Learning: Advanced Topics, for more advanced material.
Does the book come with code?
Yes. Most figures have matching Python notebooks that run on Google Colab, and the preface lists NumPy, scikit-learn, JAX, PyTorch, TensorFlow and PyMC among the libraries used. The notebooks live in the author’s pyprobml repository, which is linked from the official book page.
Related Books
- Think Bayes: Bayesian Statistics in Python – Allen B. Downey
- Think Stats: Exploratory Data Analysis in Python – Allen B. Downey
- Mathematics for Computer Science – Lehman, Leighton & Meyer
- Calculus Volume 3 – Strang & Herman (OpenStax)
Probabilistic Machine Learning: An Introduction gives you one consistent probabilistic view of machine learning, from maximum likelihood and Bayes’ rule to deep networks, kernels and trees, in a book the author makes free to read. It demands real mathematics, but it rewards the effort with understanding that carries into research and industry work. Browse more Computer Science books for the rest of your semester.
Probabilistic Machine Learning: An Introduction by Kevin P. Murphy, MIT Press, 2022. The PDF’s copyright page states that the work is subject to a Creative Commons CC-BY-NC-ND license (no version number is given), and its page footer carries the notice “Author: Kevin P. Murphy. (C) MIT Press. CC-BY-NC-ND license”. The PDF is labelled Online version, April 18, 2025, and the author asks readers to cite the MIT Press edition. Official source: https://probml.github.io/pml-book/book1.html. This page links to the official site and does not host or copy the book.
© Copyright Policy
Freebooks.pk is an educational resource for students in Pakistan. Textbooks and other books belong to their respective boards, authors and publishers, and all rights remain with them. If you are the copyright holder of any material on this page and want it changed or removed, please contact us or file a request under our DMCA policy. We review every request and remove reported content promptly.
