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:
The model starts to calculate
where can be the signal, identity or sigmoid. linear in transformed features and 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. 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:
No line separates the internal from the external. However, with
the problem becomes one-dimensional: just compare with the threshold .

Figure 5.1. A circular boundary in the original space becomes a linear threshold after radial transformation.
We don’t need to reverse after training. new example , we calculate and apply the learned model. output continues to refer to the original example.
5.1.2 Sample transformation
Stop
the processed sample is
Labels do not change. The linear algorithm receives as its features and choose
The final hypothesis in the original domain is the composition .
5.1.3 Polynomial example
For two entries, a complete quadratic map may be
A linear score is
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:
| Space | Subject matter | Can it be nonlinear? |
|---|---|---|
| original entry | Yes, the border can be curved | |
| characteristics | map can be nonlinear | |
| parameters | is linear in |
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 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 features, the number of degree monomials up to is
With and , they are already 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 ;
- Implicit**:** calculate only products through a core (kernel).
The core device will be useful when the size of 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
- In what sense (5.1) is linear and in which Can sense be nonlinear?
- Why don’t we have to calculate to make predictions?
- How many degree monomials up to two are there for ?
- Give an example of transformation that would depend on statistics from Training and could cause data leaks.
- 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 features.
An ellipse aligned to the axes, with semi-axis , satisfies
For a radius circle, we have and the equation is . The square in the radius is indispensable.
5.2.1 From an ellipse to a line
Set
In the transformed space, (5.3) becomes
which is the equation of a straight line. The “interior positive” classification can be written as
In the homogeneous vector
the weights are
and (5.4) takes the linear form .

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 ; we do not occupy All . That doesn’t stop the classifier, but remember that may lose information: points , and other signal changes have the same image.
5.2.2 Learning the ellipse
In the previous example, and seemed to be known. we provide the features and let the algorithm estimate
When and , the border corresponds to
with
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
where is a defined positive symmetrical matrix.
So we need the crossword word:
The 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 satisfies
As they expand, quadratic, linear and constant terms emerge. the complete quadratic map
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 is a hypothesis in transformed space and
So, for every example, . Using the same loss,
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 is the class of linear separators in and is fixed, the class in the original domain is
How patterns performed by correspond to patterns of on images,
For and related separators in two dimensions, therefore . 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
- Correct the classifier if the positive class is outside the ellipse.
- Derive and from under the appropriate signals.
- Expand and identify the six coefficients.
- Show that changes signal under reflection , unlike squares.
- 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 , a transformation of features has the form
The number does not need to be equal to . 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 brings together all monomials
The vector is called multiindex and is the total degree of monomium. For and , for example,
A linear function in this new vector produces
i.e., a quadratic polynomial in the original space. nonlinear in , but continues linear in 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 in variable is
Adding the degrees of to , we get
This count includes the constant term if bias is treated separately, the dimension of the vector without the constant will be
For two variables,
Thus, with , the grades generate 3, 6, respectively. 10 and 15 coefficients when we count the constant term.

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. and , (5.6) provides coefficients. A design matrix with examples can therefore go from to .
5.3.3 Expressivity, generalization and cost
By increasing , the hypothesis class contains more flexible borders. As polynomial classes are nested, the smallest training error cannot increase: a 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:
- Approximation: higher degrees may represent relationships than a simple model can’t capture.
- Estimation: plus parameters make adjustment more sensitive to particularities and the noise of the sample.
- Computing: store the processed matrix and calculate products, gradients or inverses begin to require more memory and time.
For -related separators , the class VC dimension complete linear is . However, the composite class may have smaller VC dimension, as the vectors occupy only a structured part of space still, the growth of is a good warning for the risk of overfitting.
5.3.4 How to choose the degree
The degree is a hyperparameter. An appropriate practice is:
- separate test data and do not use them in choice;
- compare candidate degrees by validation or cross-validation;
- adjust to the training set any necessary standardisation;
- apply exactly the same transformation in validation and testing;
- select the degree and the regularization together.
Standardization deserves attention. If has large values, can get numerically huge. In general, we standardize the original variables using training statistics and only then did we generate the Polynomial terms. Regularization or 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
- List all maximum grade monomials in two variables.
- Calculate and interpret the difference between counting or not constant term.
- Show why the minimum training error does not increase when a It passes from grade to grade .
- For , manually calculate in the order used in (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 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:
where is the attribute space. If there is an expression direct and cheap for , we can get the product climb without build the vectors and .

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 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 . In many problems regularized, the solution in the attribute space can be written as
To predict at a new point , we calculated
Note the change of representation. In the primal method, we store the coordinates ; in dual representation, we store coefficients 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:
This matrix summarizes the geometry of the sample in the attribute space. input measures the core-induced similarity between the examples and .
5.4.2 Example: quadratic polynomial kernel
In two dimensions, take
Expanding,
This expression is the scalar product associated with the map
Therefore, we can calculate a product in six dimensions using only in original space. factors are required for the coefficient of the crossed terms to be exactly .
5.4.3 When does the kernel trick apply?
It is not enough that the loss function contains . 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 , while the core method stores a matrix . For very large samples, the memory cost and the cost of training can overcome the savings obtained by the non materialize . Therefore, kernels are especially attractive when is huge and 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
- Manually check the value of for and using both the direct formula and the explicit map.
- Explain the difference between the dimensions of , and Gram’s matrix.
- Show that the Gram matrix of a symmetric core is also symmetric.
- Compare the memory of an explicit matrix to that of Gram matrix when and .
5.4.4 Mercer’s theorem
Not every similarity function can replace a scalar product. be a valid real core, must satisfy two fundamental properties.
First, it must be symmetrical:
Second, it must be positive semi-defined: for any quantity finite of points and any actual coefficients ,
If is the Gram matrix, this condition equals
Since 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 map such that , then
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
where are orthonormal autofunctions of an associated integral operator to the core. This suggests the map
because your scalar product recovers . The space may have dimension Infinite, but the algorithm accesses only core evaluations.
Semidefined does not mean strictly positive
is allowed for some non-null vector . 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 and are valid kernels and , then they are also valid kernels valid:
In addition, for any function,
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
- Prove directly that satisfies (5.10).
- Show that the sum of two valid kernels with non-coefficients Negative is also valid.
- Give an example of symmetrical matrix that is not semi-defined positive.
- Explain why testing only one Gram matrix does not prove that one function is core throughout the domain.
- What is the attribute map associated with ?
5.4.9 Advantage
The core device allows working with a nonlinear geometry without explicitly store all features of . 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 ;
- 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 matrix, and a prediction by (5.9) may require a core evaluation for each coefficient not null. In an SVM, only the examples with are support vectors, which can make prediction sparse; yet, its number depends on the data and the hyperparameters.
5.4.10 Linear kernel
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
with , and whole grade . The core represents monomials and interactions to the degree when . If , contains exact degree terms only. The and parameters change the relative scale of contributions and should be treated as part of the model.
5.4.12 Gaussian kernel or RBF
where
The RBF core is worth when 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:
- small (or large ): the similarity decays slowly and the border tends to vary smoothly;
- large (or small ): the influence of each point It is located and the border can become very irregular.
In SVM, interacts with the regularization parameter . high 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 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 and in logarithmic scale by cross-validation. the polynomial, grade, , and extend the search space and the They require more care.
It is also necessary to consider the sample size. When 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
- Calculate the RBF core to equal points and interpret the result.
- Describe the effect of and for points distinct.
- Explain why standardization influences the RBF, but does not correct by It’s just overfitting.
- Compare the cost of storing with in two scenarios chosen by you.
- 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
After adjustment, the decision function is
where is the support vector set. . The core changes the geometry in which the margin is maximized, while controls the penalty of violations.
5.4.16 Kernel regression
In * ridge* regression with core, we seek a function of the shape
With squared loss and regularization, the coefficients satisfy
where is the matrix of Gram and controls the regularization. addition of also improves numerical stability when 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 without explicitly forming . For this, works with a centralized Gram matrix:
Centralizing the original features does not replace this operation: what need to have zero mean are the vectors in the attribute space. 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 . 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:
- Does the method have a formulation based on scalar products?
- There is a notion of similarity appropriate to the domain and proven valid as a core?
- The number of examples allows you to store and process Values?
- The prediction will have an acceptable latency with the expected amount of Active examples or support vectors?
- There is validation to choose the core and its hyperparameters without using the test set?
If 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
- Identify where the core appears in the prediction of an S.M.M.
- Explain why is numerically more stable than when some eigenvalues are close to zero.
- Derive the matrix to and check that .
- Propose a similarity function for a structured domain and Discuss what would be lacking to prove to use as a core.
- 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.
-
When applying , the linear border in the transformed space corresponds, in the original space, to a border:
- necessarily linear.
- quadratic.
- cubica.
- independent of and .
-
After a nonlinear transformation , call the linear model means it’s linear:
- in the transformed features and their parameters.
- in any variable of the original problem.
- only in the number of examples.
- only in the execution time.
-
How many total grade monomials up to exist in variable , including the constant term?
- .
- .
- .
- in all cases.
-
Increase the degree of a polynomial map tends to:
- always reduce capacity and cost.
- increase expressiveness and also the risk of overfitting.
- preserve the exact same class of hypotheses.
- ensure zero test error.
-
The core artifice is applicable when the algorithm can be written in terms of:
- scalar products between processed examples.
- alphabetical ordering of features.
- only one co-ordinate for example.
- bitwise operations.
-
A valid core function satisfies for some attribute map. Consequently, your Gram matrix should be:
- antisymmetric.
- triangular with null diagonal.
- symmetric and semi-defined positive.
- composed only of integers.
-
What expression defines the RBF core?
- .
- .
- .
- .
-
In the RBF core, a very high value of usually makes the similarity:
- more local, falling rapidly with distance.
- constant and equal to one.
- independent of the data.
- necessarily negative.
-
An important limitation of methods that store a dense Gram matrix for examples is the order memory consumption:
- .
- .
- .
- .
-
The choice of hyperparameters such as grade, or regularization should be performed mainly with:
- the final test set.
- validation or cross-validation data.
- examples invented after knowing the test.
- only the training error.
Answer key with explanations
- b. Replace and produces a second-degree equation at the original coordinates.
- a. The border is linear in and in the weights, although it may be curved in .
- c. Counting combinations with repetition results in .
- b. More terms allow you to adjust more complex patterns, but elevate capacity, cost and sensitivity to the sample.
- a. The core replaces directly without materializing .
- c. This is the condition that allows interpreting the function as a product internal in a feature space.
- c. RBF decays exponentially with quadratic distance.
- a. The higher , the smaller the spatial scale of influence of each example.
- d. The matrix contains a similarity for each pair of examples.
- b. The test must remain untouched; validation guides decisions of modeling.