GNGiseldo Neo and Alana NeoBooks
Mathematical Foundations for Machine Learning6 / 8

Linear Transformations

Linear models combine features with a weighted sum. simplicity favors interpretation and optimization, but a frontier linear in original space does not represent all patterns. XOR and a class surrounded by another are immediate examples.

We can expand the function class without abandoning linear algorithms transforming the representation of each input:

ϕ:X⟶Z,x⟼ϕ(x). \phi:X\longrightarrow Z, \qquad x\longmapsto\phi(x).

The model starts to calculate

hw(x)=h0 ⁣(wTϕ(x)),(5.1) h_w(x)=h_0\!\left(w^{\mathsf T}\phi(x)\right), \tag{5.1}

where h0h_0 can be the signal, identity or sigmoid. linear in transformed features and ww parameters , although it is nonlinear in relation to the original entry.

The name of the chapter

In this context, “linearization” means representing a non-relationship linear by a linear model in new features. ϕ\phi map does not needs to be a linear transformation in the strict sense of algebra linear; polynomial maps, for example, are nonlinear.

5.1 Feature transformation Overview

5.1.1 Radial example

Consider points in the plane labeled by the distance to the source:

y={+1,x12+x22<r2,−1,x12+x22>r2. y= \begin{cases} +1,&x_1^2+x_2^2<r^2,\\ -1,&x_1^2+x_2^2>r^2. \end{cases}

No line separates the internal from the external. However, with

ϕ(x1,x2)=x12+x22, \phi(x_1,x_2)=x_1^2+x_2^2,

the problem becomes one-dimensional: just compare ϕ(x)\phi(x) with the threshold r2r^2.

A circular boundary in the original space becomes a linear threshold after radial transformation.

Figure 5.1. A circular boundary in the original space becomes a linear threshold after radial transformation.

We don’t need to reverse ϕ\phi after training. new example xx, we calculate ϕ(x)\phi(x) and apply the learned model. output continues to refer to the original example.

5.1.2 Sample transformation

Stop

D={(x1,y1),…,(xN,yN)}, D=\{(x_1,y_1),\ldots,(x_N,y_N)\},

the processed sample is

ϕ(D)={(ϕ(x1),y1),…,(ϕ(xN),yN)}. \phi(D) =\{(\phi(x_1),y_1),\ldots,(\phi(x_N),y_N)\}.

Labels do not change. The linear algorithm receives ϕ(xn)\phi(x_n) as its features and choose

w∗∈arg min⁡w1N∑n=1Nℓ ⁣(h0(wTϕ(xn)),yn).(5.2) w^*\in\operatorname*{arg\,min}_{w} \frac1N\sum_{n=1}^{N} \ell\!\left( h_0(w^{\mathsf T}\phi(x_n)),y_n \right). \tag{5.2}

The final hypothesis in the original domain is the composition hw∗=h0∘(w∗Tϕ)h_{w^*}=h_0\circ(w^{*\mathsf T}\phi).

5.1.3 Polynomial example

For two entries, a complete quadratic map may be

ϕ(x1,x2)=(1,x1,x2,x12,x1x2,x22). \phi(x_1,x_2) =\left(1,x_1,x_2,x_1^2,x_1x_2,x_2^2\right).

A linear ϕ(x)\phi(x) score is

w0+w1x1+w2x2+w3x12+w4x1x2+w5x22, w_0+w_1x_1+w_2x_2+w_3x_1^2+w_4x_1x_2+w_5x_2^2,

a quadratic polynomial in the original space. Your level border can be ellipse, parable, hyperbole or a case degenerate.

5.1.4 What remains linear?

It is useful to distinguish three spaces:

SpaceSubject matterCan it be nonlinear?
original entryxxYes, the border can be curved
characteristicsϕ(x)\phi(x)map can be nonlinear
parameterswTϕ(x)w^{\mathsf T}\phi(x)is linear in ww

This last linearity allows to reuse Perceptron, least squares and logistic regression without changing its mathematical structure.

5.1.5 Transformation is part of the model

Training, validation, testing and production should use exactly the same map. If ϕ\phi depends on estimated parameters — means, deviations, categories, main components — these parameters should be learned only in the training and stored with the model.

import numpy as np


def mapa_quadratico(X):
    """Transforma uma matriz com duas colunas."""
    x1 = X[:, 0]
    x2 = X[:, 1]
    return np.column_stack([
        np.ones(len(X)),
        x1,
        x2,
        x1**2,
        x1 * x2,
        x2**2,
    ])

Applying different transformations between training and prediction is a mistake data contract, even when the dimensions coincide.

5.1.6 Capacity and cost

Transforming can facilitate adjustment, but increases class capacity. For dd features, the number of degree monomials up to qq is

(d+qq). \binom{d+q}{q}.

With d=100d=100 and q=2q=2, they are already (1022)=5 151\binom{102}{2}=5\,151 features including the constant term. This increases memory, time and risk of overfitting.

Regularization and validation become especially important. transformation that reduces the training error can worsen the error outside the sample.

5.1.7 Explicit and implicit transformations

There are two strategies:

  • Explicit**:** calculate and store ϕ(x)\phi(x);
  • Implicit**:** calculate only products ϕ(x)Tϕ(x′)\phi(x)^{\mathsf T}\phi(x') through a core (kernel).

The core device will be useful when the size of ZZ is very large or even infinite, as long as the algorithm depends on the data by Climbing products.

5.1.8 Limitations

  • Adequate transformation depends on the structure of the problem.
  • Many features can amplify noise and redundancy.
  • High-grade polynomials can extrapolate extremely.
  • A fixed map may not capture relevant invariances.
  • Interpreting transformed coefficients requires considering all the composition, not isolated weights.

Initial questions

  1. In what sense (5.1) is linear and in which Can sense be nonlinear?
  2. Why don’t we have to calculate ϕ−1\phi^{-1} to make predictions?
  3. How many degree monomials up to two are there for d=10d=10?
  4. Give an example of transformation that would depend on statistics from Training and could cause data leaks.
  5. Explain why improving the adjustment does not prove improvement of generalization.

5.2 Linearizing ellipses centered at the origin

Suppose positive examples occupy the inside of an ellipse focus on the origin and the negatives stay outside. original, the border is curved and cannot be represented by a single Linear perceptron in (x1,x2)(x_1,x_2) features.

An ellipse aligned to the axes, with semi-axis a,b>0a,b>0, satisfies

x12a2+x22b2=1.(5.3) \frac{x_1^2}{a^2}+\frac{x_2^2}{b^2}=1. \tag{5.3}

For a rr radius circle, we have a=b=ra=b=r and the equation is x12+x22=r2x_1^2+x_2^2=r^2. The square in the radius is indispensable.

5.2.1 From an ellipse to a line

Set

ϕ(x1,x2)=(z1,z2)=(x12,x22). \phi(x_1,x_2)=(z_1,z_2)=(x_1^2,x_2^2).

In the transformed space, (5.3) becomes

z1a2+z2b2=1, \frac{z_1}{a^2}+\frac{z_2}{b^2}=1,

which is the equation of a straight line. The “interior positive” classification can be written as

h(x)=sinal⁡+ ⁣(1−x12a2−x22b2).(5.4) h(x) =\operatorname{sinal}_{+}\!\left( 1-\frac{x_1^2}{a^2}-\frac{x_2^2}{b^2} \right). \tag{5.4}

In the homogeneous vector

ϕ~(x)=(1,x12,x22), \widetilde\phi(x)=(1,x_1^2,x_2^2),

the weights are

w=(1,−1a2,−1b2), w=\left(1,-\frac1{a^2},-\frac1{b^2}\right),

and (5.4) takes the linear form h(x)=sinal⁡+(wTϕ~(x))h(x)=\operatorname{sinal}_{+}(w^{\mathsf T}\widetilde\phi(x)).

The ellipse in the original space corresponds to a line in the space of the square coordinates.

Figure 5.2. The ellipse in the original space corresponds to a line in the space of the square coordinates.

The accessible transformed space satisfies z1,z2≥0z_1,z_2\geq0; we do not occupy All R2\mathbb R^2. That doesn’t stop the classifier, but remember that ϕ\phi may lose information: (x1,x2)(x_1,x_2) points , (−x1,x2)(-x_1,x_2) and other signal changes have the same image.

5.2.2 Learning the ellipse

In the previous example, aa and bb seemed to be known. we provide the (1,x12,x22)(1,x_1^2,x_2^2) features and let the algorithm estimate

g(z)=w0+w1z1+w2z2. g(z)=w_0+w_1z_1+w_2z_2.

When w0>0w_0>0 and w1,w2<0w_1,w_2<0, the g(z)=0g(z)=0 border corresponds to

x12−w0/w1+x22−w0/w2=1, \frac{x_1^2}{-w_0/w_1} +\frac{x_2^2}{-w_0/w_2}=1,

with

a=−w0w1,b=−w0w2. a=\sqrt{-\frac{w_0}{w_1}}, \qquad b=\sqrt{-\frac{w_0}{w_2}}.

A linear classifier does not automatically impose these signals. other values, the border can be empty, unlimited or classify the external as positive. Geometric interpretation must be done after the adjustment.

5.2.3 Rotated ellipses

An ellipse centered on origin and not necessarily aligned to the axes is described by

xTAx=1, x^{\mathsf T}Ax=1,

where AA is a defined positive symmetrical matrix.

xTAx=a11x12+2a12x1x2+a22x22. x^{\mathsf T}Ax =a_{11}x_1^2+2a_{12}x_1x_2+a_{22}x_2^2.

So we need the crossword word:

ϕ(x1,x2)=(1,x12,x1x2,x22). \phi(x_1,x_2) =\left(1,x_1^2,x_1x_2,x_2^2\right).

The x1x2x_1x_2 coefficient allows you to rotate the main axes of the ellipse. Without it, the class contains only ellipses aligned to the axes.

5.2.4 Off-center ellipses

An ellipse centered on c=(c1,c2)c=(c_1,c_2) satisfies

(x−c)TA(x−c)=1. (x-c)^{\mathsf T}A(x-c)=1.

As they expand, quadratic, linear and constant terms emerge. the complete quadratic map

ϕ(x1,x2)=(1,x1,x2,x12,x1x2,x22) \phi(x_1,x_2) =\left(1,x_1,x_2,x_1^2,x_1x_2,x_2^2\right)

the presence of these six features is not the same as the ensures that every frontier learned is an ellipse; coefficients can to produce parables, hyperboles or degenerate forms.

5.2.5 Equality of errors after composition

If gg is a hypothesis in transformed space and

h=g∘ϕ, h=g\circ\phi,

So, for every example, h(xn)=g(ϕ(xn))h(x_n)=g(\phi(x_n)). Using the same loss,

ED(h)=1N∑nℓ(h(xn),yn)=Eϕ(D)(g). E_D(h) =\frac1N\sum_n\ell(h(x_n),y_n) =E_{\phi(D)}(g).

There is no geometric “way and back”: equality simply stems from apply the composition to the same examples and labels.

5.2.6 Ability of the transformed class

If G\mathcal G is the class of linear separators in ZZ and ϕ\phi is fixed, the class in the original domain is

Hϕ={g∘ϕ:g∈G}. \mathcal H_\phi =\{g\circ\phi:g\in\mathcal G\}.

How patterns performed by Hϕ\mathcal H_\phi correspond to patterns of G\mathcal G on ϕ(x)\phi(x) images,

dVC(Hϕ)≤dVC(G). d_{\mathrm{VC}}(\mathcal H_\phi) \leq d_{\mathrm{VC}}(\mathcal G).

For ϕ(x)=(x12,x22)\phi(x)=(x_1^2,x_2^2) and related separators in two dimensions, dVC(G)=3d_{\mathrm{VC}}(\mathcal G)=3 therefore dVC(Hϕ)≤3d_{\mathrm{VC}}(\mathcal H_\phi)\leq3. Inequality can be strict because the images are restricted to the first quadrant and points different can coincide after mapping.

If we choose among many maps using the data, the effective class is the union of the associated classes. This is not forbidden, but its complexity The selection shall be accounted for and shall use appropriate validation.

5.2.7 Implementation

import numpy as np


def atributos_elipse(X, girada=False, transladada=False):
    X = np.asarray(X, dtype=float)
    x1, x2 = X[:, 0], X[:, 1]
    colunas = [np.ones(len(X))]

    if transladada:
        colunas.extend([x1, x2])

    colunas.append(x1**2)
    if girada:
        colunas.append(x1 * x2)
    colunas.append(x2**2)
    return np.column_stack(colunas)

The order of columns must be stored with the template. Change it in prediction preserves the dimension, but associates each weight with the wrong attribute.

Exercises

  1. Correct the classifier if the positive class is outside the ellipse.
  2. Derive aa and bb from (w0,w1,w2)(w_0,w_1,w_2) under the appropriate signals.
  3. Expand (x−c)TA(x−c)(x-c)^{\mathsf T}A(x-c) and identify the six coefficients.
  4. Show that x1x2x_1x_2 changes signal under reflection (x1,x2)↦(−x1,x2)(x_1,x_2)\mapsto(-x_1,x_2), unlike squares.
  5. Explain why to select the polynomial degree in the test set produces an optimistic assessment.

5.3 Generalization of Transformation

The example of ellipse illustrates a broader idea: we can build a new vector with functions of the original coordinates and then apply the this vector a linear algorithm. If x∈Rdx\in\mathbb R^d, a transformation of features has the form

ϕ:Rd⟶Rd′,x⟼ϕ(x). \phi:\mathbb R^d\longrightarrow\mathbb R^{d'}, \qquad x\longmapsto\phi(x).

The d′d' number does not need to be equal to dd. It may be smaller, as in dimensionality reduction, or greater, when we create interactions and nonlinear terms.

5.3.1 Polynomial transformation

A maximum degree polynomial transformation QQ brings together all monomials

x1α1x2α2⋯xdαdsuch thatαj∈N0 and ∑j=1dαj≤Q. x_1^{\alpha_1}x_2^{\alpha_2}\cdots x_d^{\alpha_d} \quad\text{such that}\quad \alpha_j\in\mathbb N_0 \quad\text{ and }\quad \sum_{j=1}^d\alpha_j\leq Q.

The vector α=(α1,…,αd)\alpha=(\alpha_1,\ldots,\alpha_d) is called multiindex and ∣α∣=∑jαj|\alpha|=\sum_j\alpha_j is the total degree of monomium. For d=2d=2 and Q=2Q=2, for example,

ϕ2(x1,x2)=(1,x1,x2,x12,x1x2,x22).(5.5) \phi_2(x_1,x_2) =\left(1,x_1,x_2,x_1^2,x_1x_2,x_2^2\right). \tag{5.5}

A linear function in this new vector produces

wTϕ2(x)=w0+w1x1+w2x2+w3x12+w4x1x2+w5x22, w^{\mathsf T}\phi_2(x) =w_0+w_1x_1+w_2x_2+w_3x_1^2+w_4x_1x_2+w_5x_2^2,

i.e., a quadratic polynomial in the original space. nonlinear in xx, but continues linear in ww parameters. distinction allows using linear regression, logistic regression or others linear algorithms after transformation.

5.3.2 How many features are created?

The number of degree monomials exactly qq in dd variable is

(d+q−1q). \binom{d+q-1}{q}.

Adding the degrees of 00 to QQ, we get

m(d,Q)=∑q=0Q(d+q−1q)=(d+QQ).(5.6) m(d,Q)=\sum_{q=0}^Q\binom{d+q-1}{q} =\binom{d+Q}{Q}. \tag{5.6}

This count includes the constant term if bias is treated separately, the dimension of the vector without the constant will be

d′=(d+QQ)−1. d'=\binom{d+Q}{Q}-1.

For two variables,

d′=(Q+2Q)−1=Q(Q+3)2. d'=\binom{Q+2}{Q}-1 =\frac{Q(Q+3)}2.

Thus, with d=2d=2, the Q=1,2,3,4Q=1,2,3,4 grades generate 3, 6, respectively. 10 and 15 coefficients when we count the constant term.

The increase in degree creates new interactions and quickly elevates the dimension of attribute space.

Figure 5.3. The increase in degree creates new interactions and quickly elevates the dimension of attribute space.

In larger dimensions, combinatorial growth is more severe. d=20d=20 and Q=3Q=3, (5.6) provides (233)=1771\binom{23}{3}=1771 coefficients. A design matrix with NN examples can therefore go from N×20N\times20 to N×1771N\times1771.

5.3.3 Expressivity, generalization and cost

By increasing QQ, the hypothesis class contains more flexible borders. As polynomial classes are nested, the smallest training error cannot increase: a Q+1Q+1 grade model can always assign zero weight to new terms. This does not mean that the error outside the sample always Slow down.

Three effects should be considered:

  1. Approximation: higher degrees may represent relationships than a simple model can’t capture.
  2. Estimation: plus parameters make adjustment more sensitive to particularities and the noise of the sample.
  3. Computing: store the processed matrix and calculate products, gradients or inverses begin to require more memory and time.

For Rd′\mathbb R^{d'}-related separators , the class VC dimension complete linear is d′+1d'+1. However, the composite class {g∘ϕ:g∈G}\{g\circ\phi:g\in\mathcal G\} may have smaller VC dimension, as the ϕ(x)\phi(x) vectors occupy only a structured part of space still, the growth of d′d' is a good warning for the risk of overfitting.

5.3.4 How to choose the degree

The QQ degree is a hyperparameter. An appropriate practice is:

  1. separate test data and do not use them in choice;
  2. compare candidate degrees by validation or cross-validation;
  3. adjust to the training set any necessary standardisation;
  4. apply exactly the same transformation in validation and testing;
  5. select the degree and the regularization together.

Standardization deserves attention. If xjx_j has large values, xjQx_j^Q can get numerically huge. In general, we standardize the original variables using training statistics and only then did we generate the Polynomial terms. Regularization L2L_2 or L1L_1 also helps to control coefficients and reduce variance.

Avoid data leakage

Mean, standard deviation, grade and regularisation force shall not be chosen with test set information. In a validation crossover, all transformation needs to be adjusted again within Each training partition.

5.3.5 Implementation without specialized libraries

The following example builds (5.5) for a matrix with two columns:

import numpy as np


def atributos_quadraticos_2d(X):
    X = np.asarray(X, dtype=float)
    if X.ndim != 2 or X.shape[1] != 2:
        raise ValueError("X deve ter formato (n_amostras, 2)")

    x1, x2 = X[:, 0], X[:, 1]
    return np.column_stack([
        np.ones(len(X)),
        x1,
        x2,
        x1**2,
        x1 * x2,
        x2**2,
    ])

In actual applications, a * pipeline* shall store the order of the columns and normalization parameters. Generate the same features in order different during prediction produces incorrect results without necessarily cause dimension error.

Exercises

  1. List all maximum grade 33 monomials in two variables.
  2. Calculate m(5,2)m(5,2) and interpret the difference between counting or not constant term.
  3. Show why the minimum training error does not increase when a It passes from grade QQ to grade Q+1Q+1.
  4. For x=(2,−3)x=(2,-3), manually calculate ϕ2(x)\phi_2(x) in the order used in (5.5).
  5. Explain why standardize the entire base before cross-validation It’s a data leak.

5.4 The Kernel trick

Explicit transformations can create thousands — or infinite — features. However, some algorithms never need to access each ϕ(x)\phi(x) coordinate separately: they use only products scale between transformed examples. core device, also called kernel trick, explores exactly this situation.

A core function is calculated in the input space:

K:X×X⟶R,K(x,z)=⟨ϕ(x),ϕ(z)⟩F,(5.7) K:X\times X\longrightarrow\mathbb R, \qquad K(x,z)=\langle\phi(x),\phi(z)\rangle_{\mathcal F}, \tag{5.7}

where F\mathcal F is the attribute space. If there is an expression direct and cheap for K(x,z)K(x,z), we can get the product climb without build the vectors ϕ(x)\phi(x) and ϕ(z)\phi(z).

The core calculates directly, in the original space, the same scalar product that would be obtained after the explicit transformation.

Figure 5.4. The core calculates directly, in the original space, the same scalar product that would be obtained after the explicit transformation.

The gain does not simply come from the fact that XX has a smaller dimension. depends on two conditions: the core should be cheap to evaluate and the algorithm should be able to be formulated only in terms of these products scalars. Marginal methods, such as support vector machines, are the classic example.

5.4.1 Principle

Consider a sample D={(xi,yi)}i=1ND=\{(x_i,y_i)\}_{i=1}^N. In many problems regularized, the solution in the attribute space can be written as

w=∑i=1Nαiϕ(xi).(5.8) w=\sum_{i=1}^N\alpha_i\phi(x_i). \tag{5.8}

To predict at a new xx point , we calculated

f(x)=⟨w,ϕ(x)⟩+b=∑i=1Nαi⟨ϕ(xi),ϕ(x)⟩+b=∑i=1NαiK(xi,x)+b.(5.9) \begin{aligned} f(x) &=\langle w,\phi(x)\rangle+b\\ &=\sum_{i=1}^N\alpha_i \langle\phi(x_i),\phi(x)\rangle+b\\ &=\sum_{i=1}^N\alpha_iK(x_i,x)+b. \end{aligned} \tag{5.9}

Note the change of representation. In the primal method, we store the ww coordinates ; in dual representation, we store coefficients αi\alpha_i associated with training examples. The core receives ** two ** domain points, not a weight vector and a point.

During training, products among all pairs form the Gram matrix:

Gij=K(xi,xj),G∈RN×N. G_{ij}=K(x_i,x_j), \qquad G\in\mathbb R^{N\times N}.

This matrix summarizes the geometry of the sample in the attribute space. GijG_{ij} input measures the core-induced similarity between the examples xix_i and xjx_j.

5.4.2 Example: quadratic polynomial kernel

In two dimensions, take

K(x,z)=(1+xTz)2. K(x,z)=(1+x^{\mathsf T}z)^2.

Expanding,

K(x,z)=1+2x1z1+2x2z2+x12z12+2x1x2z1z2+x22z22. K(x,z) =1+2x_1z_1+2x_2z_2+x_1^2z_1^2 +2x_1x_2z_1z_2+x_2^2z_2^2.

This expression is the scalar product associated with the map

ϕ(x)=(1,2x1,2x2,x12,2x1x2,x22). \phi(x)= \left(1,\sqrt2x_1,\sqrt2x_2,x_1^2, \sqrt2x_1x_2,x_2^2\right).

Therefore, we can calculate a product in six dimensions using only xTzx^{\mathsf T}z in original space. 2\sqrt2 factors are required for the coefficient of the crossed terms to be exactly 22.

5.4.3 When does the kernel trick apply?

It is not enough that the loss function contains wTxw^{\mathsf T}x. It is necessary rewrite the training procedure and prediction in terms of products among examples, such as (5.8) and (5.9). SVMs, * ridge regression* in dual form and PCA with core have formulations of this type. logistic regression does not accept a kernel automatically; it would be need a formulation or an appropriate algorithm.

There’s also a computer exchange. cost as a function of d′d', while the core method stores a matrix N×NN\times N. For very large samples, the memory cost O(N2)O(N^2) and the cost of training can overcome the savings obtained by the non materialize ϕ(x)\phi(x). Therefore, kernels are especially attractive when d′d' is huge and NN is still manageable.

import numpy as np


def matriz_gram_polinomial(X, grau=2, constante=1.0):
    X = np.asarray(X, dtype=float)
    return (constante + X @ X.T) ** grau

For a X matrix of (N, d) format, the result has format (N, N). In a robust implementation, the same core parameters used in training should be preserved for prediction.

Exercises

  1. Manually check the value of K(x,z)K(x,z) for x=(1,2)x=(1,2) and z=(3,−1)z=(3,-1) using both the direct formula and the explicit map.
  2. Explain the difference between the dimensions of XX, ϕ(X)\phi(X) and Gram’s matrix.
  3. Show that the Gram matrix of a symmetric core is also symmetric.
  4. Compare the memory of an explicit matrix N×d′N\times d' to that of Gram matrix N×NN\times N when N=10 000N=10\,000 and d′=500d'=500.

5.4.4 Mercer’s theorem

Not every similarity function can replace a scalar product. be a valid real core, K:X×X→RK:X\times X\to\mathbb R must satisfy two fundamental properties.

First, it must be symmetrical:

K(x,z)=K(z,x). K(x,z)=K(z,x).

Second, it must be positive semi-defined: for any quantity finite of x1,…,xN∈Xx_1,\ldots,x_N\in X points and any actual coefficients c1,…,cNc_1,\ldots,c_N,

∑i=1N∑j=1NcicjK(xi,xj)≥0.(5.10) \sum_{i=1}^N\sum_{j=1}^N c_i c_j K(x_i,x_j)\geq0. \tag{5.10}

If GG is the Gram matrix, this condition equals

cTGc≥0for all c∈RN. c^{\mathsf T}Gc\geq0 \quad\text{for all }c\in\mathbb R^N.

Since GG is symmetrical, this also amounts to saying that all your eigenvalues are not negative. Small negative eigenvalues can appear numerically by rounding; relevant negative values indicate that the function or implementation does not produce a matrix positive semi-defined in that sample.

5.4.5 Why is positivity necessary?

If there is a ϕ\phi map such that K(x,z)=⟨ϕ(x),ϕ(z)⟩K(x,z)=\langle\phi(x),\phi(z)\rangle, then

∑i,jcicjK(xi,xj)=∑i,jcicj⟨ϕ(xi),ϕ(xj)⟩=∥∑iciϕ(xi)∥2≥0. \begin{aligned} \sum_{i,j}c_i c_jK(x_i,x_j) &=\sum_{i,j}c_i c_j \langle\phi(x_i),\phi(x_j)\rangle\\ &=\left\lVert\sum_i c_i\phi(x_i)\right\rVert^2\\ &\geq0. \end{aligned}

Therefore, (5.10) is not an arbitrary technical detail: it follows the fact that the square of a norm is never negative.

5.4.6 Mercer and associated space

In common machine learning language, the previous condition is often called “ Mercer condition”. However, it is appropriate to separate two related results:

  • Moore theorem–Aronszajn ensures that every symmetrical kernel and semi-defined positive determines a Hilbert space of functions with breeding core and an attribute map, possibly Infinite-dimensional;
  • the Mercer’s theorem, under additional hypotheses as compact domain and continuous, symmetrical and positive core provides a spectral expansion in self-functions.

In a simplified form, Mercer expansion is

K(x,z)=∑r=1∞lambdarer(x)er(z),λr≥0, K(x,z)=\sum_{r=1}^{\infty}lambda_r e_r(x)e_r(z), \qquad \lambda_r\geq0,

where ere_r are orthonormal autofunctions of an associated integral operator to the core. This suggests the map

ϕ(x)=(λ1e1(x),λ2e2(x),…), \phi(x)= \left(\sqrt{\lambda_1}e_1(x), \sqrt{\lambda_2}e_2(x),\ldots\right),

because your scalar product recovers K(x,z)K(x,z). The space may have dimension Infinite, but the algorithm accesses only core evaluations.

Semidefined does not mean strictly positive

cTGc=0c^{\mathsf T}Gc=0 is allowed for some non-null vector cc. occurs when the transformed vectors have linear dependence. positive semi-defined kernel remains valid in this case.

5.4.7 Rules for building new kernels

If K1K_1 and K2K_2 are valid kernels and a,b≥0a,b\geq0, then they are also valid kernels valid:

aK1(x,z)+bK2(x,z),K1(x,z)K2(x,z). aK_1(x,z)+bK_2(x,z), \qquad K_1(x,z)K_2(x,z).

In addition, for any q:X→Rq:X\to\mathbb R function,

K(x,z)=q(x)q(z) K(x,z)=q(x)q(z)

is a valid core. These rules allow combining notions of similarity without having to explicitly discover the resulting map. Subtract kernels or apply an arbitrary transformation on the other hand side, it can destroy the positive semi-definition.

5.4.8 Numerical verification in a sample

import numpy as np


def verificar_gram(G, tolerancia=1e-10):
    G = np.asarray(G, dtype=float)
    if G.ndim != 2 or G.shape[0] != G.shape[1]:
        raise ValueError("G deve ser uma matriz quadrada")

    simetrica = np.allclose(G, G.T, atol=tolerancia)
    G_sim = (G + G.T) / 2
    autovalores = np.linalg.eigvalsh(G_sim)
    psd = autovalores.min() >= -tolerancia
    return simetrica, psd, autovalores

This test only checks the matrix of the provided points. It can find a counterexample and prove that a function is not a core valid, but positive results in some samples do not demonstrate the property for every finite set possible. General validity requires a known proof or a known theoretical result.

Exercises

  1. Prove directly that K(x,z)=xTzK(x,z)=x^{\mathsf T}z satisfies (5.10).
  2. Show that the sum of two valid kernels with non-coefficients Negative is also valid.
  3. Give an example of symmetrical matrix that is not semi-defined positive.
  4. Explain why testing only one Gram matrix does not prove that one function is core throughout the domain.
  5. What is the attribute map associated with K(x,z)=1+xTzK(x,z)=1+x^{\mathsf T}z?

5.4.9 Advantage

The core device allows working with a nonlinear geometry without explicitly store all features of ϕ(x)\phi(x). Its main advantages are:

  • represent very high dimension interactions with a short formula;
  • reuse algorithms based on scalar products;
  • express different notions of similarity through the choice of KK;
  • obtain nonlinear borders while maintaining convex optimization on methods such as S.V.M.

These advantages do not eliminate costs. Training usually uses the Gram N×NN\times N matrix, and a prediction by (5.9) may require a core evaluation for each αi\alpha_i coefficient not null. In an SVM, only the examples with αi≠0\alpha_i\neq0 are support vectors, which can make prediction sparse; yet, its number depends on the data and the hyperparameters.

5.4.10 Linear kernel

K(x,z)=xTz. K(x,z)=x^{\mathsf T}z.

It does not create a nonlinear border: it corresponds to the identity map. It serves as a reference and is usually competitive when the features already are numerous, as in sparse representations of text.

5.4.11 Polynomial kernel

K(x,z)=(γxTz+c0)Q, K(x,z)=(\gamma x^{\mathsf T}z+c_0)^Q,

with γ>0\gamma>0, c0≥0c_0\geq0 and whole grade Q≥1Q\geq1. The core represents monomials and interactions to the degree QQ when c0>0c_0>0. If c0=0c_0=0, contains QQ exact degree terms only. The γ\gamma and c0c_0 parameters change the relative scale of contributions and should be treated as part of the model.

5.4.12 Gaussian kernel or RBF

K(x,z)=exp⁡ ⁣(−γ∥x−z∥2)=exp⁡ ⁣(−∥x−z∥22σ2), K(x,z) =\exp\!\left(-\gamma\lVert x-z\rVert^2\right) =\exp\!\left(-\frac{\lVert x-z\rVert^2}{2\sigma^2}\right),

where

γ=12σ2. \gamma=\frac1{2\sigma^2}.

The RBF core is worth 11 when x=zx=z and approaches zero as the distance grows. Its attribute map is infinite-dimensional, but the core evaluation depends only on Euclidean distance.

The parameter controls the neighborhood scale:

  • γ\gamma small (or large σ\sigma ): the similarity decays slowly and the border tends to vary smoothly;
  • γ\gamma large (or small σ\sigma ): the influence of each point It is located and the border can become very irregular.

In SVM, γ\gamma interacts with the CCregularization parameter . high CC penalize strongly violations in the sample; lower values They accept more violations to favor a regularized margin. should be chosen with validation, never by performance in the test.

Feature scaling changes RBF core

A variable measured in thousands can dominate ∥x−z∥2\lVert x-z\rVert^2 and nullify the influence of variables measured between zero and one. standardization only in training and apply the same parameters to others data.

5.4.13 Practical choice

A reasonable sequence is to start with the linear kernel, establish a base line and only then test a nonlinear geometry. For RBF, we searched for CC and γ\gamma in logarithmic scale by cross-validation. the polynomial, grade, CC, γ\gamma and c0c_0 extend the search space and the They require more care.

It is also necessary to consider the sample size. When NN is very large and a moderate explicit map exists, a linear method on the transformed features or a core approach may be more efficient that store Gram’s matrix complete.

import numpy as np


def kernel_rbf(X, Z, gamma):
    X = np.asarray(X, dtype=float)
    Z = np.asarray(Z, dtype=float)
    if gamma <= 0:
        raise ValueError("gamma deve ser positivo")

    norma_X = np.sum(X**2, axis=1)[:, None]
    norma_Z = np.sum(Z**2, axis=1)[None, :]
    dist2 = np.maximum(norma_X + norma_Z - 2 * X @ Z.T, 0.0)
    return np.exp(-gamma * dist2)

Correction with maximum removes small negative distance values quadratic caused by rounding. The result has format (len(X), len(Z)), useful for both the training matrix and for compare new examples to stored examples.

Exercises

  1. Calculate the RBF core to equal points and interpret the result.
  2. Describe the effect of γ→0\gamma\to0 and γ→∞\gamma\to\infty for points distinct.
  3. Explain why standardization influences the RBF, but does not correct by It’s just overfitting.
  4. Compare the cost of storing N×d′N\times d' with N×NN\times N in two scenarios chosen by you.
  5. Why a good result with linear kernel is a useful reference before testing more flexible kernels?

5.4.14 Applications

Systematic use of core functions precedes modern SVMs, but gained high visibility with margin classifiers in the 1990s. The idea, however, does not belong to a single algorithm: whenever a method admits a formulation based on scalar products, we can to investigate a core version.

5.4.15 Support vector machines

In the dual form of an SVM, the training uses the examples through

yiyjK(xi,xj). y_i y_j K(x_i,x_j).

After adjustment, the decision function is

f(x)=∑i∈SαiyiK(xi,x)+b, f(x)=\sum_{i\in\mathcal S}\alpha_i y_iK(x_i,x)+b,

where S\mathcal S is the support vector set. sinal⁡(f(x))\operatorname{sinal}(f(x)). The core changes the geometry in which the margin is maximized, while CC controls the penalty of violations.

5.4.16 Kernel regression

In * ridge* regression with core, we seek a function of the shape

f(x)=∑i=1NαiK(xi,x). f(x)=\sum_{i=1}^N\alpha_iK(x_i,x).

With squared loss and regularization, the coefficients satisfy

(G+λI)α=y, (G+\lambda I)\alpha=y,

where GG is the matrix of Gram and λ>0\lambda>0 controls the regularization. addition of λI\lambda I also improves numerical stability when GG It’s unique or almost unique.

5.4.17 Kernel PCA

The analysis of common main components finds linear directions of greater variance. PCA with core performs space analysis F\mathcal F without explicitly forming ϕ(x)\phi(x). For this, works with a centralized Gram matrix:

Gc=HGH,H=I−1N11T. G_c=HGH, \qquad H=I-\frac1N\mathbf1\mathbf1^{\mathsf T}.

Centralizing the original features does not replace this operation: what need to have zero mean are the vectors ϕ(xi)\phi(x_i) in the attribute space. GcG_c autovectors provide useful nonlinear coordinates for visualization and reduction of dimensionality.

5.4.18 Structured data and specialized kernels

The domain does not need to be Rd\mathbb R^d. It is possible to set kernels for sequences, trees, graphs, sets or histograms, provided that resultant function is symmetric and semi-defined positive. the core incorporates knowledge about the structure of the object and allows for the apply a geometric method without converting everything to a dense vector of fixed size.

In text, for example, the linear kernel on sparse vectors of frequency is a strong base. More elaborate kernels can compare subsequences, but its cost and difficulty to choose hyperparameters need to be compared to explicit representations modern.

5.4.19 A decision-making roadmap

Before adopting a core method, answer:

  1. Does the method have a formulation based on scalar products?
  2. There is a notion of similarity appropriate to the domain and proven valid as a core?
  3. The NN number of examples allows you to store and process N2N^2 Values?
  4. The prediction will have an acceptable latency with the expected amount of Active examples or support vectors?
  5. There is validation to choose the core and its hyperparameters without using the test set?

If NN is too large, alternatives include explicit low maps dimension, approximations by random characteristics, methods of Nyström and linear or neural models trained in batches. powerful tool, not a mandatory step.

5.4.20 Example of experimental flow

# Pseudocode: The exact syntax depends on the library used.
separar_treino_validacao_teste()

for nome_kernel, parametros in configuracoes:
    for particao_treino, particao_validacao in validacao_cruzada(treino):
        normalizador.ajustar(particao_treino.X)
        Xtr = normalizador.transformar(particao_treino.X)
        Xva = normalizador.transformar(particao_validacao.X)

        modelo = SVM(kernel=nome_kernel, **parametros)
        modelo.ajustar(Xtr, particao_treino.y)
        registrar(modelo.avaliar(Xva, particao_validacao.y))

escolher_configuracao_por_validacao()
avaliar_uma_vez_no_teste()

The normalizer is readjusted on each partition to avoid leakage. final evaluation in the test is performed only once, after all of the modeling decisions have been terminated.

Exercises

  1. Identify where the core appears in the prediction of an S.M.M.
  2. Explain why G+λIG+\lambda I is numerically more stable than GG when some eigenvalues are close to zero.
  3. Derive the HH matrix to N=3N=3 and check that H1=0H\mathbf1=0.
  4. Propose a similarity function for a structured domain and Discuss what would be lacking to prove to use as a core.
  5. In which scenario an explicit map may be preferable to the matrix of Gram?

5.4.21 Summary of the chapter

Transforming features allows you to convert nonlinear relationships into space original in linear relationships in another space. Polynomial maps make this concrete construction, but its dimension grows combined. core device avoids materializing the map when the algorithm depends only scalar products. In exchange, shift the cost to the matrix Gram and for similarity assessments. The choice between map explicit and core should consider expressiveness, generalization, memory, training time and prediction cost.

5.5 Multiple choice exercises

The questions integrate transformation of features, polynomial maps and methods of There is only one correct alternative in each item.

  1. When applying ϕ(x1,x2)=(x12,x22)\phi(x_1,x_2)=(x_1^2,x_2^2), the linear border w1z1+w2z2+b=0w_1z_1+w_2z_2+b=0 in the transformed space corresponds, in the original space, to a border:

    1. necessarily linear.
    2. quadratic.
    3. cubica.
    4. independent of x1x_1 and x2x_2.
  2. After a nonlinear transformation ϕ\phi, call the linear model means it’s linear:

    1. in the transformed features and their parameters.
    2. in any variable of the original problem.
    3. only in the number of examples.
    4. only in the execution time.
  3. How many total grade monomials up to pp exist in variable dd , including the constant term?

    1. dpdp.
    2. d+pd+p.
    3. (d+pp)\binom{d+p}{p}.
    4. 2dp2^{dp} in all cases.
  4. Increase the degree of a polynomial map tends to:

    1. always reduce capacity and cost.
    2. increase expressiveness and also the risk of overfitting.
    3. preserve the exact same class of hypotheses.
    4. ensure zero test error.
  5. The core artifice is applicable when the algorithm can be written in terms of:

    1. scalar products between processed examples.
    2. alphabetical ordering of features.
    3. only one co-ordinate for example.
    4. bitwise operations.
  6. A valid core function satisfies k(x,z)=⟨ϕ(x),ϕ(z)⟩k(x,z)=\langle\phi(x),\phi(z)\rangle for some attribute map. Consequently, your Gram matrix should be:

    1. antisymmetric.
    2. triangular with null diagonal.
    3. symmetric and semi-defined positive.
    4. composed only of integers.
  7. What expression defines the RBF core?

    1. xTzx^{\mathsf T}z.
    2. (xTz+c)p(x^{\mathsf T}z+c)^p.
    3. exp⁡(−γ∥x−z∥2)\exp(-\gamma\|x-z\|^2).
    4. ∥x+z∥\|x+z\|.
  8. In the RBF core, a very high value of γ\gamma usually makes the similarity:

    1. more local, falling rapidly with distance.
    2. constant and equal to one.
    3. independent of the data.
    4. necessarily negative.
  9. An important limitation of methods that store a dense Gram matrix for NN examples is the order memory consumption:

    1. O(1)O(1).
    2. O(log⁡N)O(\log N).
    3. O(N)O(N).
    4. O(N2)O(N^2).
  10. The choice of hyperparameters such as grade, γ\gamma or regularization should be performed mainly with:

    1. the final test set.
    2. validation or cross-validation data.
    3. examples invented after knowing the test.
    4. only the training error.

Answer key with explanations

  1. b. Replace z1=x12z_1=x_1^2 and z2=x22z_2=x_2^2 produces a second-degree equation at the original coordinates.
  2. a. The border is linear in ϕ(x)\phi(x) and in the weights, although it may be curved in xx.
  3. c. Counting combinations with repetition results in (d+pp)\binom{d+p}{p}.
  4. b. More terms allow you to adjust more complex patterns, but elevate capacity, cost and sensitivity to the sample.
  5. a. The core replaces directly ⟨ϕ(x),ϕ(z)⟩\langle\phi(x),\phi(z)\rangle without materializing ϕ\phi.
  6. c. This is the condition that allows interpreting the function as a product internal in a feature space.
  7. c. RBF decays exponentially with quadratic distance.
  8. a. The higher γ\gamma, the smaller the spatial scale of influence of each example.
  9. d. The matrix contains a similarity for each pair of examples.
  10. b. The test must remain untouched; validation guides decisions of modeling.