Machine learning seeks useful structure in data and predictors that remain accurate on new observations. We begin with dimensionality reduction and clustering, then develop regression and classification through empirical risk minimization, regularization, and kernel methods. Connections with inverse problems explain the role of model assumptions, while the final analysis of generalization balances approximation error against the statistical complexity of the chosen model class.
Imaging problems often concern the reconstruction or processing of an individual signal or image, whereas machine learning studies patterns across collections of observations. Their goals and performance measures differ, but both use tools such as linear models, regularization, and convex optimization.
In unsupervised learning, we observe n points (xi)i=1n.
The aim is to identify structure in these observations, for example to visualize them or group them into clusters.
We assume for simplicity that the observations lie in Euclidean space, xi∈Rp, where p is the number of features. We store the observations as the rows of a matrix X∈Rn×p.
Dimensionality reduction produces a compact representation of the data for visualization or subsequent analysis. By retaining informative features, it can also reduce computational cost and improve prediction.
Principal component analysis (PCA) projects the data orthogonally onto the principal axes of the covariance matrix.
Presentation of the method.
The empirical mean is defined as
m^:=n1i=1∑nxi∈Rp
and the empirical covariance as
C^:=n1i=1∑n(xi−m^)(xi−m^)∗∈Rp×p.(13.1)
With the centered data matrix X~:=X−1nm^∗, the covariance is C^=X~∗X~/n.
Suppose the points (xi)i are i.i.d. with a finite second moment, and let x denote a random variable with their common distribution. The law of large numbers gives the following almost sure limits as n→+∞:
m^→m:=E(x)andC^→C:=E((x−m)(x−m)∗).(13.2)
Let μ be the distribution on Rp of x. Then these limits can also be written as
m=∫Rpxdμ(x)andC=∫Rp(x−m)(x−m)∗dμ(x).
Figure 13.1. Empirical covariance of the Iris measurements and its eigenvalues.
Figure 13.2. Principal directions of variation.
The PCA basis consists of the right singular vectors of the centered data matrix. Proposition 9.1 gives the reduced singular value decomposition
X~=nUdiag(σ)V∗
where U∈Rn×r and V∈Rp×r have orthonormal columns, and r=rank(X~)⩽min(n,p).
Write V=(vk)k=1r for the orthonormal columns, which are eigenvectors of C^=Vdiag(σ2)V⊤, with vk∈Rp. These vectors describe the principal directions of variation in the point cloud (xi)i in Rp.
We order the singular values as σ1⩾…⩾σr, so the leading components account for the greatest variance.
Figure 13.1 displays an empirical covariance matrix and its spectrum (σk2)k for the Iris dataset (Iris flower data set) introduced by Fisher. It contains 50 samples from each of three iris species: Iris setosa, Iris virginica, and Iris versicolor. The four features are sepal length, sepal width, petal length, and petal width.
To obtain a PCA embedding xi∈Rp↦zi∈Rd of dimension d⩽p, project onto the first d right singular vectors, extending the basis if d>r:
zi:=(⟨xi−m^,vk⟩)k=1d∈Rd.(13.3)
The corresponding reconstruction is
x~i:=m^+k=1∑dzi,kvk∈Rp.(13.4)
Thus x~i=ProjT~(xi), where T~:=m^+Spank=1d(vk) is the affine reconstruction space.
Figure 13.3 shows an example of PCA for 2-D and 3-D visualization.
Figure 13.3. PCA projections of the data into two and three dimensions.
Optimality analysis.
Figure 13.4. Rows of the centered data matrix are observations; columns are features.
We prove that PCA minimizes the ℓ2 reconstruction error among linear dimensionality-reduction methods.
An optimal affine reconstruction space can be chosen to contain the empirical mean: for any fixed direction space, translating it to the mean cannot increase squared reconstruction error. After centering, we therefore assume m^=0, hence X=X~.
We recall that X=nUdiag(σ)V⊤ with observations in rows, and C^=X⊤X/n=Vdiag(σi2)V⊤. We assume 1⩽k⩽p and extend V to an orthogonal basis of Rp when necessary.
Figure 13.5. Linear compression followed by reconstruction.
For the centered data, compare linear compression maps into dimension k followed by reconstruction:
Although f(⋅,S) and f(R,⋅) are convex separately, f is not jointly convex. Alternating minimization in R and S therefore need not reach a global minimizer.
Nevertheless, a global minimizer has a simple explicit form.
The compressor S⊤ and decompressor R=S give precisely the PCA maps in (13.3) and (13.4).
We first prove that one can restrict attention to orthogonal projection matrices.
The next lemma bounds the objective by a linear program. We then show that PCA attains this bound, proving optimality.
Clustering assigns a label yi∈{1,…,k} to each observation xi. Observations with the same label form a cluster.
k-means
One approach is to seek compact clusters by minimizing a measure of within-cluster dispersion. In Euclidean space, the k-means objective measures distances from observations to their centroids c=(cℓ)ℓ=1k, with cℓ∈Rp. Related formulations are possible in general metric spaces, although the centroid computations may be more difficult. The optimization problem is
(y,c)minE(y,c):=ℓ=1∑ki:yi=ℓ∑∣∣xi−cℓ∣∣2.
Figure 13.7.k-means clusters according to Voronoi cells.
The k-means algorithm alternates between updating the labels and updating the centroids, a form of block coordinate minimization.
Initialize the centroids c, for example by choosing well-separated observations. We discuss a more systematic initialization below.
For fixed centroids c, minimize y↦E(y,c) by assigning each observation to its nearest centroid:
∀i∈{1,…,n},yi←1⩽ℓ⩽kargmin∣∣xi−cℓ∣∣.(13.7)
For fixed labels y, minimize c↦E(y,c) by setting each centroid to the mean of its cluster:
∀ℓ∈{1,…,k},cℓ←∣{i;yi=ℓ}∣∑i:yi=ℓxi(13.8)
If a cluster becomes empty, its centroid does not contribute to the objective for the current labels. One may leave it in place or reseed it at a data point before the next assignment step. The centroid formula applies only to nonempty clusters.
Each step decreases or preserves E. With a fixed tie-breaking rule that retains existing assignments at ties, and without indefinite reseeding, a changed assignment strictly decreases the objective. There are finitely many label assignments, so the algorithm terminates after finitely many such changes.
Because the objective is nonconvex, k-means need not find globally optimal clusters.
A reseeding heuristic moves centroids cℓ from redundant or low-contribution clusters to regions with high distortion. This can help the iterations escape a poor local configuration.
Figure 13.8 shows an example of k-means iterations on the Iris dataset.
Figure 13.8. Left: iterations of the k-means algorithm. Right: class histograms after the k-means optimization.
k-means++
The result of k-means depends strongly on initialization. Well-separated initial centers tend to cover the data more effectively than tightly grouped centers.
The randomized k-means++ initialization has an approximation guarantee even before Lloyd iterations are applied. In practice, Lloyd iterations usually improve the resulting centers. First choose c1 uniformly among the sample points. After choosing c1,…,cℓ, select cℓ+1 from the sample according to a probability π(ℓ) on {1,…,n} proportional to the squared distance from the nearest selected center
Points far from the previously seeded centers are more likely to be chosen. If every di=0, the current centers already achieve zero distortion and the procedure can stop.
The following theorem, due to David Arthur and Sergei Vassilvitskii, bounds the expected seeding cost by a logarithmic factor times the optimal cost. Computing a global optimum is NP-hard in general.
Lloyd algorithm and continuous densities.
The k-means iterations are also known as Lloyd’s algorithm and are used in vector quantization for compression. The same alternating procedure applies to a probability measure μ on Rp with finite second moment.
The energy to minimize becomes
(V,c)minℓ=1∑k∫Vℓ∣∣x−cℓ∣∣2dμ(x)
where (Vℓ)ℓ is a partition of the domain.
Step (13.7) is replaced by the computation of a Voronoi cell
∀ℓ∈{1,…,k},Vℓ:={x;∀ℓ′=ℓ,∣∣x−cℓ∣∣⩽∣∣x−cℓ′∣∣}.
For distinct centroids, the Voronoi cells are polyhedra bounded by perpendicular bisectors. Resolve distance ties consistently to obtain a partition; this matters if μ assigns positive mass to a boundary. In low dimensions, computational geometry provides efficient algorithms for constructing the cells.
The centroid update applies to cells of positive μ-mass; zero-mass cells require a separate convention, as in the discrete algorithm. For a uniform planar density, hexagonal Voronoi patterns are characteristic of high-resolution quantization away from the boundary. They need not be exact finite-k minimizers on a bounded domain.
Figure 13.9 displays two examples of Lloyd iterations on 2-D densities on a square domain.
Figure 13.9. Continuous k-means (Lloyd) iterations 0,2,3,5,30. The top row uses a uniform density; the bottom row uses the nonuniform density shown in grayscale.
We first describe empirical risk minimization, a framework shared by regression and classification. For classification, predictions may represent class probabilities rather than labels.
To make fitting yi≈f(xi) computationally tractable and obtain useful predictions, we restrict the admissible functions to a class of controlled complexity. The class may become richer as the sample size n grows, but its complexity must remain compatible with the available data.
The desired consistency property is f^n→fˉ as n→+∞. One way to express this is through expected prediction error over the training samples (xi,yi)i:
En:=E(L~(f^n(x),fˉ(x)))⟶0.
Here the expectation includes both the test input x, drawn from the marginal πX, and the n i.i.d. training pairs (xi,yi)∼π that determine f^n.
The comparison loss L~ measures discrepancies between predictions in Y; for example, we may take L~=L. One can also study convergence in probability, i.e.
∀ε>0,Eε,n:=P(L~(f^n(x),fˉ(x))>ε)→0.
These properties define consistency in expectation and in probability, respectively.
A convergence rate gives an explicit upper bound on the decay of En or Eε,n.
For L~(y,y′)=∣y−y′∣r, convergence in expectation implies convergence in probability by Markov’s inequality:
Instead of specifying Fn through a hard constraint, we can favor simple or regular functions through a penalty.
A typical way to achieve this is by using a parametric model y≈f(x,β) where β∈B parametrizes the function f(⋅,β):X→Y. The empirical risk minimization procedure (13.9) now becomes
where J is a regularizer. For example, J=∣∣⋅∣∣22 controls parameter magnitude, while J=∣∣⋅∣∣1 promotes sparse coefficients and, in a linear feature model, feature selection. Here λn>0 is a regularization parameter, and its asymptotic scaling must balance approximation and estimation; consistency often requires λn→0 at a controlled rate.
The population counterpart of (13.10) defines the parameter βˉ. A limiting estimator as n→+∞ then takes the form fˉ=f(⋅,βˉ), with βˉ satisfying
We may also ask how accurately β^ estimates βˉ, as measured by the parameter error ∣∣β^−βˉ∣∣ for a chosen norm ∣∣⋅∣∣. Parameter estimation is generally more demanding than prediction: different parameters can produce similar predictions, especially when the model is poorly identified.
13.2.4 Validation, Test Sets, and Cross-validation¶
The errors En and Eε,n cannot be evaluated directly because the population optimum fˉ is unknown.
To tune a parameter such as the regularization strength λ, we estimate the prediction risk E(L(f^(x),y)) on data held out from training.
Use a second sample (xˉj,yˉj)j=1nˉ, called a validation set. In the statistical model, these observations are i.i.d. with distribution π and independent of the training sample. The validation risk is
Rnˉ=nˉ1j=1∑nˉL(f^(xˉj),yˉj)(13.13)
which converges to E(L(f^(x),y)) for large nˉ.
Minimizing Rnˉ over hyperparameters (such as λn) is holdout validation. Cross-validation repeats training and validation across folds. A separate test set, untouched by hyperparameter selection, estimates the performance of the final selected procedure.
In supervised learning, the training data consist of pairs (xi,yi)∈X×Y, with X=Rp here for simplicity. We seek a function f:X→Y that captures the relationship yi≈f(xi) and predicts an output f(x) for a new input x.
When Y is finite and discrete, the task is supervised classification, studied in Section 13.4. Binary classification uses Y={0,1}; for example, in a medical application, yi=0 may indicate a healthy subject and yi=1 a subject with the condition of interest.
When Y is continuous, typically Y=R, the task is regression.
For regression, we specialize empirical risk minimization to Y=R with the quadratic loss L(y,y′)=21∣y−y′∣2.
Nonlinear regression can be formulated using a dictionary of features, such as polynomials. This lifts the data into a higher-dimensional space and leads to the kernel methods of Section 13.5.
Least squares and conditional expectation.
If f ranges over measurable functions and E(y2)<∞, a population minimizer fˉ in (13.10) is the conditional mean of the response given the input. It is defined up to equality almost everywhere under the input distribution.
Suppose for simplicity that π has density dxdydπ with respect to a product measure dxdy, such as Lebesgue measure. Then
where (x,y) has law π and the formula applies where the denominator is positive.
Figure 13.11. Conditional expectation.
If X and Y are discrete, let πx,y denote the probability of (x=x,y=y). Then
∀x∈X,fˉ(x)=∑yπx,y∑yyπx,y
with no prescribed value when the marginal of π on X vanishes at x.
Replacing π by the empirical distribution averages responses at each observed input but leaves predictions unspecified elsewhere. Generalization therefore requires assumptions on regularity or model complexity.
Penalized linear models.
Figure 13.12. Linear regression.
A linear model constrains f to have the form f(x,β)=⟨x,β⟩ with parameters β∈B=Rp. Affine predictors are included through the identity ⟨x,β⟩+β0=⟨(x,1),(β,β0)⟩, by appending a constant coordinate to x to form (x,1). We therefore use the linear notation below.
Under the square loss, the regularized ERM (13.11) is conveniently rewritten as
β^∈β∈Bargmin21⟨C^β,β⟩−⟨u^,β⟩+λnJ(β)(13.14)
where we introduced the empirical second-moment matrix (equal to the covariance (13.1) for centered data) and cross-moment vector
As n→+∞, suitable moment assumptions on π give the following almost sure limits by the law of large numbers:
C^→C:=E(xx∗)andu^→u:=E(yx).(13.15)
For appropriately chosen λn→0, the estimator can converge as n→+∞ to the population parameter
βˉ∈βargmin{J(β);Cβ=u}.
Problem (13.14) is equivalent to the regularized resolution of inverse problems (9.9), with X/n in place of Φ and y/n as the observation vector.
Random design introduces sampling error into the operator as well: C^ estimates C. The typical scale is 1/n, in the sense that
E(∣∣C^−C∣∣)=O(n−1/2)andE(∣∣u^−u∣∣)=O(n−1/2),
assuming E(y4)<+∞ and E(∣∣x∣∣4)<+∞, which give finite second moments for xx∗ and xy. Using a linear predictor does not require a correctly specified model y=⟨x,β⟩+w with noise w independent of x. The aim is to estimate the best linear predictor βˉ.
Extensions of Theorems 9.4, 11.9, and 11.11 can account for covariance-estimation error and yield prediction bounds of the form
E(∣⟨β^,x⟩−⟨βˉ,x⟩∣2)=O(n−κ)
and estimation rates of the form
E(∣∣β^−βˉ∣∣2)=O(n−κ′),
under suitable source conditions involving C and u.
Since the noise level is roughly n−21, the ideal cases are when κ=κ′=1, which is the so-called linear rate regime.
Support-recovery guarantees can also be derived by extending Theorem 11.15. We now focus on quadratic regularization, a standard regression method. Sparse penalties such as ℓ1 are useful when feature selection or a sparse model is appropriate; their statistical benefit depends on the data and assumptions.
In imaging inverse problems, sparse regularization expresses prior structure of the object being reconstructed.
Ridge regression (quadratic penalization).
For J=∣∣⋅∣∣2/2, the estimator (13.14) is obtained in closed form as
β^=(X∗X+nλnIdp)−1X∗y=(C^+λnIdp)−1u^.(13.16)
This is often called ridge regression in the literature.
The Woodbury identity gives the equivalent expression
β^=X∗(XX∗+nλnIdn)−1y.(13.17)
When n≫p, formula (13.16) requires solving the smaller, p×p system. When p≫n, formula (13.17) uses an n×n system and is preferable; it also extends to infinite-dimensional feature spaces.
Convergence to the minimum-norm population solution βˉ=C+u requires control of both the regularization bias and sampling error. The condition λn→0 alone is insufficient when small eigenvalues amplify noise. Here is one elementary bound that also applies in a Hilbert feature space.
In finite dimensions, a source representation exists for every βˉ∈Im(C), but its radius ρ depends on the spectrum and on the target. In infinite dimensions, it is an additional regularity assumption. The bound displays no explicit feature dimension, although κ, B, and ρ may depend on it. Standard ridge regularization has bias saturation beyond source exponent γ=1; stronger source assumptions alone do not justify extending this estimate to γ=2.
The R-nearest-neighbor method (R-NN) classifies an input using the labels of its R nearest training observations. Increasing R reduces sensitivity to individual noisy labels, but excessive smoothing can obscure class boundaries. For consistency, a standard asymptotic choice has R=Rn→∞ and Rn/n→0.
Nearest-neighbor classification is a useful baseline, especially when the feature dimension p is small.
The prediction f^(x)∈Y is the most frequent label among those R observations, with a fixed rule for breaking ties. The method is nonparametric: its representation depends on the training sample rather than on a fixed-dimensional parameter vector.
Figure 13.13. Nearest neighbors.
First compute the Euclidean distance from the query x to each training observation xi.
Sorting the distances generates an indexing σ (a permutation of {1,…,n}) such that
∣∣x−xσ(1)∣∣⩽∣∣x−xσ(2)∣∣⩽…⩽∣∣x−xσ(n)∣∣.
For a given R, one can compute the “local” histogram of classes around x
hℓ(x):=R1#{i∈{1,…,R}:yσ(i)=ℓ}.
The predicted class at x is an index attaining the largest histogram value:
f^(x)∈ℓargmaxhℓ(x).
Choose R by validation or cross-validation. For classification, the validation risk (13.13) typically uses the 0–1 loss, giving the fraction of misclassified observations
Rnˉ:=nˉ1j=1∑nˉδ(yˉj−f^(xˉj))
where δ(0)=0 and δ(s)=1 if s=0.
The method also applies to features in a general metric space in place of Rp.
Fast nearest-neighbor search can avoid explicitly sorting every distance.
Figure 13.14. Classification boundaries produced by R-nearest neighbors.
Figure 13.14 shows the predicted class regions {x;f^(x)=ℓ}, for ℓ=1,…,k, in a two-dimensional projection of the Iris dataset.
Logistic classification is a widely used baseline for binary and multiclass prediction. It outputs a probability for each class, providing a richer prediction than a class label alone. The accuracy of these probabilities must still be assessed on held-out data.
The standard name for this model is logistic regression, even when the prediction task is classification.
Support vector machines provide another common approach. Their hinge loss is nonsmooth, and their scores are not probabilities without an additional calibration step. The choice between these methods depends on the task and evaluation criterion.
For the binary formulas below, use labels yi∈Y={−1,1}. In logistic classification, the prediction f(⋅,β)∈[0,1] is a probability for the positive class rather than a class label. We retain the notation f for this probability predictor.
Approximate risk minimization.
A linear score ⟨x,β⟩ defines the classifier sign(⟨x,β⟩), with either class assigned when the score is zero. The empirical 0–1 objective counts classification errors, leading to the minimization problem
βmini=1∑nℓ0(−yi⟨xi,β⟩)(13.20)
where ℓ0=1[0,+∞) counts zero margins as errors. Away from ties, misclassification corresponds to ⟨xi,β⟩ and yi having different signs, so that in this case ℓ0(−yi⟨xi,β⟩)=1 (and 0 otherwise for correct classification).
The loss ℓ0 is nonconvex, and solving (13.20) globally is NP-hard in general. Convex upper bounds on ℓ0 provide tractable surrogate objectives.
Two common surrogates are
ℓ(u)=(1+u)+andℓ(u)=log(1+exp(u))/log(2)
These are, respectively, the nonsmooth hinge loss used in support vector machines and the smooth logistic loss. The 1/log(2) is just a constant which makes ℓ0⩽ℓ.
AdaBoost uses the exponential loss ℓ(u)=eu.
Least squares uses ℓ(u)=(1+u)2. Its growth for large negative margins makes it a poor pointwise approximation of ℓ0, although it can still give useful classifiers.
Unregularized hinge-loss minimization is equivalent to a linear program with nonnegative slack variables:
u⩾0,βmin{i∑ui;yi⟨xi,β⟩⩾1−ui for all i}.
Logistic loss probabilistic interpretation.
Logistic regression applies a sigmoid to the linear score from Section 13.3.1. The resulting probability predictor is nonlinear. The predicted probability of class +1 is
Despite its simplicity, a linear classifier can be effective when the feature dimension p is large.
With s=⟨x,β⟩, the predicted probability of class -1 is 1−f(x,β)=θ(−s). The identity θ(−s)=1−θ(s) makes the two probabilities sum to one. It does not require balanced class frequencies; an intercept can account for unequal prior frequencies.
For a nonzero parameter, β/∣∣β∣∣ determines the normal direction of the separating hyperplane, while 1/∣∣β∣∣ controls the width of the probability transition. As ∣∣β∣∣→+∞ along a fixed direction, the transition approaches a sharp decision boundary.
Figure 13.15. Logistic classification in one and two dimensions, showing how ∣∣β∣∣ controls the width of the probability transition.
The predictor f(x,β) is also a single-layer perceptron with a logistic (sigmoid) activation; see Chapter 17.
For conditionally independent labels yi∈{−1,+1}, write yˉi=(yi+1)/2∈{0,1}, si=⟨xi,β⟩, and pi=θ(si). The likelihood is
Problem (13.22) is a smooth convex minimization. If X has full column rank, E is strictly convex, so it has at most one minimizer. A finite minimizer need not exist for separable data. A positive quadratic penalty guarantees existence and uniqueness.
Figure 13.16. Classification losses as functions of the negative margin s=−y⟨x,β⟩, with zero margin counted as an error. The unscaled logistic loss need not upper-bound the 0–1 loss; division by log2 gives the upper-bound normalization used above.
Figure 13.16 compares the 0–1, logistic, and hinge losses.
Gradient descent method.
Write the objective as
E(β)=L(Xβ,y)whereL(s,y)=n1i∑L(si,yi),
Its gradient is
∇E(β)=X∗∇L(Xβ,y)where∇L(s,y)=−ny⊙θ(−y⊙s),
where ⊙ is the pointwise multiplication operator, i.e. .* in Matlab.
Once β(ℓ=0)∈Rp is initialized (for instance at 0p), one step of gradient descent (14.13) reads
β(ℓ+1)=β(ℓ)−τℓ∇E(β(ℓ)).
Figure 13.17. Effect of class separation on predicted classification probabilities.
Figure 13.17 illustrates the method on samples from a Gaussian mixture, whose overlap is controlled by an offset ω.
Overlaying the data on the probability map highlights the separating hyperplane {x;⟨β,x⟩=0}.
For multiclass logistic classification, introduce one weight vector for each of the k classes. Collect the vectors β=(βℓ)ℓ=1k as columns of β∈Rp×k.
For an input x∈Rp, convert the class scores into probabilities using the softmax model:
f(x,β)=(∑me⟨x,βm⟩e⟨x,βℓ⟩)ℓ(13.24)
The vector f(x,β)∈[0,1]k gives the probabilities that x belongs to each class, and satisfies ∑ℓf(x,β)ℓ=1.
Estimate β by maximizing the log-likelihood over the training sample:
β∈Rp×kmaxn1i=1∑nlog(f(xi,β)yi)
where yi∈Y={1,…,k} is the label of observation xi.
This is conveniently rewritten as
β∈Rp×kminE(β):=n1(i∑LSE(Xβ)i−⟨Xβ,D⟩)
where D∈{0,1}n×k is the one-hot class matrix
Di,ℓ={1ifyi=ℓ,0otherwise.
and LSE is the log-sum-exp operator
LSE(S)i=log(ℓ∑exp(Si,ℓ)),LSE(S)∈Rn.
For k=2, identify the first class with label +1 and the second with label -1. The model then agrees with binary logistic classification in Section 13.4.2, with parameter β1−β2. A single weight vector therefore suffices in that case.
Direct evaluation of log-sum-exp can overflow when Si,ℓ is large. A stable evaluation subtracts the largest entry in each row before exponentiation, using the identity
LSE(S+a)=LSE(S)+a
for a rowwise constant a. This shift is especially useful for well-separated classes, whose parameter vectors βℓ may grow large.
The gradient of the sum of the rowwise log-sum-exp values is the softmax operator
∇Si∑LSE(S)i=SM(S):=(∑meSi,meSi,ℓ)
As with log-sum-exp, subtract the largest entry in each row before evaluating the exponentials.
Figure 13.18. Digit images and their two- and three-dimensional PCA projections.
Once the matrix D is computed, the gradient of E is computed as
∇E(β)=n1X∗(SM(Xβ)−D).
The objective E can then be minimized by gradient descent.
To illustrate the method, we use a dataset of n images of size p=8×8, representing digits from 0 to 9 (so there are k=10 classes).
Figure 13.18 displays a few representative examples as well as 2-D and 3-D PCA projections.
Figure 13.19 visualizes the fitted class probabilities f(x,β^) by assigning colors on a regular image grid.
Figure 13.19. Digit classification. Left: the first nine class probabilities on an affine two-dimensional PCA slice through the training mean. Right: the mixture of all ten class colors, with projected observations overlaid.
Linear models may fail to capture the geometry needed for a regression or classification task. Moreover, inputs such as strings and graphs need not belong to a vector space.
Kernel methods introduce a feature map into a richer space and apply linear prediction there. This produces nonlinear regression and classification rules while retaining linear-system solvers and convex optimization. The kernel trick expresses the computations through similarities between the n observations, without constructing the feature vectors explicitly. Such methods are nonparametric when the number of fitted coefficients grows with n, allowing the model to become more expressive as data accumulate.
Algorithms that use the observations xi only through inner products can often be kernelized. Examples include linear regression, nearest-neighbor methods, SVMs, logistic classification, and PCA. We introduce the construction through ridge regression and then extend it to other losses and distance-based methods.
Let φ:X→H be a feature map into a real Hilbert space H, which may be infinite dimensional.
The input space X need not be a vector space. When X=Rp, the choice φ(x)=x recovers ordinary linear methods.
For regression, we consider predictions which are linear functions over this lifted space, i.e. of the form x↦⟨φ(x),β⟩H for some weight vector β∈H. For binary classification, one uses x↦sign(⟨φ(x),β⟩H).
For scalar inputs (p=1), the feature map φ(x)=(1,x,x2,…,xk)∈Rk+1 gives polynomial regression. Multivariate monomials extend this construction to higher-dimensional inputs.
Let Φ=(φ(xi)∗)i=1n be the feature matrix, whose rows are φ(xi). For H=Rpˉ, it is an ordinary matrix Φ∈Rn×pˉ. In an infinite-dimensional feature space, the same notation represents a linear operator.
For λ>0, consider the regularized empirical-risk problem
Start with regression under the squared loss ℓ(y,z)=21(y−z)2:
β⋆=β∈Hargmin∣∣Φβ−y∣∣Rn2+λ∣∣β∣∣H2.
which is the ridge regression problem studied in Section 13.3.1.
Setting the gradient to zero gives
β⋆=(Φ∗Φ+λIdH)−1Φ∗y.
Direct computation may be impractical or impossible when H is infinite dimensional. The following Woodbury identity converts the problem into a finite system.
This is the feature-space counterpart of (13.17), with Φ replacing X and λ replacing nλn.
The coefficients c⋆∈Rn depend on the inputs only through κ, without explicit computation of φ(x). If κ is inexpensive to evaluate, forming K takes O(n2) kernel evaluations. A dense direct solve costs O(n3) operations; an iterative solve costs O(n2) per matrix-vector product, with the iteration count determined by conditioning and accuracy.
The fitted predictor at a new input x∈X also uses only kernel evaluations:
One can also start directly from a kernel κ(x,x′) rather than an explicit feature map φ. This is often convenient because kernels can be designed through their geometric properties and combined, for example by addition. The required condition is that every Gram matrix (κ(xi,xj))i,j be symmetric positive semidefinite. Such kernels are commonly called positive definite kernels; the condition is equivalent to the existence of a Hilbert-space feature map generating the kernel.
The underlying input space need not be Euclidean.
When using the linear kernel κ(x,y)=⟨x,y⟩, one retrieves the linear models studied in the previous section, and the lifting is trivial φ(x)=x.
A family of popular kernels are polynomial ones, κ(x,x′)=(⟨x,x′⟩+c)a for a∈N∗ and c>0, which corresponds to a lifting in finite dimension. For instance, for a=2 and p=2, one has a lifting in dimension 6
A widely used choice on Euclidean spaces is the Gaussian kernel
κ(x,y):=e−2σ2∣∣x−y∣∣2.(13.27)
The bandwidth σ>0 controls the locality of the model and is typically tuned by cross-validation. The Gaussian kernel has the infinite-dimensional feature map φ(x)(t)=(2/(πσ2))p/4exp(−∣∣x−t∣∣2/σ2)∈L2(Rp).
Another related popular kernel is the Laplacian kernel exp(−∣∣x−y∣∣/σ).
More generally, Bochner’s theorem states that a continuous translation-invariant kernel κ(x,x′)=k(x−x′) on Rp is positive definite if and only if k is the Fourier transform of a finite nonnegative measure. If this measure has an integrable density, a feature map can be built from the square root of that density. When k is integrable and its Fourier transform is an integrable function, the condition is k^⩾0; strict positivity is not necessary.
Figure 13.20 shows an example of regression using a Gaussian kernel.
Figure 13.20. Regression using a Gaussian kernel.
Kernel on non-Euclidean spaces.
On a general input space X, a real kernel κ must produce a symmetric positive semidefinite Gram matrix K=(κ(xi,xj))i,j for every finite collection of inputs. Equivalently, there is a Hilbert space H and a feature map φ:X→H such that κ(x,x′)=⟨φ(x),φ(x′)⟩H.
For instance, if X=P(M) is the set of measurable sets of finite measure in a measure space (M,μ), one can define κ(A,B)=μ(A∩B) which corresponds to the lifting φ(A)=1A so that ⟨φ(A),φ(B)⟩=∫1A(x)1B(x)dμ(x)=μ(A∩B).
Kernels can also be defined on strings and graphs, although their construction is more involved.
When κ(x,x)>0 for every input under consideration, the kernel can be normalized to have a unit diagonal. For a translation-invariant kernel on Rp, the diagonal equals the constant k(0), so normalization only requires division by k(0)>0. This corresponds to replacing φ(x) by φ(x)/∣∣φ(x)∣∣H and thus replacing κ(x,x′) by κ(x,x)κ(x′,x′)κ(x,x′).
The least-squares result extends to other losses under the assumptions below. With a squared Hilbert-space norm penalty, the minimizer belongs to a subspace generated by the data, of dimension at most n. This representer theorem reduces the problem to finitely many coefficients even when the feature space H is infinite dimensional.
Equation (13.29) places the minimizer in a subspace of dimension at most n, spanned by the observed feature vectors φ(xi).
The potentially infinite-dimensional problem (13.28) becomes the finite-dimensional problem (13.30). A dense first-order iteration costs O(n2) once the kernel matrix is available. A low-rank approximation K≈Φ~∗Φ~ can reduce this cost further by introducing a smaller approximate feature space.
For classification applications, one can use for ℓ a hinge or a logistic loss function, and then the decision boundary is computed following (13.26) using kernel evaluations only as
sign(⟨β⋆,φ(x)⟩H)=sign(i∑ci⋆κ(x,xi)).
Figure 13.21 illustrates a nonlinear decision boundary in two dimensions. The decision rule is linear in the feature space H; evaluating it through the nonlinear feature map produces a curved boundary in the input space.
Figure 13.21. Nonlinear classification using a Gaussian kernel.
Nearest-neighbor classification (Section 13.4.1) and regression can likewise use distances in feature space, computed entirely from the kernel:
This section introduces Probably Approximately Correct (PAC) learning, which studies generalization guarantees under explicit complexity and sampling assumptions. Distribution-free bounds avoid further restrictions on the data distribution. The main reference (and in particular the proofs of the mentioned results) for this section is the book “Foundations of Machine Learning” by Mehryar Mohri, Afshin Rostamizadeh, and Ameet Talwalkar https://cs.nyu.edu/~mohri/mlbook/.
Assume the observations D:=(xi,yi)i=1n are independent and identically distributed copies of a random pair (X,Y) taking values in X×Y. From this sample, we seek a predictor f:X→Y with risk close to the smallest achievable value:
L(f):=E(ℓ(Y,f(X)))=∫X×Yℓ(y,f(x))dPX,Y(x,y)
where ℓ:Y×Y→R is some loss function.
To estimate this minimizer, we select a class of functions F and minimize the empirical risk
f^∈f∈FargminL^(f):=n1i=1∑nℓ(yi,f(xi)).
We assume a measurable minimizer exists. It is random because it depends on the sample D.
PAC learning seeks a bound on the excess risk L(f^)−inf(L)⩾0 that holds with probability at least 1−δ. The bound depends on the sample size n and confidence parameter δ. For the excess risk to vanish, the approximation class must become sufficiently rich while its statistical complexity remains controlled. Quantitative approximation rates require distributional assumptions, although some consistency results hold without them.
Consequently, f⋆ can be chosen separately at each input x by solving
f⋆(x)=zargminα(z∣x).
Calibration in the classification setup
We would like the classifier sign(f⋆) to agree with a Bayes classifier for the 0–1 loss, namely sign(2η−1) away from ties. This property is called classification calibration. It does not require the scores f⋆ and 2η−1 themselves to agree. The following result characterizes calibration for finite convex margin losses.
Both hinge and logistic loss satisfy this calibration criterion.
Let LΓ be the risk for ℓ(y,z)=Γ(−yz) and let L0–1 be classification risk, with a fixed tie-breaking convention. Quantitative calibration bounds have the form
0⩽L0–1(signf)−infL0–1⩽Ψ(LΓ(f)−infLΓ)(13.31)
for some increasing function Ψ:R+→R+ satisfying Ψ(0)=0. Such a control ensures in particular that if f⋆ minimizes LΓ, its induced classifier has Bayes-optimal 0–1 risk. At η=1/2, either class is optimal; away from ties, its sign agrees almost surely with that of 2η−1.
For hinge loss, the calibration bound holds with Ψ(r)=r. For logistic loss, it holds with Ψ(s)=2s.
This separates the effects of sampling and model approximation.
Enlarging a nested class F reduces approximation error but typically increases the estimation-error bound. Choose the class size as a function of n to balance these effects and avoid overfitting.
Approximation error.
A quantitative approximation bound requires assumptions on f⋆. No-free-lunch results rule out a uniform distribution-free approximation rate over all measurable targets.
The following example illustrates such a bound.
Estimation error.
Concentration inequalities control sampling fluctuations, while a bound on the complexity of F makes this control uniform over the model class.
The estimation error is controlled by uniform deviations between L and L^. Let g∈F attain infFL, assuming for simplicity that such a minimizer exists. Then
The preceding decomposition gives the sharper bound L(f^)−infFL⩽Δ++Δ−. Assume all suprema below are measurable (or use outer expectations).
To bound EDΔ±(D), we need to control the complexity of F. VC dimension gives one approach, but for norm-constrained linear models it can yield loose bounds that depend on the ambient dimension. Rademacher complexity gives a finer measure for a class G of functions from X×Y to R:
Rn(G):=Eε,D[g∈Gsupn1i=1∑nεig(xi,yi)]
where εi, independent of the data, are independent Rademacher random variables (i.e. P(εi=±1)=1/2). The quantity Rn(G) depends on the distribution of (X,Y).
Apply this complexity measure to the loss class G=ℓ[F], defined by