The line that leaves more room, and why it matters
A Support Vector Machine (SVM) separates two classes with the boundary that is as far as possible from both. If you split two groups of points on a sheet of paper, infinitely many lines work; the SVM chooses the one that leaves the widest corridor between the classes, the margin. The intuition is practical: a boundary that passes a hair away from the training data fails at the first new data point that is slightly noisier, one with a wide margin tolerates more. After decision trees, which draw staircase boundaries, SVMs are the first model in the series with smooth boundaries, even curved ones thanks to the kernel trick. It applies to classification, where you use SVC, and to regression, with SVR.
Support vectors: the few points that decide
The support vectors are the training points that determine the hyperplane: those lying exactly on the edge of the margin and, in the case of non-separable data, also those that ended up inside the margin or on the wrong side. A common inaccuracy is to say they are "only the points on the margin": with the soft margin they are also those that violate it. All the others, far from the boundary, can disappear without changing anything. This statement can be checked instead of believed, and that is what the listing does on the breast cancer dataset: it computes the signed distance of each point from the boundary (positive on the right side, and equal to 1 on the edge of the margin), checks that the points with distance at most 1 coincide with the scikit-learn support vectors, and then retrains using only those.
The first line of the output answers a question I will take up later: the same SVM with an RBF kernel, with and without StandardScaler. SVMs rely on distances between points, so a variable with values in the order of thousands crushes one in the order of units.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# First of all, why scaling is mandatory: same RBF kernel, with and without
rbf_senza = SVC(kernel="rbf").fit(X_train, y_train)
rbf_con = make_pipeline(StandardScaler(), SVC(kernel="rbf")).fit(X_train, y_train)
print(f"RBF without scaling: test {rbf_senza.score(X_test, y_test):.3f} with scaling: test {rbf_con.score(X_test, y_test):.3f}")
con = make_pipeline(StandardScaler(), SVC(kernel="linear", C=1.0)).fit(X_train, y_train)
scaler, svm = con[0], con[1]
Z = scaler.transform(X_train)
firmato = np.where(y_train == 1, 1, -1) * svm.decision_function(Z) # >= 1: outside the margin
TOL = 1e-3 # the tolerance of the SVC solver
sv_attesi = np.where(firmato <= 1 + TOL)[0]
print("support vectors per class:", svm.n_support_, "out of", len(Z), "samples")
print("coincide with the points at signed distance <= 1:", set(sv_attesi) == set(svm.support_))
print("of which inside the margin or on the wrong side:", int(np.sum(firmato < 1 - TOL)))
# Retrain keeping ONLY the support vectors: the hyperplane does not change
solo_sv = SVC(kernel="linear", C=1.0).fit(Z[svm.support_], y_train[svm.support_])
print("same predictions with the support vectors only:", bool(np.all(solo_sv.predict(Z) == svm.predict(Z))))
print("maximum difference between the coefficients:", float(np.abs(solo_sv.coef_ - svm.coef_).max()))
# Output:
# RBF without scaling: test 0.947 with scaling: test 0.982
# support vectors per class: [16 20] out of 455 samples
# coincide with the points at signed distance <= 1: True
# of which inside the margin or on the wrong side: 18
# same predictions with the support vectors only: True
# maximum difference between the coefficients: 0.0009094246134688788
Without scaling the test gives 0.947, with scaling 0.982: four points of accuracy lost just because of an omitted step, and it is the most common mistake with SVMs. Then the numbers on the linear model: 36 support vectors out of 455 samples (16 of one class and 20 of the other), that is 8% of the data. The comparison with the signed distance says they are exactly the points with distance at most 1, up to the tolerance of the solver (tol=1e-3, which is why the points on the edge come out at 1.0005 and not at 1); half of them, 18, are inside the margin or on the wrong side, and the other 18 are on the edge. Retraining with only the 36 points gives the same predictions on all 455 and coefficients that differ by less than 0.001: the other 419 samples were useless to the position of the boundary. This makes SVMs cheap at prediction time, but not at training time, which still has to look at all the data to find out which ones they are.
The C parameter: how much to tolerate errors
Real data are not perfectly separable, and for this reason the form used everywhere is the soft margin: some points are allowed to violate the margin, paying a penalty. The C parameter is the price of each violation. With a high C every error costs a lot, the margin narrows to classify the training set well and there is a risk of fitting the noise; with a low C errors are cheap, the margin widens and the model is smoother. The hard margin is the limiting case of infinite C and works only with separable data. For scikit-learn C is 1.0 if you do not write it, and its ideal value depends on the scale of the data and on the noise: there is no universal value. The listing tries six values on a logarithmic scale with a linear kernel and prints how many support vectors remain and the accuracies.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(" C support vectors train test")
for C in (0.001, 0.01, 0.1, 1, 10, 1000):
m = make_pipeline(StandardScaler(), SVC(kernel="linear", C=C)).fit(X_train, y_train)
print(f"{C:>6} {int(m[-1].n_support_.sum()):>14} {m.score(X_train, y_train):.3f} {m.score(X_test, y_test):.3f}")
# Output:
# C support vectors train test
# 0.001 218 0.938 0.956
# 0.01 105 0.967 0.974
# 0.1 53 0.982 0.982
# 1 36 0.987 0.956
# 10 30 0.991 0.965
# 1000 25 1.000 0.939
Read the table from top to bottom. With C = 0.001 the margin is very wide: 218 support vectors out of 455 (almost half of the data defines the boundary) and the training score is the worst, 0.938. Going up, the support vectors fall to 53, 36, 30, 25 and the training accuracy rises up to 1.000: with C = 1000 the model classifies all 455 training samples perfectly. On the test set the curve is instead non-monotonic: it rises to 0.982 with C = 0.1 and then falls to 0.939 with C = 1000. It is the signature of overfitting: the harder the model tries not to make mistakes on the training set, the more it loses on the rest. With only 114 test samples, 0.956 and 0.965 differ by one sample, so ignore the differences between C = 1 and C = 10 and look at the trend. To choose C you use cross-validation, as in the listing further on.
The kernel trick, with the numbers in hand
If the data have the shape of two half-moons, no line separates them. The idea of the kernel trick is to add dimensions in which they become separable by a plane, without paying the cost of actually computing those coordinates. A minimal example with two variables: the map φ(p) = (p₁², √2·p₁p₂, p₂²) takes the points from 2 to 3 dimensions. Computing the dot product between two mapped points is equivalent to computing, in the original space, (x·z)²: the kernel function gives the answer without building the map. The RBF (Gaussian) kernel, exp(-γ‖x−z‖²), corresponds to a map with infinitely many dimensions, which nobody could build, and that is why the trick really matters.
The listing verifies both equivalences with numbers, compares the RBF kernel written by hand with the scikit-learn rbf_kernel, and then puts the linear, polynomial and RBF kernels to the test on 500 half-moon points with noise 0.2, using five-fold cross-validation. The gamma parameter of the RBF is 0.5 in the numerical check, while SVC by default uses gamma='scale', computed from the data.
import numpy as np
from sklearn.datasets import make_moons
from sklearn.metrics.pairwise import rbf_kernel
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
# 1) The trick, verified: the kernel (x . z)^2 equals the dot product after an explicit map
def mappa(p): # from 2 dimensions to 3
return np.array([p[0] ** 2, np.sqrt(2) * p[0] * p[1], p[1] ** 2])
x, z = np.array([1.0, 2.0]), np.array([3.0, 0.5])
print("kernel (x.z)^2 :", (x @ z) ** 2)
print("map(x) . map(z) :", round(float(mappa(x) @ mappa(z)), 6))
print("RBF by hand and sklearn :", round(float(np.exp(-0.5 * np.sum((x - z) ** 2))), 6), rbf_kernel([x], [z], gamma=0.5)[0, 0].round(6))
# 2) Data shaped like two half-moons: no line separates them
X, y = make_moons(n_samples=500, noise=0.2, random_state=42)
for kernel in ("linear", "poly", "rbf"):
m = make_pipeline(StandardScaler(), SVC(kernel=kernel))
s = cross_val_score(m, X, y, cv=5)
print(f"kernel {kernel:6s} accuracy {s.mean():.3f} (+/- {s.std():.3f})")
# Output:
# kernel (x.z)^2 : 16.0
# map(x) . map(z) : 16.0
# RBF by hand and sklearn : 0.043937 0.043937
# kernel linear accuracy 0.854 (+/- 0.040)
# kernel poly accuracy 0.862 (+/- 0.019)
# kernel rbf accuracy 0.972 (+/- 0.007)
The first two lines print 16.0 both ways: the kernel and the dot product in the three-dimensional space coincide, and that is the "trick". The third line does the same for the RBF: 0.043937 by hand and with the library. Then the part that matters for choosing: the linear kernel gets 0.854, the polynomial one (degree 3 by default) 0.862, the RBF 0.972 with a standard deviation of just 0.007. For data with a curved structure the RBF is a good first attempt, while on high-dimensional and almost linear data, such as text and genomics, the linear kernel is enough and costs far less.
C and gamma together, with a test that does not look at the search
With the RBF there are two parameters. gamma is the inverse of the radius of influence of each point: a low gamma gives a smooth boundary that fades over the whole region (risk of underfitting), a high gamma creates narrow islands around each point (risk of overfitting). They are searched with a grid search with cross-validation, GridSearchCV. The listing does something many guides omit: it first separates the test set, runs the search on the training set only, and reports the accuracy on the test set that the search never saw. The best_score_ score is in fact the best among twenty combinations tried and therefore optimistic: it was chosen precisely because it was high. The last three lines keep C fixed at 1 and vary gamma, to see the effect alone.
from sklearn.datasets import make_moons
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = make_moons(n_samples=500, noise=0.2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
pipe = Pipeline([("scaler", StandardScaler()), ("svm", SVC(kernel="rbf"))])
griglia = {"svm__C": [0.1, 1, 10, 100], "svm__gamma": [0.01, 0.1, 1, 10, 100]}
ricerca = GridSearchCV(pipe, griglia, cv=5).fit(X_train, y_train) # the search sees only the train set
print("best parameters:", ricerca.best_params_)
print(f"cross-validation accuracy on train: {ricerca.best_score_:.3f}")
print(f"accuracy on unused test set: {ricerca.score(X_test, y_test):.3f}")
for gamma in (0.01, 1, 100):
m = Pipeline([("scaler", StandardScaler()), ("svm", SVC(C=1, gamma=gamma))]).fit(X_train, y_train)
print(f"C=1 gamma={gamma:>5}: train {m.score(X_train, y_train):.3f} test {m.score(X_test, y_test):.3f}")
# Output:
# best parameters: {'svm__C': 0.1, 'svm__gamma': 10}
# cross-validation accuracy on train: 0.975
# accuracy on unused test set: 0.970
# C=1 gamma= 0.01: train 0.845 test 0.860
# C=1 gamma= 1: train 0.980 test 0.970
# C=1 gamma= 100: train 0.998 test 0.940
The search chooses C = 0.1 and gamma = 10, with 0.975 in cross-validation and 0.970 on the never-used test set: the two close values say that the choice was not inflated. The three final lines show the trade-off with C = 1: gamma 0.01 underfits (0.845 on the training set and 0.860 on the test set, the boundary is too smooth to follow the half-moons), gamma 1 is fine (0.980 and 0.970), gamma 100 overfits (0.998 on the training set and 0.940 on the test set). Note that the two parameters interact: the best pair found has a high gamma and a low C, and this is normal, because a low C compensates for the excessive flexibility of a high gamma. That is why they are searched together and on a logarithmic scale.
More than two classes, probabilities and regression
SVMs are binary and scikit-learn extends them in two ways, which must be told apart because they are often confused. SVC internally uses the one-vs-one strategy: for N classes it trains N(N−1)/2 classifiers, one for each pair. The decision_function_shape parameter is 'ovr' by default, but it only changes the shape of the output, turning the pairwise scores into one score per class; training stays pairwise. LinearSVC, on the other hand, really uses one-vs-rest: one classifier per class against all the others. The listing shows it on the 10 digits of the load_digits dataset.
from sklearn.datasets import load_digits
from sklearn.svm import SVC, LinearSVC
X, y = load_digits(return_X_y=True) # 10 classes
Xs = X / 16.0 # pixels go from 0 to 16
svc = SVC(kernel="linear", decision_function_shape="ovo").fit(Xs, y)
print("SVC, ovo output, columns per sample:", svc.decision_function(Xs[:1]).shape[1], "(class pairs: 10*9/2)")
print("SVC, ovr output (only reorganized): ", SVC(kernel="linear").fit(Xs, y).decision_function(Xs[:1]).shape[1])
lin = LinearSVC(max_iter=10000).fit(Xs, y)
print("LinearSVC, rows of coef_ (one classifier per class):", lin.coef_.shape[0])
# Output:
# SVC, ovo output, columns per sample: 45 (class pairs: 10*9/2)
# SVC, ovr output (only reorganized): 10
# LinearSVC, rows of coef_ (one classifier per class): 10
With ten classes, SVC with 'ovo' output returns 45 columns per sample, as many as the pairs (10·9/2), while with the default output it returns 10 and LinearSVC has 10 rows of coef_, one per class. In practice the difference affects training time: the 45 classifiers of SVC each work on only two classes, so they are small, and LinearSVC is much faster on large datasets.
Two more clarifications. The SVM does not produce probabilities: with probability=True scikit-learn obtains them with Platt calibration, a logistic regression on the scores trained with an internal cross-validation; the guide warns that it is expensive on large datasets and that the probabilities may be inconsistent with the scores. The SVR, for regression, looks for a tube of width epsilon around the function: points inside the tube cost nothing, and those outside become support vectors.
When to choose an SVM
An SVM is a good choice with datasets from a few hundred to a few tens of thousands of examples, with many variables, and when you need a nonlinear boundary without building the interactions by hand. The scikit-learn guide warns that the training of SVC scales between O(features × samples²) and O(features × samples³), depending on the effectiveness of the cache: beyond a few tens of thousands of samples LinearSVC is better, or a boosted tree as in the article on ensembles. With very noisy data, where the classes overlap, the margin has little to offer.
What you can do now
You can verify that the support vectors are the only points that count, and recognize them even when they violate the margin. You can read the effect of C from the table of support vectors, and search C and gamma together without contaminating the test set. You know that an SVM always goes after a scaler, inside a Pipeline, and that the RBF kernel is a good starting point for curved data. The next article moves on to two algorithms based on proximity: K-Nearest Neighbors and clustering.
Frequently asked questions
Why do SVMs require scaling of the variables?
Because they rely on distances or dot products between points: a variable with very large values dominates the others. On the breast cancer dataset the RBF kernel goes from 0.947 to 0.982 on the test set by adding a StandardScaler.
How do you choose C and gamma in an SVM with an RBF kernel?
With a grid search with cross-validation (GridSearchCV) on values on a logarithmic scale, run on the training set only, and confirming the result on a test set never used in the search.
Sources
- scikit-learn User Guide: Support Vector Machines - one-vs-one in SVC, one-vs-rest in LinearSVC, Platt scaling and training complexity, consulted on 2026-11-12
- scikit-learn API: SVC - default values of C, kernel and gamma='scale', consulted on 2026-11-12
- scikit-learn API: rbf_kernel - the definition of the Gaussian kernel used in the numerical check, consulted on 2026-11-12
Commenti
Caricamento commenti...
Sign in to comment