Chapter 7: Support Vector Machines
Master Support Vector Machines, one of the most elegant algorithms in machine learning. Learn how SVMs find optimal separating hyperplanes with maximum margin, handle non-separable data with soft margins, and tackle non-linear problems through the powerful kernel trick.
- Topics
- 5
- Demos
- 4
- Min read
- 52
Chapter Overview
Support Vector Machines represent a beautiful intersection of geometry, optimization, and learning theory. The core idea is elegantly simple: among all hyperplanes that separate two classes, choose the one with the maximum margin to the nearest training points.
This maximum margin principle has deep theoretical justification—it maximizes the geometric separation between classes, leading to better generalization. The points that lie exactly on the margin boundaries are called support vectors, and remarkably, only these points determine the decision boundary.
Real-world data is rarely perfectly separable, so soft margin SVMs allow some violations by introducing slack variables. The regularization parameter C controls the trade-off: high C penalizes misclassifications heavily (narrow margin, potential overfitting), while low C allows more errors (wide margin, potential underfitting).
The true power of SVMs comes from the kernel trick, which enables learning non-linear decision boundaries without explicitly computing high-dimensional feature mappings. By using kernel functions that compute inner products in transformed spaces, SVMs can learn complex patterns while remaining computationally tractable.
This chapter covers:
- Maximum Margin: The geometric intuition behind finding the optimal separating hyperplane
- Soft Margin: Handling overlapping classes with slack variables and the C parameter
- Kernel Trick: Using RBF, polynomial, and other kernels to learn non-linear boundaries
- Practical SVM: Feature scaling, hyperparameter tuning, and when to use SVMs
- SVR: Adapting the SVM framework for regression with ε-insensitive loss
Chapter Roadmap
Click any topic to jump in
Maximum Margin
The geometric insight — find the separating hyperplane with the widest gap to nearest points.
Two extensions that make SVMs practical
Soft Margin SVM
Handle overlapping classes with slack variables and the C parameter for real-world data.
Kernel Trick
Learn non-linear boundaries by computing inner products in high-dimensional spaces implicitly.
Classification pipelines and regression adaptation
Practical SVM
Feature scaling, hyperparameter tuning, multi-class strategies, and when to choose SVMs.
Support Vector Regression
Adapt the SVM margin framework to regression with the epsilon-insensitive loss tube.
Topics
5 topics in this chapter
The previous chapter, Ensemble Methods, built strong classifiers by averaging many trees. Now we return to a single linear boundary and ask a sharper question. When two classes can be separated by a straight line, infinitely many lines do it perfectly on the training set. Logistic regression picks one by maximizing likelihood, and the perceptron stops at whichever separating line it reaches first. Which of these lines should we trust on new data? A line that grazes a training point will misclassify a test point that lands slightly to the wrong side of it.
Support Vector Machines answer with a geometric principle: choose the boundary that stays as far as possible from the nearest training points of both classes. This topic builds that idea step by step. We define a hyperplane, then two ways to measure a point's distance from it, the functional and geometric margins, and see why only the second is meaningful. We then meet the support vectors, the few points that pin the boundary, write the hard-margin optimization problem, and close with why a wide margin generalizes better.
Definition
A linear support vector machine classifies with the sign of . Among all hyperplanes that separate the training data, the hard-margin SVM chooses the one that maximizes the margin, the distance between the two parallel boundaries , subject to every point lying on its correct side.
In this topic
- 1Hyperplane
- 2Functional Margin
- 3Geometric Margin
- 4Support Vectors
- 5Hard Margin SVM
- 6Why Maximum Margin?
Hyperplane
A hyperplane is the set of points with : a line in 2D, a plane in 3D, and a flat -dimensional surface in dimensions. The weight vector is normal (perpendicular) to it and sets its orientation; the bias shifts it away from the origin. The classifier predicts when and otherwise. The signed distance of a point from the hyperplane is . This is the same linear score used by logistic regression in the Classification chapter; SVMs differ only in how they choose and .
The hyperplane partitions into two half-spaces. The normal vector is perpendicular to the hyperplane, and is the signed distance from the origin. The sign of determines which side of the hyperplane a point falls on. In 2D this is a line, in 3D a plane, and in D a -dimensional affine subspace — the geometry is the same regardless of dimensionality.
w=[2,1], b=-3. Is point (2,1) on positive or negative side?
Functional Margin
The functional margin of training point is , where the label is or . Multiplying by the label makes it positive exactly when the point is classified correctly, and larger values suggest more confidence. Its flaw is scale: replacing with for any describes the same hyperplane but multiplies every functional margin by . Maximizing it directly is therefore meaningless, since doubling always wins. SVMs fix this by normalizing, either dividing by or requiring the closest points to have functional margin exactly 1.
The functional margin is positive when the point is correctly classified and its magnitude reflects confidence. However, replacing with doubles the functional margin without changing the hyperplane — the margin is not scale-invariant. This is why we need to normalize by to get a geometrically meaningful quantity, or equivalently constrain the optimization so that .
y=+1, wᵀx+b=5. Functional margin? If we double w and b?
Geometric Margin
The geometric margin is a true distance, unaffected by rescaling and . SVMs fix the scale by requiring for all points, with equality for the closest ones. Those points then sit on the parallel planes , each at distance from the decision boundary, so the full width of the empty band between the classes is , the formula above. A wider margin requires a smaller . This turns the geometric goal, a widest band, into an algebraic one: minimize the norm of the weights.
The geometric margin is the perpendicular distance between the two margin boundaries . Maximizing is equivalent to minimizing , transforming a geometric problem into a convex quadratic program. The factor of is a convention that simplifies the gradient to instead of . Larger margins correspond to smoother decision boundaries with better generalization — this is formalized by VC dimension theory.
||w|| = 2. What's the margin width?
Support Vectors
Support vectors are the training points that lie exactly on the margin planes, where . In the dual form of the optimization, each point gets a weight and the solution is . Points strictly outside the margin get , so only support vectors shape the boundary. Delete any other point, retrain, and the hyperplane is unchanged. This sparsity is what makes SVMs distinctive: logistic regression gives every point some influence. The flip side is sensitivity: move or mislabel a single support vector and the whole boundary shifts.
Support vectors are the training points where the constraint is active (equality holds). By the KKT complementarity conditions, non-support vectors have dual variables and contribute nothing to . This sparsity means the solution depends only on the hardest-to-classify points. Removing any non-support vector does not change the optimal hyperplane — the SVM is effectively determined by a small subset of the data.
1000 training points. SVM has 15 support vectors. How many points actually matter?
Hard Margin SVM
s.t.
The hard-margin SVM combines the previous concepts into one problem: minimize subject to for every training point. The objective is a convex quadratic and the constraints are linear, so this is a quadratic program with a single global optimum and no local minima. The squared norm is minimized instead of maximizing because it is smooth and convex; the factor just tidies the gradient. Its fatal weakness is the requirement of perfect separability: one overlapping or mislabeled point makes the constraints impossible to satisfy, and an outlier near the boundary can drastically narrow the margin.
The hard margin optimization s.t. is a convex quadratic program with linear constraints. Strong duality holds (Slater's condition), so the dual gives the same solution. The dual depends only on inner products — this is the foundation for the kernel trick.
Data has one mislabeled point making classes overlap. Hard margin SVM?
Why Maximum Margin?
Why should the widest band generalize best? Intuitively, test points are perturbed versions of training points. If every training point is at least half the margin width from the boundary, small perturbations cannot push them across. Formally, statistical learning theory bounds the capacity of large-margin classifiers: for data inside a ball of radius , the VC dimension of hyperplanes with margin is bounded by roughly , regardless of the number of features. A wide margin therefore limits complexity even in very high dimensions, which is why SVMs work well on text. The bound depends on scale, so it presumes the features are standardized.
VC theory gives the formal justification. With probability , test error is at most training error plus a term of order . For hyperplanes that separate data lying in a ball of radius with distance at least from every point to the boundary, , which does not grow with the ambient dimension once is the smaller term. Maximizing the margin shrinks this capacity term, which explains why maximum-margin classifiers can generalize in very high-dimensional spaces, provided features are scaled so that is meaningful.
Margin A: 0.1 units. Margin B: 2 units. New point is 0.5 units from boundary. Which classifies correctly?
Theory Exercise
Problem:
In a trained SVM, you have 3 support vectors out of 100 training points. What happens to the decision boundary if you remove a non-support-vector point?
Hints:
- What determines the decision boundary?
- Are all training points equally important?
- Think about the optimization solution
Coding Exercise
Problem:
Train a hard(ish)-margin linear SVM on a linearly separable 2D dataset, then inspect which training points became support vectors. Confirm that only the support vectors define the boundary by checking how few there are relative to the dataset.
Hints:
- Use sklearn.svm.SVC(kernel='linear', C=1e6) to approximate a hard margin
- After fitting, clf.support_vectors_ holds the support vectors and clf.support_ holds their indices
- clf.coef_ and clf.intercept_ give w and b of the hyperplane
Related Problems on PixelBank
The previous topic, Linear SVM and Maximum Margin, built a clean optimization problem with one unrealistic assumption: the two classes must be perfectly separable by a hyperplane. Real data almost never cooperates. Measurement noise, mislabeled examples, and genuinely overlapping classes mean that a single bad point makes the hard-margin problem infeasible. Even when separation is possible, one outlier near the boundary can force a very narrow margin and a fragile classifier.
The soft-margin SVM, introduced by Cortes and Vapnik in 1995, keeps the large-margin idea but lets individual points break the rules at a price. This topic starts with slack variables, which measure how far each point violates its margin constraint, and then the soft-margin objective, which trades a wide margin against total violation. The regularization parameter C controls that trade-off, and choosing it is the main tuning decision for linear SVMs. Finally we rewrite the whole problem as an unconstrained loss, the hinge loss, which connects SVMs to logistic regression and gradient-based training.
Definition
The soft-margin SVM minimizes subject to and . The slack measures how far point violates its margin, and the constant sets the price of each unit of violation relative to margin width. Equivalently, it minimizes the hinge loss plus an L2 penalty.
In this topic
- 1Slack Variables
- 2Soft Margin Objective
- 3C Parameter
- 4Hinge Loss
Slack Variables
A slack variable relaxes point 's constraint to . Its value describes where the point lands. : on or beyond its own margin plane, no violation. : inside the margin but still on the correct side of the boundary. : exactly on the decision boundary. : on the wrong side, misclassified. At the optimum , so each misclassified point contributes more than 1 and the total slack upper-bounds the number of training errors.
Each slack variable measures how much point violates the margin constraint. The relaxed constraint with creates a continuous spectrum: (correct, outside margin), (correct, inside margin), (on the boundary), (misclassified). The total slack upper-bounds the number of training errors, providing a convex proxy for the 0-1 loss.
Point has ξ=0.3. Another has ξ=1.5. What's happening to each?
Soft Margin Objective
The soft-margin objective adds a penalty to the hard-margin one: rewards a wide margin, and charges for every unit of violation. The two terms pull in opposite directions. Shrinking widens the margin, which usually puts more points inside it and raises total slack. The problem remains a convex quadratic program, and it is always feasible, since large enough slacks satisfy every constraint. In the dual, the only change from the hard margin is a cap on each weight, , so no single point, including an outlier, can dominate the solution.
The objective is equivalent to minimizing the regularized hinge loss: . The first term controls margin width (), the second penalizes margin violations. This is a convex optimization problem with a unique global minimum. The parameter plays the same role as the inverse regularization strength in ridge regression.
||w||²=4, Σξ=2. Loss at C=1? At C=10?
C Parameter
C sets the exchange rate between margin width and violations, playing the role of an inverse regularization strength, like in ridge regression. Large C makes violations expensive, so the optimizer narrows the margin to classify nearly every training point correctly: low bias, high variance, and as the hard margin returns. Small C tolerates violations for a wide, smooth margin: high bias, low variance, and at very small C the model can collapse to predicting the majority class. Because the scale of C depends on the data size and feature scaling, it must be tuned by cross-validation over a logarithmic grid such as 0.01 to 1,000.
The parameter controls the bias-variance trade-off: recovers the hard margin (fewest training errors, narrow margin, high variance), while makes violations free (very wide margin, high bias). The number of support vectors usually falls as grows: with small the margin is wide and many points sit inside it, so many become support vectors, while with large the margin narrows and fewer points touch it. In the dual formulation, upper-bounds each : the constraint prevents any single point from having unbounded influence.
C=0.001: 75% train acc, 74% test. C=1000: 99% train, 65% test. Diagnosis?
Hinge Loss
Substituting the optimal slack turns the constrained problem into an unconstrained one: minimize with the hinge loss above. The loss is zero once a point is correct with functional margin at least 1, and grows linearly as falls below 1. It is a convex upper bound on the 0-1 loss. Compared with logistic regression's log loss , which is never exactly zero, hinge loss ignores well-classified points entirely, and that is the source of SVM sparsity. The unconstrained form also allows training with stochastic gradient descent.
The hinge loss is a convex upper bound on the 0-1 loss. Its sub-gradient is when and otherwise — making it piecewise linear and computationally efficient. The kink at corresponds to the margin boundary. Unlike log-loss (logistic regression) which always has non-zero gradient, hinge loss has exactly zero gradient for well-classified points — this is why SVMs produce sparse solutions with few support vectors.
y=+1. Predictions: f(x)=2, f(x)=0.5, f(x)=-1. Hinge loss for each?
Theory Exercise
Problem:
You have a dataset where a linear SVM with C=1 gives 85% accuracy and has 50 support vectors. With C=100, accuracy is 90% but there are 150 support vectors. Which model would you deploy and why?
Hints:
- What does the number of support vectors indicate?
- Consider overfitting vs underfitting
- Think about the margin width
Coding Exercise
Problem:
On a dataset with overlapping classes, sweep the C parameter across several orders of magnitude and observe how the number of support vectors and the train/test accuracy gap change. Identify which C balances fit and generalization.
Hints:
- Generate slightly overlapping classes (e.g. make_classification with class_sep small)
- Loop C over [0.01, 0.1, 1, 10, 100] and refit SVC(kernel='linear', C=C)
- Track len(clf.support_), clf.score(Xtr, ytr) and clf.score(Xte, yte) for each C
Related Problems on PixelBank
The previous topic, Soft Margin SVM, made linear SVMs robust to noise, but the boundary is still a straight line. Many problems are not linearly separable even in principle: points of one class surrounded by a ring of the other, or two interleaving crescents. The classic fix is to add features, such as squares and products of the originals, so that a curved boundary in the original space becomes a hyperplane in the expanded one. The catch is size. All degree-2 products of 1,000 features already give over 500,000 features, and higher degrees explode further.
The kernel trick removes that cost. The SVM dual problem touches the data only through inner products between pairs of points, so if a function can compute the inner product in the expanded space directly from the original vectors, the expansion never has to be built. This topic defines kernel functions and explains why they work, then surveys the standard kernels: linear, polynomial, the RBF or Gaussian kernel with its crucial gamma parameter, and the sigmoid kernel and its pitfalls.
Definition
A kernel is a function equal to the inner product under some feature map . The kernel trick replaces every inner product in an algorithm, such as the SVM dual, with , fitting a linear model in the feature space without ever computing . A valid kernel's Gram matrix must be positive semi-definite.
In this topic
- 1Kernel Function
- 2Why Kernels Work
- 3Linear Kernel
- 4Polynomial Kernel
- 5RBF (Gaussian) Kernel
- 6Gamma Parameter (RBF)
- 7Sigmoid Kernel
Kernel Function
A kernel function takes two input vectors and returns a number equal to , the inner product after mapping both through a feature map . The point is that is computed from the original vectors, often in time, while might have millions or infinitely many dimensions. Not every function qualifies: Mercer's condition requires that, for any set of points, the Gram matrix of pairwise kernel values be symmetric positive semi-definite. A valid kernel can be read as a similarity measure, large for similar points, and kernels can be combined, since sums and products of valid kernels are valid.
A kernel computes the inner product in a (potentially infinite-dimensional) feature space without explicitly computing . By Mercer's theorem, any positive semi-definite function is a valid kernel — meaning there exists some feature space where the kernel equals the inner product. The computational savings are enormous: the RBF kernel implicitly maps to infinite dimensions but costs only operations to evaluate.
φ(x) maps to 1M dimensions. Computing φ(x)·φ(x') directly?
Why Kernels Work
Kernels work because of how the SVM solution is written. In the dual problem the training data enter only as inner products , and the decision function is , a weighted sum over support vectors. Replacing each inner product with fits a maximum-margin hyperplane in the feature space while every computation stays in the input space. The cost moves from the feature dimension to the number of samples: training needs kernel values between pairs of points, and prediction needs one kernel value per support vector. That trade is excellent for moderate and poor for millions of points.
The SVM dual formulation depends only on pairwise kernel evaluations. The decision function also uses only kernel evaluations. Since we never need explicitly — only — we can work in infinite-dimensional spaces at finite computational cost. This is the representer theorem: the optimal solution lies in the span of kernel evaluations at training points.
RBF kernel maps to infinite dimensions. How is this computationally feasible?
Linear Kernel
The linear kernel uses the identity feature map, so it gives exactly the linear SVM of the previous topics. Its advantages are speed and simplicity: the model collapses to a single weight vector, prediction costs , and specialized solvers such as LIBLINEAR train on millions of sparse examples. It is the right choice when the number of features is large relative to the number of samples, as in text classification with bag-of-words features. In that regime the data are usually close to linearly separable already, so a nonlinear kernel adds cost and hyperparameters without adding accuracy. It cannot fit curved boundaries in low-dimensional data.
The linear kernel makes no transformation at all — is the identity. Despite its simplicity, it is optimal for high-dimensional sparse data (like text with TF-IDF features) where . In this regime, the data is often already linearly separable in the original space. Computational cost is per kernel evaluation, and the decision function is just , making inference extremely fast.
Text classification: 50,000 word features, 1,000 documents. Linear or RBF?
Polynomial Kernel
The polynomial kernel corresponds to a feature space containing all monomials of the inputs up to degree . The degree sets the flexibility: 2 gives quadratic boundaries such as ellipses, 3 gives cubic ones. The constant (coef0 in scikit-learn) weights lower-degree terms against the top-degree ones; with only degree- products remain. The feature count grows as for inputs, which explains the kernel's value. In practice high degrees are numerically unstable, since values far from 1 explode or vanish when raised to a high power, so degrees above 3 or 4 are rare.
The polynomial kernel maps to a feature space of dimension , containing all monomials up to degree . For : — 6 features from 2. The kernel computes the inner product in this space with just operations instead of . The coef0 controls the balance between high-degree and low-degree terms.
2 features, degree=2 polynomial. How many features in transformed space?
RBF (Gaussian) Kernel
The radial basis function (RBF) kernel measures similarity by distance: 1 for identical points, decaying toward 0 as they move apart, with setting how fast. Its feature space is infinite-dimensional, as a Taylor expansion of the exponential shows, and it can approximate any smooth boundary. The decision function becomes a weighted sum of Gaussian bumps centered on the support vectors, so the model behaves like a smart nearest-neighbor method. It is the usual default for nonlinear SVMs. It needs scaled features, since distances drive everything, and it extrapolates poorly: far from all support vectors, every kernel value is near zero.
The RBF kernel maps to an infinite-dimensional feature space via the Taylor expansion: . Each term is a polynomial kernel of degree , so the RBF kernel spans all polynomial features simultaneously. The parameter controls the bandwidth — how far each support vector's influence reaches.
x=[0,0], x'=[1,0], γ=1. What's K(x,x')?
Gamma Parameter (RBF)
Gamma sets the reach of each support vector's influence, roughly in distance units. Large gamma makes each Gaussian bump narrow, so the boundary can wrap around individual points: low bias, high variance, and eventually memorization, with nearly every point a support vector. Small gamma makes the bumps wide, and the boundary becomes smooth, approaching a linear one: high bias, low variance. scikit-learn's default gamma='scale' uses , which adapts to the feature scale. Gamma interacts with C, so the two must be tuned together on a logarithmic grid, typically to , with cross-validation.
Gamma is an inverse squared length scale for each support vector's influence. At , for all pairs: the kernel matrix approaches all-ones and the model cannot distinguish points. At , for every distinct pair, so the kernel matrix approaches the identity, each point forms its own island, and the model memorizes the training set. A good makes comparable to typical squared pairwise distances. The default does this: for standardized data the expected squared distance between two points is , so is about 2 on average.
γ=0.001: decision boundary is almost linear. γ=1000: boundary hugs each point. Best γ?
Sigmoid Kernel
The sigmoid kernel was inspired by neural networks: an SVM with this kernel resembles a two-layer network with tanh hidden units. Its weakness is that it is not a valid Mercer kernel for most settings of and : the Gram matrix can have negative eigenvalues, so the optimization is no longer convex, and solvers may converge to poor or unstable solutions. Lin and Lin found that it behaves acceptably only in a restricted region, with and , where it acts much like the RBF kernel. In practice it rarely beats RBF, and modern neural networks have replaced its motivation.
The sigmoid kernel resembles a two-layer neural network with tanh hidden units. However, it is not positive semi-definite for most combinations: the kernel matrix can have negative eigenvalues, violating Mercer's condition, so the dual problem is no longer guaranteed convex and the solver may return a poor local solution. Lin and Lin (2003) showed that it behaves reasonably mainly when is small and , where it acts much like the RBF kernel; even then it is not PSD in general, so RBF is the safer choice.
Want to try sigmoid kernel. Any concerns?
Theory Exercise
Problem:
Your RBF SVM with γ=0.1 has 90% train accuracy, 85% test accuracy. With γ=10, train accuracy is 99%, test accuracy drops to 70%. What's happening?
Hints:
- Compare train vs test gaps
- What does high gamma mean geometrically?
- Think about overfitting
Coding Exercise
Problem:
Generate a dataset that is NOT linearly separable (two concentric circles) and compare a linear-kernel SVM against an RBF-kernel SVM. Show that only the RBF kernel can separate the classes.
Hints:
- Use sklearn.datasets.make_circles for non-linearly-separable data
- Fit SVC(kernel='linear') and SVC(kernel='rbf', gamma='scale') on the same data
- Compare cross-validated accuracy of the two kernels
Related Problems on PixelBank
The previous topic, Kernel Trick, gave SVMs nonlinear power, and with it more ways to fail. A kernel SVM trained on raw, unscaled features with default hyperparameters often performs worse than a plain logistic regression, and an SVM trained on a few hundred thousand rows may simply never finish. The theory is elegant, but practical success depends on a short list of habits that experienced practitioners apply every time.
This topic collects those habits. It starts with feature scaling, the step most often forgotten, and why distance-based kernels make it mandatory. Next come the joint behavior of C and gamma, and a coarse-to-fine grid search strategy for tuning them together. We then look at when an SVM is the right tool at all, and how training cost grows with the number of samples, which decides between kernel SVMs, linear solvers, and other model families. The topic closes with two output issues: turning SVM scores into calibrated probabilities with Platt scaling, and extending a binary classifier to many classes with one-vs-rest or one-vs-one schemes.
Definition
Practical SVM use means standardizing features, choosing a kernel (linear for high-dimensional sparse data, RBF otherwise), and tuning C and gamma jointly with cross-validated grid search on logarithmic scales. It also means respecting kernel training cost, which grows roughly quadratically in sample count, calibrating scores when probabilities are needed, and combining binary SVMs for multiclass problems.
In this topic
- 1Feature Scaling is Critical
- 2C and Gamma Interaction
- 3Grid Search Strategy
- 4When to Use SVM
- 5SVM Complexity
- 6Probability Outputs
- 7Multi-class Strategy
Feature Scaling is Critical
SVMs are distance-based: the RBF kernel uses , and even the linear margin is measured in feature units. A feature measured in large units, such as income in dollars, contributes squared differences millions of times larger than one measured in small units, such as age in years, and the kernel effectively ignores the small one. Standardizing each feature to zero mean and unit variance, or min-max scaling, puts features on equal footing. Fit the scaler on the training data only, ideally inside a Pipeline so cross-validation does not leak test statistics. Tree models from earlier chapters do not need this; SVMs do.
SVM margin computation uses Euclidean distance . Without scaling, a feature with range contributes to the distance while a feature with range contributes — the small feature becomes invisible. Standardization () equalizes contributions. The kernel function is also affected: an RBF kernel with optimized for unscaled features will behave completely differently after scaling.
Features: age (20 to 80 years) and income (20,000 to 200,000 dollars). RBF SVM without scaling?
C and Gamma Interaction
C and gamma both control complexity, and they interact. Gamma sets how wiggly the boundary can be; C sets how hard the optimizer fits every point. High C with high gamma gives a boundary that wraps tightly around individual points, severe overfitting. Low C with low gamma gives a nearly linear, heavily regularized boundary, underfitting. Good settings often lie along a diagonal ridge in the plane of log C against log gamma: a smaller gamma can be offset by a larger C. Tuning one at a time can miss the best pair, so search them jointly.
The parameters form a 2D trade-off surface. controls how many margin violations are tolerated (model complexity via slack). controls decision boundary complexity (feature space dimensionality). Their interaction is multiplicative: high + high = complex boundary with zero tolerance = severe overfitting. The optimal region typically lies along a diagonal ridge in the plane, which is why grid search over logarithmic scales is standard.
Fixed C=1, tuned γ: best is γ=0.1 (85%). Now tune C with γ=0.1: C=10 gives 87%. Done?
Grid Search Strategy
Because good C and gamma values can lie anywhere across several orders of magnitude, search on a logarithmic scale. A practical recipe from the LIBSVM authors is coarse to fine. First evaluate a coarse grid such as C in 0.1, 1, 10, 100 and gamma in 0.001, 0.01, 0.1, 1 with k-fold cross-validation. Then search a finer grid centered on the best cell. If the winner sits on the edge of the grid, extend the grid in that direction before refining. Each grid point costs k fits. Randomized search or Bayesian optimization, covered in Model Evaluation, are alternatives when there are more hyperparameters.
A fine grid over has combinations; with 5-fold CV that is model trainings. Coarse-to-fine search reduces this: a coarse grid (80 trainings) identifies the best region, then a fine grid around the winner (125 trainings) refines it, 205 in total, about a quarter of the cost. Because the validation surface over is usually smooth, this two-stage approach rarely misses the optimum, as long as the coarse winner is not on the grid's edge.
Coarse grid: best at C=10, γ=0.1. Next step?
When to Use SVM
SVMs shine on small to medium datasets, up to tens of thousands of samples, where a clear margin exists and features are informative. They are especially strong in high-dimensional sparse settings such as text, where a linear SVM is a classic baseline that is hard to beat, and in domains with good similarity measures that can be written as custom kernels. They are weaker when samples number in the millions, where kernel training cost explodes, when calibrated probabilities are central, and on heterogeneous tabular data with mixed types and missing values, where gradient-boosted trees usually win with less preprocessing. Neural networks dominate raw images, audio, and text at scale.
Kernel SVM training solves a QP with variables (one per sample), which needs up to memory for the kernel matrix and roughly to time. For beyond about this becomes prohibitive. Linear SVMs avoid the kernel matrix: the primal form has only parameters, and stochastic sub-gradient methods such as Pegasos reach accuracy in about steps of cost each, independent of . The sweet spot for kernel SVMs is up to tens of thousands of samples.
5000 samples, text classification (10K features). SVM or Random Forest?
SVM Complexity
to training
Kernel SVM training, typically with the SMO algorithm used by LIBSVM and scikit-learn's SVC, scales between about and in the number of samples , depending on the data, C, and cache size. The kernel matrix alone has entries: 0.8 GB in float64 for 10,000 samples and 80 GB for 100,000. Prediction costs one kernel evaluation per support vector, which can also be slow when there are many. Beyond roughly 10,000 to 100,000 samples, switch to linear solvers (LinearSVC, or SGDClassifier with hinge loss), which scale about linearly, or approximate the kernel with Nystroem or random Fourier features and train a linear model on top.
The standard SMO algorithm for kernel SVM has time complexity in practice, with worst-case . The kernel matrix requires storage — at , that is GB for float64. Approximation methods like the Nystr"om method approximate using landmark points, reducing cost to time and storage. Random Fourier Features provide another approximation.
10K samples: SVM takes 10 min. 100K samples: how long?
Probability Outputs
An SVM outputs a score , a signed distance from the boundary, not a probability. Platt scaling converts scores to probabilities by fitting a sigmoid on held-out data, with and chosen to minimize log loss. In scikit-learn, probability=True does this with an internal 5-fold cross-validation, which makes training noticeably slower, and predict_proba can occasionally disagree with predict near the boundary. CalibratedClassifierCV gives explicit control and offers isotonic regression for larger datasets. If you only need a ranking, such as for ROC AUC, the raw decision_function scores are enough.
SVMs output the signed score , not a probability. Platt scaling fits a sigmoid to the SVM outputs on held-out data, choosing and to minimize cross-entropy; scikit-learn's probability=True does this with internal 5-fold cross-validation. The sigmoid assumes a particular shape for the score distribution, so the result can be miscalibrated when that shape is wrong. CalibratedClassifierCV defaults to the same sigmoid method but also offers isotonic regression, which is non-parametric and more flexible, though it needs more calibration data to avoid overfitting.
Need P(spam) for ranking, not just 0/1. SVM outputs f(x)=2.5. Probability?
Multi-class Strategy
SVMs are binary classifiers, so classes need a combination scheme. One-vs-rest (OvR) trains classifiers, each separating one class from all others, and predicts the class with the highest score; the subproblems are imbalanced and use all samples. One-vs-one (OvO) trains classifiers, one per pair of classes, each on only about samples, and predicts by voting. Because kernel training is superlinear in , many small OvO problems are often cheaper than a few large OvR ones. scikit-learn's SVC uses OvO internally; LinearSVC uses OvR. Accuracy is usually similar, as Hsu and Lin found.
One-vs-Rest (OvR) trains binary SVMs, each separating class from the rest. One-vs-One (OvO) trains SVMs, each separating a pair of classes. OvO is sklearn's default for SVC because each classifier trains on only samples (faster per classifier), though the total classifiers makes it slower for large . The decision function combines votes or confidence scores — ambiguous regions where classifiers disagree are resolved by the highest aggregate score.
10-class problem. OvR vs OvO: how many classifiers?
Theory Exercise
Problem:
You have 1 million samples with 100 features. Would you use SVM with RBF kernel? Why or why not? What alternatives would you consider?
Hints:
- Consider SVM training complexity
- Think about scalable alternatives
- What about linear SVMs?
Coding Exercise
Problem:
Build a proper SVM pipeline with feature scaling, then use GridSearchCV to tune C and gamma together. Demonstrate that scaling + joint tuning beats an unscaled default SVC.
Hints:
- Wrap StandardScaler and SVC in a Pipeline so scaling is fit inside each CV fold
- Grid over svc__C and svc__gamma on logarithmic scales
- Compare the tuned pipeline's best score to a plain unscaled SVC()
Related Problems on PixelBank
The previous topic, Practical SVM Usage, covered how to scale, tune, and deploy SVM classifiers. Many real problems are regression instead: predicting a price, a temperature, or a demand level. Can the margin idea, which made SVM classifiers robust, carry over when the target is a continuous number and there is no boundary between classes? Ordinary least squares penalizes every residual, no matter how tiny, and squares large ones, so a few outliers can dominate the fit.
Support Vector Regression (SVR), developed by Vapnik and colleagues in the mid-1990s, turns the margin into a tube. Points whose residual is within a tolerance epsilon of the prediction cost nothing; only points outside the tube are penalized, and only linearly. This topic starts with that epsilon-insensitive loss, then writes the SVR objective with its two sets of slack variables, examines how the epsilon parameter trades accuracy for sparsity, and finishes with kernel SVR, which reuses the kernels of the classification topics to fit nonlinear functions. The same tuning habits apply: scale features and tune C, epsilon, and gamma.
Definition
Support Vector Regression fits by minimizing , where slacks measure how far each target lies above or below a tube of half-width around the prediction. Residuals inside the tube cost nothing; only points on or outside it become support vectors.
In this topic
- 1ε-Insensitive Loss
- 2SVR Objective
- 3ε Parameter
- 4SVR Kernels
ε-Insensitive Loss
The epsilon-insensitive loss is zero whenever the prediction is within of the target and grows linearly beyond that. It combines two ideas. The dead zone of width means small errors, often just noise, are ignored, which is what makes SVR sparse: points inside the tube do not affect the model. The linear growth outside, like absolute error, means large residuals and outliers have bounded influence on the gradient, unlike squared error, where a single residual of 10 counts 100 times as much as a residual of 1. It is the regression analog of the hinge loss.
The -insensitive loss is zero inside the tube and linear outside. This creates a flat region in the loss landscape where the gradient is exactly zero — points inside the tube do not influence the model at all. Compared to squared error (which penalizes every deviation), this provides natural robustness to noise. The loss is a shifted absolute value function, making SVR equivalent to regression outside the tube.
ε=0.5, y=10. Predictions: f(x)=10.3, f(x)=10.8, f(x)=11.5. Losses?
SVR Objective
SVR minimizes subject to and , with all slacks nonnegative. measures how far a target lies above the tube and how far below; at most one is positive for any point. The norm term prefers flat functions, a form of regularization, and C prices points that escape the tube. The dual solution is , where only points on or outside the tube have nonzero coefficients. These are SVR's support vectors.
The SVR objective uses two slack variables per point: for points above the tube () and for points below (). Only points outside the tube have non-zero slack, and these become the support vectors. The solution depends only on support vectors — the model is sparse, ignoring the majority of training points that fall within the tube.
100 points: 80 inside ε-tube, 20 outside. What contributes to loss?
ε Parameter
Epsilon sets the half-width of the tube and therefore the size of residual the model treats as noise. A larger epsilon puts more points inside the tube, giving fewer support vectors, a sparser and faster model, and a flatter fit; too large and the tube swallows real signal and the model underfits. A smaller epsilon makes nearly every point a support vector and fits more closely, including noise. Epsilon is in the same units as the target, so a natural starting point is a fraction of the noise standard deviation, or the error tolerance that matters for the application. Cherkassky and Ma proposed for noise level .
Epsilon controls the tube width: larger means more points fall inside (zero loss, not support vectors), producing a sparser, flatter model, and the number of support vectors generally falls as grows. Cherkassky and Ma (2004) proposed , where is the noise standard deviation and the sample size: it scales with the noise level and shrinks as more data pin down the function. For and this gives about 0.067. Too small an fits noise with many support vectors; too large misses the signal.
ε=0.1: RMSE=0.2, 500 SVs. ε=1.0: RMSE=0.8, 50 SVs. Which to choose?
SVR Kernels
Kernels work in SVR exactly as in classification: replace inner products with , and the prediction becomes a weighted sum of kernel values at the support vectors. A linear kernel fits a hyperplane, a polynomial kernel fits polynomial trends, and the RBF kernel fits smooth arbitrary curves as a sum of Gaussian bumps. The kernel's inductive bias matters most outside the training range. A linear model extrapolates its trend, while an RBF prediction decays toward the intercept far from all support vectors, because every kernel value there is near zero. Choose the kernel to match the expected shape, and tune C, epsilon, and gamma jointly.
Kernel SVR replaces the linear prediction with , enabling non-linear regression. The same kernels apply: linear for simple trends, polynomial for polynomial relationships, RBF for arbitrary smooth functions. The -tube now forms a band around the non-linear prediction surface in the input space. The RBF kernel with appropriate can approximate any continuous function to arbitrary precision (universal approximation).
Predicting house prices. Relationship with sqft is linear. SVR kernel?
Theory Exercise
Problem:
You fit an SVR with epsilon=0.5 and get 300 support vectors out of 1000 points. You then increase epsilon to 2.0 and the number of support vectors drops to 40. Explain why, and describe the trade-off you are making.
Hints:
- Which points become support vectors in SVR?
- What does epsilon control geometrically?
- Think about the relationship between tube width and model flexibility
Coding Exercise
Problem:
Fit an RBF Support Vector Regressor to a noisy sine curve and visualize (numerically) how the epsilon-insensitive tube behaves: report the number of support vectors and the fit error, then show that raising epsilon reduces the support-vector count.
Hints:
- Generate y = sin(x) + noise and scale is fine since x is small; use SVR(kernel='rbf')
- After fitting, len(svr.support_) gives the number of support vectors
- Refit with a larger epsilon and compare support-vector counts and RMSE