~/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.
Plan of the deck
- Maximum margin. The separating line furthest from the nearest points, written as a convex problem.
- Soft margin and the price C. Slack variables and the hinge loss, for data that no line separates.
- The dual and the support vectors. Lagrange multipliers, KKT conditions and a four-point example by hand.
- The kernel trick. Polynomial and RBF kernels, and Mercer's condition on valid kernels.
- Kernel ridge and practice. The closed form, a three-point example, and , scaling, the cost in , and a short lab.
- Decision trees and impurity. CART's greedy search, Gini and entropy, two candidate splits on ten clients.
- 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 and write . Rescaling and together leaves the boundary unchanged, so we set at the nearest points. Since a point lies at distance from the hyperplane, the band is wide, and widening it means shrinking . The result is a convex quadratic problem with a unique minimum (Cortes and Vapnik, 1995):
| Client | Position | Class | Lead | Role |
|---|---|---|---|---|
| 1 | (0, 0) | sound, | 5/3 | outside the band |
| 2 | (1, 0) | sound, | 1 | on the edge |
| 3 | (0, 1) | sound, | 1 | on the edge |
| 4 | (2, 2) | default, | 1 | on the edge |
| 5 | (3, 2) | default, | 5/3 | outside the band |
| 6 | (2, 3) | default, | 5/3 | outside the band |
The solution, which scikit-learn's SVC with a linear kernel and a very large also returns, has , so the band is wide: exactly the gap between the two dashed lines, measured along the normal . Three clients touch the band; they are the support vectors. The other three could move, or disappear, without the boundary changing.
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 , the amount by which it breaks the margin, and add to the objective. At the optimum each slack equals , so the constraints can be removed altogether:
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 , the same shape as ridge, with playing the role of . A small gives a wide margin and strong regularisation (risk of underfitting), a large a narrow margin and a risk of overfitting, as with the C of LogisticRegression.
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 to each constraint and subtract the constraints from the objective. Setting the gradient in to zero, then the derivative in , gives two identities. Substituting them back removes and and leaves a problem in alone:
With a soft margin, the only change is a cap . Complementary slackness, one of the Karush-Kuhn-Tucker (KKT) conditions, gives , so either the price is zero or the constraint is tight. A point classified correctly and outside the band has and vanishes from and from every prediction. That sparsity is why SVC keeps only its support_ points to predict.
Worked example: four clients on a line
- Data. Sound clients at and , defaults at and . The two inner points are the closest to the other class.
- Supports on the edge. Writing at and gives and . Adding them, , so , , and the boundary sits at .
- Outer points. At and the lead is , so the constraint is slack and, by complementary slackness, their price is zero.
- Prices. The condition forces the two remaining prices to be equal, say . Then , hence .
- Check. The primal value equals the dual value , and the margin is the distance from to . Moving the point at to changes nothing; moving the point at changes everything.
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 table of dot products , the Gram matrix, and prediction only . Points on a line with one class at both ends and the other in the middle cannot be split by one threshold, but after a horizontal line does it. A curved boundary is a flat one after a transformation , the feature map. The kernel trick computes straight from and , without building (Boser, Guyon and Vapnik, 1992).
For the degree-2 polynomial kernel in two dimensions, expanding the square and splitting the cross term into reveals the hidden map:
Check with and . The kernel side needs two products, a sum and a square: , so . The feature side builds and , whose dot product is . The general kernel contains every interaction up to degree for the price of one dot product and a power.
The Gaussian or RBF kernel (radial basis function) is 1 for identical points and fades with distance; sets how far each training point's influence reaches. For two points at squared distance 5, it is with and about 0.082 with . Expanding the exponential as a power series shows that its feature map has infinitely many coordinates. With a small 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 fails: on two points at distance , its Gram matrix has the eigenvalue . Sums and products of kernels are kernels, which is how new ones are built safely.
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 shows that with one weight per training point. Predictions then involve only dot products , which a kernel replaces (the representer theorem, Kimeldorf and Wahba, 1971):
Unlike the SVM there is no sparsity: the loss is squared, so in general every 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 alpha and fits no intercept.
| Input | Target | Weight | Prediction |
|---|---|---|---|
| 0 | 0 | 8/59 ≈ 0.136 | |
| 1 | 1 | 34/59 ≈ 0.576 | |
| 2 | 0 | 8/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 the target is 1, but the penalty shrinks the fit to 0.576.
| Value of | Train accuracy | Test accuracy | Reading |
|---|---|---|---|
| 0.1 | 0.873 | 0.844 | almost a straight line: underfits |
| 1 | 0.920 | 0.898 | follows the crescents |
| 100 | 0.993 | 0.839 | islands around points: overfits |
Raising pushes in the same direction as raising , 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 collapses to the identity. The scaler goes inside the pipeline, fitted on the training folds.
The price of the trick is the 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 operations. For large , random Fourier features (Rahimi and Recht, 2007) build random cosine columns whose dot products approximate the RBF kernel; a logistic regression on them scales in and, unlike SVC or KernelRidge, returns probabilities.
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.
The Gini impurity 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 , zero on a pure node and at most . Shannon entropy , 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.
| Node | Clients | Defaults | Gini | Entropy (bits) |
|---|---|---|---|---|
| Parent | 10 | 4 | 0.480 | 0.971 |
| A, late (left) | 4 | 3 | 0.375 | 0.811 |
| A, not late (right) | 6 | 1 | 0.278 | 0.650 |
| B, either side | 5 | 2 | 0.480 | 0.971 |
Worked example: the gain of each split
- Parent. Four defaults out of ten, so and .
- Children of A. Three defaults out of four on the left, , and one out of six on the right gives .
- Weighted average. By counts, , so split A gains . With entropy, the gain is , so A wins on both criteria.
- 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.
- Check.
DecisionTreeClassifier(max_depth=1)picksPAY_0at the threshold 1.5, the midpoint between 1 and 2, and reports the same three impurities.
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.
Rather than stopping early, CART grows the full tree and then prunes it: is the training error, the number of leaves and a price per leaf, chosen by cross-validation (ccp_alpha in scikit-learn). The optimal subtrees are nested, so only a handful need testing.
| Leaves kept | Leaf price ccp_alpha | CV accuracy |
|---|---|---|
| 397 | 0 | 0.595 |
| 144 | 0.001 | 0.603 |
| 6 | 0.002 | 0.689 |
| 2 | 0.005 | 0.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.
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).
Key takeaways
- The SVM keeps the boundary with the widest margin, , by minimising under one constraint per point; the soft margin adds a hinge loss priced by .
- In the dual, and points outside the band have , so only the support vectors shape the boundary.
- 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 sets each point's reach.
- Kernel ridge solves in one linear system but keeps every training point; standardise first, and approximate the kernel when is large.
- A tree picks each split by the largest drop in weighted impurity; a split that copies the parent's proportions gains nothing.
- 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 , 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 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 , 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.
Previous: A defensible baseline modelNext: Forests, boosting, honest comparison
- IntroductionAI winters, jobs and method
- ToolsKaggle, GitHub, Python: the tools
- Session 1Project framing and least squares
- Session 2Maximum likelihood and logistic regression
- Session 3Gradient descent, ridge and lasso
- Session 4Decision threshold and reproducible ML
- HomeworkA defensible baseline model
- Session 5Kernels, SVM and decision trees
- Session 6Forests, boosting, honest comparison
- Session 7SHAP, fairness, PCA and clustering
- HomeworkA documented champion model
- Session 8Neural networks, drift, conformal prediction
- HomeworkA delivered machine learning project
- Session 9Defending a machine learning project
- ReferenceCredit default scoring project
- ReferenceAsset returns: XGBoost and sentiment
- ReferencePython code for every ML model
- ReferenceDeep learning essentials
- ReferenceOpen data ML projects by sector
- ReferenceData and AI engineer handbook
- ReferenceData engineering, SRE and cloud
- ReferencePanorama of machine learning models
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: .