Deep Learning Notes-2: Probability Distributions, Linear Regression, and the Bias-Variance Tradeoff
Deep Learning Notes-2, covering the Bernoulli distribution, multinomial distribution, multivariate Gaussian distribution, the probabilistic derivation of linear regression, decision theory, and the bias-variance tradeoff. Corresponds to Chapters 3-4 of "Deep Learning: Foundations and Concepts".
Part 2/8 of the series ← Previous | Next | Glossary
It is recommended to read Part 1 first (foundations of probability theory). This part covers common probability distributions, the probabilistic derivation of linear regression, and the bias-variance tradeoff.
Chapter 3 Standard Distributions
This chapter assumes that all observed data are independent and identically distributed
Discrete Variables
Bernoulli Distribution
Intuition: Flipping a coin, the outcome is either heads (1) or tails (0), and the probability of heads is . The Bernoulli distribution is the mathematical description of this “black or white” scenario—it characterizes the probability of a single binary random variable (a binary random variable, one that can only take the value 0 or 1) . Its probability mass function (the probability description of a discrete variable) is:
where is the probability that , with . The expectation and variance of this distribution are respectively:
Given an independent and identically distributed (i.i.d., each sample is unaffected by the others and comes from the same distribution) dataset , its likelihood function (a measure of how well the parameters explain the data) is:
The log-likelihood function is:
By maximizing the log-likelihood (taking the derivative with respect to the parameter and setting it to zero), we obtain the maximum likelihood estimate (Maximum Likelihood, ML, the parameter value that maximizes the probability of the data occurring):
also known as the sample mean; here is the number of observations in the dataset for which . This shows that the maximum likelihood estimate is simply the proportion of “success” events in the sample.
Binomial Distribution
Intuition: A coin is flipped times; what is the probability that heads comes up exactly times? This is the question answered by the Binomial distribution—it describes the probability of the total number of “successes” in independent Bernoulli trials (each an independent coin flip). Its probability mass function is:
The expectation and variance of this distribution are:
As , by the central limit theorem, the binomial distribution approaches the Gaussian distribution (normal distribution).

As N increases, the binomial distribution approaches the Gaussian distribution (normal distribution)
Multinomial Distribution
Intuition: Rolling a die, the six faces each have different probabilities of coming up. If you roll it times, how many times does each face appear? The Multinomial distribution is the generalization of the Bernoulli distribution from “flipping a coin” to “rolling a die”—it handles the case of multiple categories ( states). Consider a -state discrete variable (a variable that can only take a finite number of values) , represented using 1-of- encoding (only one of positions is 1, the rest are 0, also called one-hot encoding) as . Let be the probability that , satisfying . For a single observation, its distribution is:
For independent observations, let be the number of times the -th state appears (i.e., ); then the multinomial distribution is (proof omitted):
Its maximum likelihood estimate is:
Multivariate Gaussian Distribution (Normal Distribution)
Univariate Gaussian Distribution
Let us recall the univariate (one-dimensional) normal distribution mentioned earlier:
The probability density function of the univariate Gaussian distribution (normal distribution) is:
where is the mean, is the variance, is the standard deviation, and is the precision. The latter part of the expression can be understood as normalization.
Multivariate Gaussian Distribution
Intuition: Imagine a cloud in the shape of an ellipsoid, with data points densely clustered near the center and becoming sparser toward the outside. The Multivariate Gaussian distribution (also called the multivariate normal distribution) is the mathematical description of this “dense in the middle, sparse around the edges” ellipsoidal distribution. For a -dimensional random vector (a vector composed of multiple random variables) , the multivariate Gaussian distribution is:
(which can be understood as the cumulative result of the one-dimensional case) where is the -dimensional mean vector (a vector composed of the average values along each dimension), and is the covariance matrix (a symmetric positive-definite matrix that describes the spread of each dimension and the correlations between dimensions). is called the precision matrix (the inverse of the covariance matrix). The latter part of the expression can similarly be understood as normalization.
For the two-dimensional case, the covariance matrix is written out as:
The diagonal contains the variance of each dimension itself (its covariance with itself), and the off-diagonal contains the covariance between different dimensions (the tendency of and to vary together). Since the covariance matrix is symmetric, .
The equiprobability density surface (the surface formed by points of equal probability density) of the Gaussian distribution is determined by the quadratic form , a quantity called the Mahalanobis distance (a “distance” measure that accounts for differences in scale across dimensions and correlations). When the covariance matrix is the identity matrix, the Mahalanobis distance reduces to the ordinary Euclidean distance.

How the eigenvalues and eigenvectors of the covariance matrix affect the shape of the distribution (such as the direction and length of the principal axes of the ellipse)
The eigenvectors (vectors whose direction is unchanged under the matrix transformation) and eigenvalues (the corresponding scaling factors) of the covariance matrix determine the shape of the Gaussian distribution. The eigenvectors define the directions of the principal axes, and the square roots of the eigenvalues are proportional to the lengths of the principal axes. (Proof omitted)
Moments
Intuition: If you imagine a probability distribution as a thin plate of irregular shape, then the “moments” are the statistics that describe the characteristics of this plate in different directions. The first moment is the center of gravity of the plate, and the second moment describes how “fat or thin” the plate is around its center of gravity. Specifically:
Derivation of the first moment (click to expand)
The first moment is the expectation of the random vector . For the multivariate Gaussian distribution with parameters and , its expectation is computed as:
By the variable substitution and expanding, the integral can be transformed into:
The exponential term is an even function of , while the integration interval is . Therefore, the term involving (i.e., itself) integrates to zero over the symmetric interval (by symmetry). The remaining term is:
Because the Gaussian distribution is normalized, its integral equals 1. Therefore, we conclude:
This confirms that the parameter is the mean vector of this Gaussian distribution.
Conclusion: The first moment (expectation) equals the parameter , i.e., the “center of gravity” of the distribution. Mathematically:
Derivation of the second moment (click to expand)
The second moment involves the expectation of the outer product of the random vector , . This contains elements , which can be combined into a matrix.
The computation of similarly uses the variable substitution :
Expanding gives four terms: , , , and . By symmetry, the integrals of and are zero. is a constant and can be pulled outside the integral, whose value is 1. The key part is the expectation of :
Using the eigenvector expansion of the covariance matrix (, where , is an eigenvector, and is an eigenvalue), it can be shown that:
Finally, we obtain:
Conclusion: The second moment is .
Covariance matrix:
When defining variance, we usually first subtract the mean—just as when measuring “how far from the center of gravity.” For the multivariate case, the covariance of the random vector is defined as:
Substituting and :
where is the second moment and is the square of the first moment.
Therefore, the parameter matrix is precisely the covariance matrix of this Gaussian distribution, which determines the spread of the data in each direction and the correlation between variables.
Conditional and Marginal Gaussian Distributions
Intuition: Imagine a two-dimensional ellipsoidal cloud of data. If you “cut a slice” along a vertical line, the cross-section is still a one-dimensional Gaussian (bell curve); if you “project away” one of the dimensions, what remains is still a Gaussian. This is the closure property of the Gaussian distribution.
An important property of the Gaussian distribution is that both its conditional distribution (the distribution of the remaining variables given part of the variables) and its marginal distribution (the distribution of the remaining variables after ignoring some variables) are also Gaussian distributions.
Split into two parts and , and correspondingly partition the mean and the covariance matrix :
Conditional distribution: (split)
where: (proof omitted)
Note that the mean of the conditional distribution is a linear function of , and the covariance is independent of .
In the proof, the block matrix inversion formula is used; it is included here as well:
where it is defined that:
The quantity is called the Schur complement of the left matrix with respect to the submatrix .
Suppose we have a two-dimensional Gaussian distribution: Now given , find the conditional distribution of :
, ,
Conditional mean:
Conditional variance:
So:
- Marginal distribution: (dimensionality reduction, looking only at the probability distribution of ) If , where: then the marginal distribution of is: where:

The left figure shows the probability density function (PDF) of a two-dimensional Gaussian distribution, represented as contour lines. The contours are elliptical (see Gaussian Geometry above), centered at the mean point , and the direction of the principal axes of the ellipse is determined by the covariance matrix (there is positive correlation here because ). The denser the ellipse, the higher the probability density; the outer ellipses represent low-probability regions. The distribution has positive correlation ( and vary in the same direction), manifested as the ellipse being stretched along the diagonal.
The red horizontal line indicates the slice at , used to extract the conditional distribution.
The right figure shows a one-dimensional distribution curve:
The blue curve: is the marginal distribution of (i.e., ignoring the influence of ).
The red curve: is the conditional distribution of given .
The conditional distribution uses the observed value of to provide a more precise prediction of .
The marginal distribution only reflects the overall statistical properties of and does not depend on a specific value of .
It can also be seen that: the conditional distribution of a Gaussian distribution is still a Gaussian distribution, and its mean and variance can be computed from the covariance matrix.
Bayes’ Theorem + Gaussian Distribution
Why read this section? This conclusion will be used repeatedly later—Bayesian linear regression, Gaussian processes, and probabilistic PCA all rely on it. To put it simply: if both the prior and the likelihood are Gaussian, then the posterior is also Gaussian—which is very convenient computationally, because a Gaussian distribution is completely described by just its mean and covariance.
When the prior distribution of one variable (see Part 1 - Bayes’ Theorem) and the conditional distribution of another variable are both Gaussian, the posterior distribution (the updated belief about the parameters after observing the data) is also a Gaussian distribution.
Consider two random variables and . We have the following two distributions:
- Prior distribution (the belief about the parameters before observing the data):
- This is the initial belief about , a Gaussian distribution with mean and covariance matrix ( is the precision matrix).
- Likelihood distribution (the probability of the observed data given the parameters):
- The probability of observing given . It is also a Gaussian distribution, whose mean is the linear function of , with covariance matrix .
Our goal is to use Bayes’ theorem to compute the posterior distribution , i.e., the updated belief about after observing .
Bayes’ theorem states:
First, we construct the joint distribution of as . By the definition of conditional probability:
Substituting the expressions for the two Gaussian distributions and taking the logarithm, we obtain the log form of the joint distribution:
After expanding and reorganizing, it can be found that is a quadratic form in . This shows that the joint distribution itself is also a multivariate Gaussian distribution.
For a multivariate Gaussian distribution, its precision matrix (i.e., the inverse of the covariance matrix) can be obtained from the quadratic coefficient in the log probability density function. (The quadratic term )
Extracting the quadratic term in from the above expression, we obtain the precision matrix of the joint distribution:
Using the block matrix inversion formula (see above, block matrix inversion), we can find the covariance matrix :
The expectation of is:
- Marginal distribution :
- Extracting the part of from the mean and covariance of the joint distribution above:
- This shows that the mean of is the result of the mean of after linear transformation, and its covariance is the sum of the observation noise covariance () and the covariance introduced by the uncertainty of () through the linear transformation.
- Conditional distribution :
- Using the properties of the block precision matrix (see above, block matrix inversion), we can directly write out the mean and covariance of : where
Therefore:
- The posterior covariance is jointly determined by the prior precision () and the likelihood precision (), reflecting the combination of prior information and observed information.
- The posterior mean is a weighted average of the prior mean and the “prediction” based on the observation , with weights determined by their respective uncertainties (covariances).
Maximum Likelihood Estimation
Consider an independent and identically distributed dataset , assumed to be generated by a multivariate Gaussian distribution . Its log-likelihood function is:
Taking the derivative with respect to the mean and the covariance matrix respectively and setting the derivatives to zero yields the maximum likelihood estimates:
is the sample mean, and is the sample covariance. Similar to the univariate case, is a biased estimate of the true covariance.
Sequential Estimation
Intuition: Imagine you are wearing a wristband while running that calculates your average pace. Every kilometer you run, the wristband corrects the previous estimate with the new data, rather than recalculating from scratch. Sequential estimation is this kind of online algorithm that “updates as it collects data.”
When data arrives in a streaming fashion (streaming, the data does not all arrive at once, but arrives one by one or in batches), a method is needed to update the parameter estimates online (without recomputing everything). For the mean, we can use:
This shows that the new estimate equals the old estimate plus a “correction term,” which is times the difference between the new data point and the old estimate; therefore, as grows larger and larger, the contribution of later terms becomes smaller and smaller.
Gaussian Mixture Model
Intuition: If the data clearly has multiple “clusters” (for example, male and female heights each form a peak), fitting with a single Gaussian distribution is like trying to cover two peaks with just one bell curve—no matter how you cover it, it won’t fit. The idea of the Gaussian Mixture Model (GMM) is to superimpose multiple bell curves—one Gaussian per “cluster,” mixed together in proportion.
Although the Gaussian distribution has good analytical properties, a single Gaussian distribution (with only one peak) cannot capture complex data structures, such as multimodal (multiple peaks) data.
The Gaussian Mixture Model (GMM) solves this problem by linearly combining Gaussian distributions (summing multiple Gaussian distributions weighted by proportions):
where is the mixing coefficient of the -th Gaussian component, satisfying and . Each is called a component.

Left: unmixed Gaussian distribution fit; right: mixed Gaussian distribution fit (two peaks)
- By adjusting the number of components , the mean , the covariance , and the mixing coefficient of each component, the Gaussian mixture model can approximate any continuous probability density function.
- For ease of analysis, a -dimensional latent variable (to distinguish multiple different groups) can be introduced, using 1-of-K encoding (see Chapter 5 - 1-of-K encoding) where only one element is 1 and the rest are 0. The position of the element that is 1 indicates which category the sample belongs to. means the data point was generated by the -th component. The mixing coefficient can be interpreted as , i.e., the prior probability. The conditional probability . By marginalizing over the latent variable , we obtain the marginal distribution , i.e., the Gaussian mixture model.
- Given a data point , its posterior probability of belonging to the -th component is:

One-dimensional and two-dimensional Gaussian mixtures
Modeling Periodic Variables - von Mises Distribution
Intuition: Imagine a pointer on a clock, wobbling slightly around a certain angle. If you model this with an ordinary Gaussian distribution, the angles and would be treated as two points far apart, but in reality they are only apart. The von Mises distribution is designed for this kind of “circular data”—it is the analogue of the Gaussian distribution defined on a circle.
A periodic variable (such as an angle ) cannot be effectively modeled with a standard Gaussian distribution, because the support (the range of values the variable can take) of the Gaussian distribution is the entire real line, and it cannot handle the periodic connection between and .
The von Mises distribution is also called the circular normal distribution. Its probability density function is (derivation omitted):
where is the mean direction, is the concentration parameter (similar to precision), and is the zeroth-order modified Bessel function, used for normalization. When is large, the distribution concentrates near , approximating a Gaussian distribution; when , the distribution reduces to the uniform distribution on .
Maximum likelihood estimation: For a dataset , the maximum likelihood estimate of satisfies:
This shows that is the direction of the centroid of the data points projected onto the unit circle. The maximum likelihood estimate of requires numerically solving the equation , where , and .
The von Mises distribution is also unimodal. To model multimodal periodic data, a mixture model of von Mises distributions can be used.

von Mises distribution (left in Cartesian coordinates, right in polar coordinates)
Exponential Family Distributions
Intuition: The Bernoulli, Gaussian, and other distributions discussed earlier look different in shape, but they are actually all “one family”—the exponential family. Just as different drinks (coffee, tea, juice) can all be described using the framework of “water + solute,” the exponential family provides a unified mathematical framework that encompasses most commonly used distributions.
So far, the probability distributions studied are essentially all exponential family distributions (except for mixture models).
The exponential family is a large and important class of probability distributions, whose general form is:
where:
- is the natural parameter vector (the transformation of the original parameters into the standard form of the exponential family),
- is the sufficient statistic vector (contains all the information needed to extract the parameters from the data),
- is the underlying measure function (usually independent of the parameters),
- is the normalization function, ensuring that the integral of the distribution is 1:
It is sometimes also written in the log-normalization form (more common):
where is called the log partition function or cumulant generating function.
In plain terms: The exponential family writes out various common distributions (Bernoulli, Gaussian, Poisson, etc.) using a unified “template.” is the “natural parameter” after transforming the original parameters (such as the Gaussian’s ), is the “sufficient statistic” of the data (a function that summarizes all the information in the data), and handles normalization. The benefit of this unified framework is that many properties (such as how to compute the maximum likelihood estimate, and whether a conjugate prior exists) hold for all exponential family distributions, without needing to derive each distribution separately.
Properties:
- Sufficient statistic (given the dataset, the parameters can be accurately recovered)
- In maximum likelihood estimation, the solution for the parameters depends only on the function of the data , without needing to store the entire dataset.
- This means that once is computed, the original data can be discarded, which is very efficient for large-scale data processing.
- Computation of moments
- The moments (expectation, variance, etc.) of the distribution can be obtained by differentiating :
- This makes the computation of expectation and variance systematic and analytically tractable.
- Existence of conjugate priors
- Every exponential family distribution has a corresponding conjugate prior, such that the posterior distribution belongs to the same family as the prior.
- Maximum entropy property
- Under given constraints (such as fixing the mean and variance), the exponential family distribution is the distribution with maximum entropy, i.e., the most “uncertain” or most “unbiased” choice.
Examples:
- Bernoulli distribution
- Let , .
- Convert to exponential family form:
- Correspondence:
- (logit transform),
- ,
- ,
- .
- Univariate Gaussian distribution
- Probability density function:
- Rewrite in exponential family form:
- where:
- Natural parameters: ,
- Sufficient statistic: ,
- Log partition function: .
Non-parametric Methods
Intuition: The previous methods all assume that the data follows some specific distribution (such as Gaussian), and then estimate the parameters. Non-parametric methods do the opposite—they do not presuppose the shape of the distribution, but let the data “speak for itself.” It is like using a ruler to measure the outline of an irregular object, rather than first assuming it is circular.
Non-parametric methods do not assume a fixed functional form for the distribution; their complexity (the model’s “degrees of freedom”) typically grows with the amount of data.
Histogram Density Estimation
Divide the range of the variable into fixed-width bins, and the density estimate is the frequency of data points in each bin divided by the bin width and the total amount of data. The advantages are simplicity and intuitiveness; the disadvantages are:
- Sensitive to bin width: too narrow leads to large noise, too wide leads to loss of detail.
- Discontinuity: the density jumps at bin boundaries.
- Curse of dimensionality: in high-dimensional space, most bins are empty.
Histogram density estimation is also a sufficient statistic.
Kernel Density Estimation
Kernel density estimation places a kernel function at each data point (placing a “small hill” around each data point and superimposing all these “small hills” to form the overall density estimate), and then sums them. Its form is:
where is the number of data points, is the dimension of the data (for example, for two-dimensional data ), is the bandwidth parameter (the width of each “small hill”), controlling the degree of smoothing, and is the kernel function (which must satisfy non-negativity and an integral of 1). ensures that each kernel function integrates to 1 over the entire space (the higher the dimension, the greater the “scaling” required). The Gaussian kernel is a common choice.

The effect of different bandwidths h on the estimation result in kernel density estimation (too small leads to noise, too large leads to oversmoothing)
The disadvantage is that the cost of evaluating the density at a new point is proportional to the amount of data , which is impractical for large datasets. The choice of bandwidth is key and affects the degree of smoothing.
K-Nearest-Neighbor Density Estimation
The K-nearest-neighbor method solves the problem of the fixed bandwidth in kernel density estimation. Its core idea is: near the estimation point , the sphere centered at contains exactly data points, and the volume of the sphere is determined by the data. The density estimate is:
where is the volume of the sphere containing the nearest neighbors.

The effect of different K values on the estimation result in K-nearest-neighbor density estimation (the difference between fixed bandwidth and adaptive bandwidth)
The advantage is adaptive smoothing. In dense data regions, is small, is small, capturing details; in sparse regions, is large, is large, avoiding noise. The disadvantage is again that it needs to store all the data, and computing the density at a new point requires finding the nearest neighbors, which is costly. When is small, the estimate may be unstable.
Exercise 1
You flip a coin 10 times, and get heads 7 times. What do you guess is the probability that this coin lands heads?
The maximum likelihood estimate tells you directly: . It is simply the frequency of heads, plain and simple.
But think about it—you draw a conclusion after only 10 flips. What if flips 11 through 100 are all tails? When there is too little data, MLE is easily led astray by “luck.”
If you feel “this coin is probably fair” (prior ), what would the MAP estimate become?
MAP reconciles your prior with the data: the posterior is , with a mode of about . It is pulled from the MLE’s toward —the prior “yanks” you back when there is little data, preventing you from trusting the luck of a small sample too much.
Exercise 2
When doing linear regression, we always assume the errors follow a Gaussian distribution. Why specifically Gaussian? And what does this have to do with “least squares”?
Actually, they are the same thing. If you assume the errors are Gaussian, then the maximum likelihood estimate turns out to be exactly “minimizing the squared error”—that is, least squares. So when you use least squares, you are essentially assuming the errors are Gaussian.
As the model becomes more complex (for example, as the degree of the polynomial gets higher), how do the bias and variance each change?
As complexity goes up, bias drops (the model can better capture the true pattern), but variance rises (it starts fitting the noise). Conversely, too simple means high bias and low variance. The optimal model is to find a “sweet spot” between the two.
Chapter 3 Summary
One-sentence version: This chapter starts from the simplest “coin flip” (Bernoulli), expands all the way to “rolling a die” (multinomial), the “ellipsoidal cloud” (multivariate Gaussian), “circular data” (von Mises), and finally strings them together with a “unified recipe” (exponential family), followed by the non-parametric methods that “let the data speak for itself.”
Knowledge map:
Standard Distributions├── Discrete Variables│ ├── Bernoulli Distribution (coin flip: single binary trial)│ ├── Binomial Distribution (N coin flips: number of successes)│ └── Multinomial Distribution (dice roll: multi-category generalization)├── Continuous Variables│ ├── Univariate Gaussian (one-dimensional bell curve)│ └── Multivariate Gaussian (ellipsoidal cloud)│ ├── Geometry: Mahalanobis distance → equiprobability density surface│ ├── Moments: first = center of gravity, second = spread│ ├── Conditional / Marginal Distributions (cut a slice / project away)│ ├── Bayesian Inference (Gaussian + Gaussian = Gaussian)│ └── Gaussian Mixture Model (multimodal superposition)├── Special Distributions│ ├── von Mises Distribution (circular data)│ └── Exponential Family (unified framework)└── Non-parametric Methods ├── Histogram (count in grid cells) ├── Kernel Density Estimation (place a small hill at each point) └── K-Nearest-Neighbor (adaptive sphere)Quick-reference table for choosing a distribution:
- Discrete binary data → Bernoulli distribution
- Count data → Binomial or multinomial distribution
- Continuous data assuming normality → Gaussian distribution
- Periodic data → von Mises distribution
- Complex multimodal data → Gaussian mixture model
Chapter 4 Single-Layer Networks: Regression
After the foundations of probability theory in Part 1 and the common probability distributions in Chapter 3 above, this chapter will explore how to use these distributions for actual predictive modeling—which is exactly the foundation of Part 3 (Classification). We will start from the most basic linear regression and gradually build a complete theoretical framework for regression analysis.
Linear Regression
Intuition: Drawing a “best-fit line” on a scatter plot so that the distance from all data points to this line is as small as possible—this is the core idea of linear regression. It predicts one or more continuous target variables based on a -dimensional input vector (a vector describing sample features) . Given a training set (training set) containing observations and their corresponding target values , the goal is to predict the value of for a new input . This is achieved through a function , where is the learnable parameter vector (a model fits the data by adjusting these parameters).
The simplest model is a linear combination of the input variables:
where . The key characteristic of this model is its linearity with respect to the parameters . However, it is also a linear function of the input variables , which limits its modeling capacity (it can only learn linear relationships).
Basis Functions
Intuition: If the data is not a straight-line relationship (for example, it is a parabola), fitting directly with a linear model does not work well. The idea of the basis function (basis function) is: first apply a nonlinear transformation to the original input (such as turning into , , etc.), and then take a linear combination of the transformed results. It is like straightening a bent wire first, and then measuring it with a ruler.
To expand the model’s capacity (to model nonlinear relationships), we can use a linear combination of fixed nonlinear functions of the input variables:
where is called the basis function (a fixed function that applies a nonlinear transformation to the input). The parameter is called the bias parameter, used to handle the fixed offset in the data. Usually, by defining a dummy basis function , the model can be written in a more compact vector form:
where , .
This model can be represented with a simple neural network diagram.
Common basis functions :
- Linear basis:
- Gaussian function:
- Sigmoid function:
Maximum Likelihood and Least Squares
Assume the conditional distribution of the target variable is a Gaussian distribution, with mean equal to the model output and variance :
For an independent and identically distributed (accumulated) dataset, its log-likelihood function (accumulated) is:
Maximizing the log-likelihood is equivalent to minimizing the sum-of-squares error function (see above, Chapter 2 - maximizing the log-likelihood is equivalent to minimizing the sum-of-squares error function):
Substituting the model into the error function above, and taking the derivative with respect to and setting it to zero, we obtain the normal equation for the least squares problem:
where is the design matrix (each row is a vector of basis function values for one sample), with elements .
Pseudo-inverse: When the matrix is not full rank / is not square, the least squares solution does not exist. In this case, the least squares solution can be obtained via the pseudo-inverse matrix (in this case, regarded as ).
Geometric interpretation of least squares:
Intuition: Imagine the target vector is a point in space, and the model can only “land” on a certain plane. Least squares finds the point on that plane closest to —that is, the orthogonal projection (vertical projection) of onto the plane.
The least squares solution can be understood as: the model prediction is the orthogonal projection of the target vector onto the linear subspace (the space formed by all linear combinations of the column vectors) spanned by the column vectors of the design matrix (i.e., the values of the basis functions at the data points). The error vector is orthogonal to this subspace, which is exactly the geometric meaning of the normal equation .

The essence of least squares is to project the true target vector onto the subspace expressible by the model
- The red plane represents the linear subspace spanned by the column vectors of the design matrix . This subspace is the set of all possible model outputs (i.e., the set of all function values the model can fit). Each column is the value of a basis function at a data point, and these vectors together constitute this subspace.
- The green arrow represents the true target value vector , pointing from the origin to a point not in the subspace . It represents the true observations we want the model to approximate.
- The blue arrow is the orthogonal projection of onto the subspace . It is the result of the model prediction, i.e., . The goal of least squares is to find such a so that it is as close as possible to .
- The black arrow represents the residual (error) , i.e., the gap between the actual value and the predicted value. It is perpendicular to the subspace , indicating that the error vector is orthogonal to any direction in the subspace. This is exactly the core meaning of the normal equation: (i.e., the error vector is orthogonal to the directions of all basis functions).
- represent the basis functions, with elements .
Sequential Learning
Intuition: The normal equation above needs to “swallow” all the data at once to compute the result. If the amount of data is huge or the data keeps arriving continuously, what do we do? The strategy of Stochastic Gradient Descent (SGD) is: for each data point that arrives, slightly adjust the parameters in the direction of decreasing error, just like adjusting your direction with each step as you go down a mountain.
When the dataset is large or data arrives in a streaming fashion, batch-processing all the data to compute may be impractical. Here we can use Stochastic Gradient Descent (SGD) for sequential learning. For the sum-of-squares error function, the SGD update rule is:
( uses the sum-of-squares error function above) where , and is the learning rate. This is called the Least Mean Squares (LMS) algorithm.
Regularized Least Squares
In Part 1 we discussed: to prevent overfitting (the model adapts too closely to the noise in the training data, leading to poor performance on new data), especially when there are many basis functions or little data, a regularization term (an additional term that penalizes model complexity) can be added to the error function. The simplest form is L2 regularization (L2 regularization, also called weight decay, which penalizes the sum of squares of the parameters):
The solution obtained by minimizing this function is:
The regularization term ensures that the matrix is always invertible, even when is singular. (It is an extension of ; see above, - normal equation for least squares problem)
Decision Theory
Intuition: You predict that tomorrow’s temperature is , but it is actually . How much did this prediction “miss” by? What does a difference of mean in terms of cost? Decision theory is the framework that answers “how to make optimal predictions based on a probabilistic model”; see Part 3 (Classification) for further discussion.
The next chapter will also explain in detail
Decision theory guides us on how to make optimal predictions based on a probabilistic model. For regression problems, we use a loss function (a function that quantifies the “cost” between the prediction and the true value) to quantify the cost between the prediction and the true value . The goal is to choose the prediction function to minimize the expected loss:
For the squared loss , the optimal prediction function that minimizes the expected loss is the conditional mean:
Be careful not to confuse the error function with the loss function. The error function is used to set the parameters during training, while the loss function is used to control how to use the conditional distribution to arrive at the prediction function f(x) for predicting x, which is exactly what the linear regression model tries to learn.
The expected loss can be decomposed into two parts:
The first term is the mean squared error between the prediction function and the true regression function (which can be reduced by improving the model), and the second term is the variance of the target variable given the input (irreducible error, the noise that cannot be eliminated no matter how good the model is).

The regression function that minimizes the squared loss is given by the mean of the conditional distribution
Other loss functions:
- Minkowski loss: .
- : the optimal solution is the conditional mean.
- : the optimal solution is the conditional median.
- : the optimal solution is the conditional mode.

Effect of different values of q
Bias-Variance Tradeoff
Intuition (target shooting metaphor): Imagine you are shooting at a target.
- Bias is whether your gun sight is aimed accurately—if the scope is crooked, all the bullets will deviate from the bullseye, but the holes will be tightly clustered.
- Variance is whether your hand is shaking—even if the scope is fine, a shaky hand will scatter the bullet holes around the bullseye.
- High bias + low variance = crooked scope but steady hand (simple model, underfitting)
- Low bias + high variance = straight scope but shaky hand (complex model, overfitting)
- Best = straight scope and steady hand (the balance point between bias and variance)
In model selection, there is a tradeoff between bias (the systematic prediction error of the model) and variance (the sensitivity of the model to changes in the training data). Bias measures the systematic deviation of the model’s average prediction from the true function. Variance measures the sensitivity of the model’s predictions to a specific training dataset.
Consider a simple regression problem, where the true function is , and the observed data is generated by , with being zero-mean noise. A model (dependent on the dataset ) is used for prediction. The expected prediction error can be decomposed as:
where is the average prediction of the model over different datasets (imagine training the same model with infinitely many different training sets and taking the average of the predictions).
- High bias, low variance (crooked scope but steady hand when shooting): a simple model (such as a low-degree polynomial) may fail to capture the complexity of the data, leading to high bias, but its predictions are insensitive to changes in the dataset (low variance) -> underfitting (the model is too simple and hasn’t even learned the patterns in the training data)
- Low bias, high variance (straight scope but shaky hand when shooting): a complex model (such as a high-degree polynomial) can fit the training data well (low bias), but may overfit the noise in the training data, leading to large prediction differences across different datasets (high variance) -> overfitting
The optimal model strikes a balance between bias and variance to minimize the total error. This tradeoff is the theoretical foundation of the model selection problem in Part 1, and will appear again in Part 3 (Classification).

Bias-variance tradeoff (variance grows larger on the left, bias grows smaller on the right)
Exercise 3
You do linear regression, and after adding L2 regularization the test set performance improves. How does this “accidentally” improve generalization?
Regularization puts a “tightening spell” on the model—it doesn’t allow the weights to be too large. As a result, the model complexity drops, and the variance drops along with it (it is less likely to be led astray by noise), but the bias will rise slightly (it becomes less flexible). However, as long as the regularization strength is appropriate, the part of the variance that drops is larger than the part of the bias that rises, so the total error actually decreases.
Put simply: it is better to underfit slightly than to overfit to the noise of the training set.
Chapter 4 Summary
One-sentence version: Linear regression = drawing the best-fit line on a scatter plot; decision theory = tells you how “best” is defined (minimize loss); bias-variance tradeoff = a model that is too simple underfits, too complex overfits, and you need to find a balance.
Knowledge map:
Single-Layer Networks: Regression├── Linear Regression│ ├── Basic model: y = w^T x (draw a straight line)│ ├── Basis function extension: y = w^T phi(x) (draw a curve)│ ├── Parameter learning│ │ ├── Maximum likelihood ≡ Least squares (normal equation)│ │ ├── Geometric interpretation: orthogonal projection│ │ └── Sequential learning: SGD / LMS│ └── Regularization: L2 weight decay (prevent overfitting)├── Decision Theory│ ├── Loss function: quantifies prediction cost│ ├── Squared loss → optimal prediction = conditional mean│ └── Expected loss = reducible error + irreducible error└── Bias-Variance Tradeoff ├── Bias: is the scope accurate (systematic error) ├── Variance: is the hand shaking (sensitivity to data) └── Optimal model = balance point between bias and variance