Skip to content

~/teaching · machine learning · session 5, tuesday 15 december 2026

The kernel trick, support vector machines, kernel ridge and decision trees, with worked numbers

Two model families that look nothing like logistic regression: similarities between points, and nested questions.

Abstract

This page summarises session 5 of the Machine Learning course at Centrale Méditerranée (option DDEFI, 2026-2027). After a first block on linear and logistic models, it turns to two families that work differently: kernel methods, which predict by a weighted vote of similarities to the training points, and decision trees, which cut the space into boxes one question at a time.

The kernel part goes from the maximum-margin classifier to its dual, shows why only the support vectors matter, swaps the dot product for a polynomial or Gaussian kernel, and turns ridge into kernel ridge. The tree part builds CART: Gini and entropy, the gain of a split, depth, pruning, instability and the bias of impurity-based importance. Every step is checked on numbers small enough to redo with a pencil.

The slides

Back-to-class test, kernels, SVM and decision trees

Session 5, Tuesday 15 December 2026. Machine Learning, Centrale Méditerranée, option DDEFI, 2026-2027.

Open the slides (password from your teacher)

The deck itself is encrypted for the students of the course; this page summarises it for everyone.

The course page · Attention and transformers, step by step

Plan of the deck

  1. Maximum margin. The separating line furthest from the nearest points, written as a convex problem.
  2. Soft margin and the price C. Slack variables and the hinge loss, for data that no line separates.
  3. The dual and the support vectors. Lagrange multipliers, KKT conditions and a four-point example by hand.
  4. The kernel trick. Polynomial and RBF kernels, and Mercer's condition on valid kernels.
  5. Kernel ridge and practice. The closed form, a three-point example, γ\gamma and CC, scaling, the cost in nn, and a short lab.
  6. Decision trees and impurity. CART's greedy search, Gini and entropy, two candidate splits on ten clients.
  7. Depth, pruning and importance. Overfitting with depth, cost-complexity pruning, instability and the MDI bias.

The maximum-margin classifier

Among all the lines that separate two classes without error, the SVM keeps the one that stays as far as possible from the closest points on each side.

When two classes can be separated by a straight line, infinitely many lines do it with zero training error. Logistic regression picks one through the likelihood. The support vector machine (SVM) asks a geometric question instead: which boundary leaves the widest empty band between the classes? A new client resembles a known one plus a little noise, so a boundary that grazes a training point misclassifies its noisy neighbours.

Code the classes as yi∈{−1,+1}y_i \in \{-1, +1\} and write f(x)=w⊤x+bf(x) = w^{\top}x + b. Rescaling ww and bb together leaves the boundary unchanged, so we set ∣f∣=1|f| = 1 at the nearest points. Since a point lies at distance ∣f(x)∣/∥w∥|f(x)| / \lVert w \rVert from the hyperplane, the band is 2/∥w∥2/\lVert w \rVert wide, and widening it means shrinking ∥w∥\lVert w \rVert. The result is a convex quadratic problem with a unique minimum (Cortes and Vapnik, 1995):

min⁡w, b 12∥w∥2subject toyi (w⊤xi+b)≥1,i=1,…,n\min_{w,\,b}\ \tfrac12 \lVert w \rVert^{2} \quad \text{subject to} \quad y_i\,(w^{\top}x_i + b) \ge 1,\quad i = 1, \dots, n
(1)
Table 1: Six illustrative clients in two standardised variables. With w=(2/3,2/3)w = (2/3, 2/3) and b=−5/3b = -5/3, the boundary is x1+x2=2.5x_1 + x_2 = 2.5 and the band runs from x1+x2=1x_1 + x_2 = 1 to x1+x2=4x_1 + x_2 = 4.
ClientPosition (x1,x2)(x_1, x_2)Class yyLead y f(x)y\,f(x)Role
1(0, 0)sound, −1-15/3outside the band
2(1, 0)sound, −1-11on the edge
3(0, 1)sound, −1-11on the edge
4(2, 2)default, +1+11on the edge
5(3, 2)default, +1+15/3outside the band
6(2, 3)default, +1+15/3outside the band

The solution, which scikit-learn's SVC with a linear kernel and a very large CC also returns, has ∥w∥=22/3≈0.943\lVert w \rVert = 2\sqrt2/3 \approx 0.943, so the band is 2/∥w∥=3/2≈2.122/\lVert w \rVert = 3/\sqrt2 \approx 2.12 wide: exactly the gap between the two dashed lines, measured along the normal (1,1)/2(1, 1)/\sqrt2. Three clients touch the band; they are the support vectors. The other three could move, or disappear, without the boundary changing.

Back to contents.

Soft margin, hinge loss and the price C

Real data are never perfectly separable, so the SVM lets some points cross into the band and charges a fixed price for each unit of trespass.

On credit data, no line separates the defaulters from the sound clients. Cortes and Vapnik (1995) give each point a slack variable ξi≥0\xi_i \ge 0, the amount by which it breaks the margin, and add C∑iξiC \sum_i \xi_i to the objective. At the optimum each slack equals max⁡(0,1−yif(xi))\max(0, 1 - y_i f(x_i)), so the constraints can be removed altogether:

min⁡w, b 12∥w∥2+C∑i=1nmax⁡(0, 1−yi f(xi))\min_{w,\,b}\ \tfrac12 \lVert w \rVert^{2} + C \sum_{i=1}^{n} \max\big(0,\ 1 - y_i\, f(x_i)\big)
(2)

The summand is the hinge loss: zero for a point on the right side with a lead of at least 1, then growing linearly as the point moves into the band or across the boundary. Read this way, the soft-margin SVM is a loss plus a penalty on ∥w∥2\lVert w \rVert^{2}, the same shape as ridge, with CC playing the role of 1/λ1/\lambda. A small CC gives a wide margin and strong regularisation (risk of underfitting), a large CC a narrow margin and a risk of overfitting, as with the C of LogisticRegression.

Back to contents.

The dual problem: only the support vectors count

Rewritten with one price per constraint, the SVM shows that points far from the boundary get a price of zero, so deleting them changes nothing.

Attach a Lagrange multiplier αi≥0\alpha_i \ge 0 to each constraint and subtract the constraints from the objective. Setting the gradient in ww to zero, then the derivative in bb, gives two identities. Substituting them back removes ww and bb and leaves a problem in α\alpha alone:

L(w,b,α)=12∥w∥2−∑iαi[ yi(w⊤xi+b)−1 ]L(w, b, \alpha) = \tfrac12 \lVert w \rVert^{2} - \sum_{i} \alpha_i \big[\, y_i (w^{\top}x_i + b) - 1 \,\big]
(3)
w=∑iαi yi xi,∑iαi yi=0w = \sum_{i} \alpha_i\, y_i\, x_i, \qquad \sum_{i} \alpha_i\, y_i = 0
(4)
max⁡α≥0 ∑iαi−12∑i,jαiαj yiyj xi⊤xjsubject to∑iαiyi=0\max_{\alpha \ge 0}\ \sum_{i} \alpha_i - \tfrac12 \sum_{i,j} \alpha_i \alpha_j\, y_i y_j\, x_i^{\top}x_j \quad \text{subject to} \quad \sum_i \alpha_i y_i = 0
(5)

With a soft margin, the only change is a cap αi≤C\alpha_i \le C. Complementary slackness, one of the Karush-Kuhn-Tucker (KKT) conditions, gives αi [ yif(xi)−1 ]=0\alpha_i\,[\,y_i f(x_i) - 1\,] = 0, so either the price is zero or the constraint is tight. A point classified correctly and outside the band has αi=0\alpha_i = 0 and vanishes from ww and from every prediction. That sparsity is why SVC keeps only its support_ points to predict.

Worked example: four clients on a line

  1. Data. Sound clients at x=−3x = -3 and x=−1x = -1, defaults at x=2x = 2 and x=4x = 4. The two inner points are the closest to the other class.
  2. Supports on the edge. Writing y f(x)=1y\,f(x) = 1 at x=−1x = -1 and x=2x = 2 gives w−b=1w - b = 1 and 2w+b=12w + b = 1. Adding them, 3w=23w = 2, so w=2/3w = 2/3, b=−1/3b = -1/3, and the boundary sits at x=1/2x = 1/2.
  3. Outer points. At x=−3x = -3 and x=4x = 4 the lead is 7/3>17/3 > 1, so the constraint is slack and, by complementary slackness, their price is zero.
  4. Prices. The condition ∑iαiyi=0\sum_i \alpha_i y_i = 0 forces the two remaining prices to be equal, say aa. Then w=a(−1)(−1)+a(+1)(2)=3a=2/3w = a(-1)(-1) + a(+1)(2) = 3a = 2/3, hence a=2/9a = 2/9.
  5. Check. The primal value 12w2=2/9\tfrac12 w^{2} = 2/9 equals the dual value ∑iαi−12w2=4/9−2/9\sum_i \alpha_i - \tfrac12 w^{2} = 4/9 - 2/9, and the margin 2/w=32/w = 3 is the distance from −1-1 to 22. Moving the point at −3-3 to −10-10 changes nothing; moving the point at −1-1 changes everything.

Back to contents.

The kernel trick: polynomial and RBF kernels

The dual touches the data only through similarities between pairs of points, so swapping the dot product for a richer similarity bends the boundary without extra work.

Look again at the dual: training needs only the n×nn \times n table of dot products xi⊤xjx_i^{\top}x_j, the Gram matrix, and prediction only xi⊤xx_i^{\top}x. Points on a line with one class at both ends and the other in the middle cannot be split by one threshold, but after x↦(x,x2)x \mapsto (x, x^{2}) a horizontal line does it. A curved boundary is a flat one after a transformation φ\varphi, the feature map. The kernel trick computes φ(x)⊤φ(z)\varphi(x)^{\top}\varphi(z) straight from xx and zz, without building φ\varphi (Boser, Guyon and Vapnik, 1992).

k(x,z)=φ(x)⊤φ(z),f(x)=∑iαi yi k(xi,x)+bk(x, z) = \varphi(x)^{\top}\varphi(z), \qquad f(x) = \sum_{i} \alpha_i\, y_i\, k(x_i, x) + b
(6)

For the degree-2 polynomial kernel in two dimensions, expanding the square and splitting the cross term into 2⋅2\sqrt2 \cdot \sqrt2 reveals the hidden map:

(x⊤z)2=x12z12+2 x1x2 z1z2+x22z22=φ(x)⊤φ(z),φ(x)=(x12, 2 x1x2, x22)(x^{\top}z)^{2} = x_1^{2}z_1^{2} + 2\,x_1x_2\,z_1z_2 + x_2^{2}z_2^{2} = \varphi(x)^{\top}\varphi(z), \quad \varphi(x) = \big(x_1^{2},\ \sqrt2\,x_1x_2,\ x_2^{2}\big)
(7)

Check with x=(1,2)x = (1, 2) and z=(3,−1)z = (3, -1). The kernel side needs two products, a sum and a square: x⊤z=1x^{\top}z = 1, so k=1k = 1. The feature side builds φ(x)=(1,22,4)\varphi(x) = (1, 2\sqrt2, 4) and φ(z)=(9,−32,1)\varphi(z) = (9, -3\sqrt2, 1), whose dot product is 9−12+4=19 - 12 + 4 = 1. The general kernel (x⊤z+c)d(x^{\top}z + c)^{d} contains every interaction up to degree dd for the price of one dot product and a power.

k(x,z)=e−γ∥x−z∥2,γ>0k(x, z) = e^{-\gamma \lVert x - z \rVert^{2}}, \qquad \gamma > 0
(8)

The Gaussian or RBF kernel (radial basis function) is 1 for identical points and fades with distance; γ\gamma sets how far each training point's influence reaches. For two points at squared distance 5, it is e−0.5≈0.607e^{-0.5} \approx 0.607 with γ=0.1\gamma = 0.1 and about 0.082 with γ=0.5\gamma = 0.5. Expanding the exponential as a power series shows that its feature map has infinitely many coordinates. With a small γ\gamma the boundary is nearly straight; with a large one it draws islands around single points.

Remark (Which functions are kernels?). A symmetric function is a dot product in some space exactly when all its Gram matrices are positive semi-definite. (Mercer, 1909; Aronszajn, 1950). The distance ∥x−z∥\lVert x - z \rVert fails: on two points at distance dd, its Gram matrix has the eigenvalue −d-d. Sums and products of kernels are kernels, which is how new ones are built safely.

Back to contents.

Kernel ridge, and kernels in practice

Kernel ridge is ridge regression rewritten with one weight per training point, which lets a kernel replace the dot product and still gives a closed-form answer.

Start from the closed-form ridge. The identity (X⊤X+λIp)X⊤=X⊤(XX⊤+λIn)(X^{\top}X + \lambda I_p)X^{\top} = X^{\top}(XX^{\top} + \lambda I_n) shows that β^=X⊤α\hat\beta = X^{\top}\alpha with one weight per training point. Predictions then involve only dot products xi⊤xx_i^{\top}x, which a kernel replaces (the representer theorem, Kimeldorf and Wahba, 1971):

α=(K+λI)−1y,f^(x)=∑i=1nαi k(xi,x),Kij=k(xi,xj)\alpha = (K + \lambda I)^{-1} y, \qquad \hat f(x) = \sum_{i=1}^{n} \alpha_i\, k(x_i, x), \qquad K_{ij} = k(x_i, x_j)
(9)

Unlike the SVM there is no sparsity: the loss is squared, so in general every αi\alpha_i is non-zero and the whole training set is kept. In exchange, fitting is one linear system, solved with np.linalg.solve rather than by inverting the matrix; with a linear kernel it must reproduce ridge to machine precision. In scikit-learn, KernelRidge calls λ\lambda alpha and fits no intercept.

Table 2: Kernel ridge by hand: inputs 0, 1, 2 with targets 0, 1, 0, γ=ln⁡2\gamma = \ln 2 (so k(x,z)=2−(x−z)2k(x, z) = 2^{-(x - z)^{2}}) and λ=1/2\lambda = 1/2. Every number is a fraction over 59.
Input xxTargetWeight αi\alpha_iPrediction f^(x)\hat f(x)
00−16/59-16/598/59 ≈ 0.136
1150/5950/5934/59 ≈ 0.576
20−16/59-16/598/59 ≈ 0.136
0.5 (new point)≈ 0.428

The two points with target 0 get negative weights: they pull the fit down around them. At x=1x = 1 the target is 1, but the penalty shrinks the fit to 0.576.

Table 3: Effect of γ\gamma on an RBF SVC with C=1C = 1, on scikit-learn's two-crescent toy data (make_moons, noise 0.3, 150 training points, 2,000 test points). The author's calculation.
Value of γ\gammaTrain accuracyTest accuracyReading
0.10.8730.844almost a straight line: underfits
10.9200.898follows the crescents
1000.9930.839islands around points: overfits

Raising CC pushes in the same direction as raising γ\gamma, and both are chosen by cross-validation on a grid in powers of 10. Standardise first: an RBF kernel adds squared gaps in each variable's units, so a credit limit in tens of thousands of dollars drowns an age in years and KK collapses to the identity. The scaler goes inside the pipeline, fitted on the training folds.

The price of the trick is the n×nn \times n matrix: 32 MB in double precision for 2,000 rows, 2.6 GB for the 18,000 training rows of the credit dataset, and a solve in about n3n^{3} operations. For large nn, random Fourier features (Rahimi and Recht, 2007) build DD random cosine columns whose dot products approximate the RBF kernel; a logistic regression on them scales in O(nD)O(nD) and, unlike SVC or KernelRidge, returns probabilities.

Back to contents.

Decision trees: the split that purifies most

A decision tree asks a chain of yes-or-no questions, one variable at a time, choosing each question so that the groups it creates are as homogeneous as possible.

A decision tree plays Guess Who: was the client at least two months late last month? Then a question on the credit limit, and so on, until a leaf predicts the share of defaults among the training clients that reach it. CART (Breiman, Friedman, Olshen and Stone, 1984) grows the tree greedily from the top: at each node it tries every variable and every threshold (the midpoints between sorted values), keeps the split that most lowers the weighted impurity of the children, then recurses.

G=1−∑kpk2,H=−∑kpklog⁡2pkG = 1 - \sum_k p_k^{2}, \qquad H = -\sum_k p_k \log_2 p_k
(10)
Δ(j,s)=I(t)−nLnt I(L)−nRnt I(R)\Delta(j, s) = I(t) - \frac{n_L}{n_t}\, I(L) - \frac{n_R}{n_t}\, I(R)
(11)

The Gini impurity GG measures how mixed a node is: pick two of its clients at random, with replacement, and it gives the chance that their classes differ; with two classes it equals 2p(1−p)2p(1-p), zero on a pure node and at most 1/21/2. Shannon entropy HH, in bits, comes from Quinlan's ID3 (1986) and C4.5 (1993); its reduction is the information gain. The two curves have the same shape and almost always choose the same split. scikit-learn uses Gini by default.

Table 4: Ten illustrative clients, four of them defaults. Split A asks PAY_0 ≥ 2 (at least two months late); split B asks AGE < 30.
NodeClientsDefaultsGiniEntropy (bits)
Parent1040.4800.971
A, late (left)430.3750.811
A, not late (right)610.2780.650
B, either side520.4800.971

Worked example: the gain of each split

  1. Parent. Four defaults out of ten, so p=0.4p = 0.4 and G=1−0.16−0.36=0.48G = 1 - 0.16 - 0.36 = 0.48.
  2. Children of A. Three defaults out of four on the left, G=1−9/16−1/16=6/16=0.375G = 1 - 9/16 - 1/16 = 6/16 = 0.375, and one out of six on the right gives G=10/36≈0.278G = 10/36 \approx 0.278.
  3. Weighted average. By counts, 0.4×0.375+0.6×0.278≈0.3170.4 \times 0.375 + 0.6 \times 0.278 \approx 0.317, so split A gains 0.48−0.317=0.1630.48 - 0.317 = 0.163. With entropy, the gain is 0.971−(0.4×0.811+0.6×0.650)≈0.2560.971 - (0.4 \times 0.811 + 0.6 \times 0.650) \approx 0.256, so A wins on both criteria.
  4. Split B. Each side has two defaults out of five, the parent's proportion, so both children have the parent's impurity and the gain is zero. A question that reproduces the parent's mix teaches nothing, whatever the variable.
  5. Check. DecisionTreeClassifier(max_depth=1) picks PAY_0 at the threshold 1.5, the midpoint between 1 and 2, and reports the same three impurities.

Back to contents.

Depth, pruning, instability and the bias of MDI

Left alone, a tree grows until it memorises the training set, so it has to be stopped or pruned, and its built-in importance scores must be read with suspicion.

By default (max_depth=None) scikit-learn grows the tree until every leaf is pure. A maximum depth, a minimum leaf size (min_samples_leaf) or a minimum gain stop it earlier; small leaves also give coarse probabilities.

The deck's simulation makes the point: one binary variable sets the default probability at 0.7 or 0.3, two others are noise, 1,000 rows to train and 1,000 to test, so no classifier can beat 0.70. A tree of depth 1 or 2 reaches 0.683 on test; an unlimited one scores 1.000 on train with 397 leaves and 0.549 on test, barely better than a coin.

Rα(T)=R(T)+α ∣T∣R_\alpha(T) = R(T) + \alpha\, |T|
(12)

Rather than stopping early, CART grows the full tree and then prunes it: R(T)R(T) is the training error, ∣T∣|T| the number of leaves and α\alpha a price per leaf, chosen by cross-validation (ccp_alpha in scikit-learn). The optimal subtrees are nested, so only a handful need testing.

Table 5: Cost-complexity pruning on the same simulation: leaves kept and cross-validated accuracy for four values of the leaf price. The author's calculation.
Leaves keptLeaf price ccp_alphaCV accuracy
39700.595
1440.0010.603
60.0020.689
20.0050.727

With the largest price, two leaves remain: one split, on the only useful variable. A short tree can be read aloud as a rule that a client can contest, which regulated credit values. It is also unstable: refit a depth-3 tree after dropping 5 % of the rows at random and the second level jumps to noise variables and new thresholds. Breiman's bagging (1996) starts from that observation and leads to the random forests and boosting of the next session.

MDI(j)=∑t : split on jntn Δt\mathrm{MDI}(j) = \sum_{t\,:\,\text{split on } j} \frac{n_t}{n}\, \Delta_t
(13)

scikit-learn's feature_importances_ is the mean decrease in impurity (MDI): the size-weighted gains of the splits on each variable, normalised to 1. It is free but biased twice over. It is measured on the training data, so splits that fitted noise count too; and a continuous variable offers hundreds of thresholds where a binary one offers one, hence many more lucky splits. On the unlimited tree of the simulation, MDI puts the continuous noise first (0.754) and the useful variable second (0.206); permutation importance on held-out data restores the order (Strobl et al., 2007).

Back to contents.

Key takeaways

  1. The SVM keeps the boundary with the widest margin, 2/∥w∥2/\lVert w \rVert, by minimising 12∥w∥2\tfrac12 \lVert w \rVert^{2} under one constraint per point; the soft margin adds a hinge loss priced by CC.
  2. In the dual, w=∑iαiyixiw = \sum_i \alpha_i y_i x_i and points outside the band have αi=0\alpha_i = 0, so only the support vectors shape the boundary.
  3. Because the dual sees the data only through dot products, any kernel with positive semi-definite Gram matrices can replace them; the RBF kernel's γ\gamma sets each point's reach.
  4. Kernel ridge solves α=(K+λI)−1y\alpha = (K + \lambda I)^{-1} y in one linear system but keeps every training point; standardise first, and approximate the kernel when nn is large.
  5. A tree picks each split by the largest drop in weighted impurity; a split that copies the parent's proportions gains nothing.
  6. An unlimited tree learns the noise, a short one is readable but unstable, and impurity-based importance favours variables with many thresholds.

Glossary

Support vector machine (SVM)
A classifier that keeps the boundary with the widest margin, softened by a price on violations.
Support vectors
The training points on or inside the margin; the only ones with a non-zero dual weight.
Hinge loss
The loss max⁡(0,1−yf(x))\max(0, 1 - y f(x)), zero for a point on the right side with a lead of at least 1.
Kernel trick
Replacing every dot product by a kernel, a dot product in a larger space computed without building it.
Gram matrix
The n×nn \times n matrix of kernel values on all pairs; positive semi-definite for a valid kernel.
Kernel ridge regression
Ridge in dual form with a kernel, one weight per training point.
Decision tree
A model of nested threshold questions on one variable at a time; each leaf is a box of the input space.
Gini impurity
The quantity 1−∑kpk21 - \sum_k p_k^{2}, the chance that two points drawn from a node have different classes.
Cost-complexity pruning
Growing the full tree, then keeping the subtree that minimises training error plus a price per leaf.
Mean decrease in impurity (MDI)
A tree's built-in importance, biased towards variables with many thresholds.

The other notes of the course

One public summary per deck, in the order of the course.

  1. IntroductionAI winters, jobs and method
  2. ToolsKaggle, GitHub, Python: the tools
  3. Session 1Project framing and least squares
  4. Session 2Maximum likelihood and logistic regression
  5. Session 3Gradient descent, ridge and lasso
  6. Session 4Decision threshold and reproducible ML
  7. HomeworkA defensible baseline model
  8. Session 5Kernels, SVM and decision trees
  9. Session 6Forests, boosting, honest comparison
  10. Session 7SHAP, fairness, PCA and clustering
  11. HomeworkA documented champion model
  12. Session 8Neural networks, drift, conformal prediction
  13. HomeworkA delivered machine learning project
  14. Session 9Defending a machine learning project
  15. ReferenceCredit default scoring project
  16. ReferenceAsset returns: XGBoost and sentiment
  17. ReferencePython code for every ML model
  18. ReferenceDeep learning essentials
  19. ReferenceOpen data ML projects by sector
  20. ReferenceData and AI engineer handbook
  21. ReferenceData engineering, SRE and cloud
  22. ReferencePanorama of machine learning models

All the notes, as a reading list

Attention and transformers, step by step

About these notes

Written by the lecturer from the slides of the deck, as a public summary: the key ideas, the formulas and one worked example. The exercises, their solutions, the tests and the grading stay in the deck, for the students of the course.

Revision: .