Sub topic 17
Training algorithms and how cost grows with data
This chapter assumes you know the soft-margin SVM, the dual problem, support vectors, and the kernel trick from earlier chapters. You should also be comfortable with Python, NumPy, and scikit-learn's fit and predict interface. Here we look at how SVMs are actually trained and why training time grows quickly as the number of samples increases.
Why training cost matters
The dual problem has one variable αi per training sample. The solver must find the α values that maximize the dual objective, subject to 0 ≤ αi ≤ C and Σ αi yi = 0. Every term in the objective involves the kernel value K(xi, xj) for a pair of samples. With n samples there are n² pairs, so cost grows at least with the size of the kernel matrix.
Two costs are worth separating:
- Training cost: finding the α values.
- Prediction cost: evaluating f(x) = Σ αi yi K(xi, x) + b. Only support vectors have αi > 0, so prediction costs one kernel evaluation per support vector.
A model with many support vectors is slow to fit and slow to predict. Noisy data, a large C, or a large gamma all tend to increase the number of support vectors.
The quadratic programming view
The dual is a quadratic program (QP) with n variables, a dense n × n matrix Q where Qij = yi yj K(xi, x_j), one equality constraint, and box constraints. A general-purpose QP solver would need to store Q and work with it directly. That takes O(n²) memory and often O(n³) time. For n = 100,000, Q has 10¹⁰ entries, which is about 80 GB in float64. General QP solvers are therefore not used for large SVMs.
Decomposition and SMO
Practical SVM solvers use decomposition. They keep most α values fixed and optimize a small working set at each step. Sequential Minimal Optimization (SMO) takes this to the extreme with a working set of exactly two variables.
Two variables are the minimum because of the equality constraint Σ αi yi = 0. Changing one α alone would break it, but changing two together can keep it satisfied. With two variables, the sub-problem has a closed-form solution, so no numerical QP solver is needed.
Each SMO iteration does the following:
- Select a pair (i, j) that violates the KKT conditions the most, using a heuristic.
- Solve for the new αi and αj analytically, clipping them to the box [0, C].
- Update the cached gradient (the error values) for all samples.
- Stop when the largest KKT violation falls below a tolerance.
scikit-learn's SVC uses libsvm, which implements an SMO-type method with second-order working-set selection. Its tol parameter (default 1e-3) sets the stopping tolerance.
Kernel caching and shrinking
Most of the time in an SMO iteration goes to computing kernel values. libsvm uses two techniques to reduce this work.
- Kernel cache: recently used rows of the kernel matrix are kept in memory, so repeated requests are cheap. The size is set by
cache_sizein scikit-learn, in MB (default 200). A larger cache can speed up training noticeably on bigger problems. - Shrinking: samples whose α sits at 0 or C and is unlikely to change are temporarily dropped from the active set. This shrinks the work per iteration. The solver checks the dropped samples at the end and restores them if needed. It is on by default (
shrinking=True).
How cost grows with n
For kernel SVMs from libsvm, empirical training time typically scales between O(n²) and O(n³), depending on the data and on C. Doubling the data can multiply the time by four or more. The number of support vectors also affects the result, since it determines how many kernel evaluations each prediction needs.
The script below measures this directly. Run it to see how the fit time of an RBF SVC grows with n.
import time
from sklearn.datasets import make_classification
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
for n in [1000, 2000, 4000, 8000]:
X, y = make_classification(
n_samples=n, n_features=20, n_informative=10, flip_y=0.05, random_state=0
)
X = StandardScaler().fit_transform(X)
clf = SVC(kernel="rbf", C=1.0, gamma="scale")
start = time.perf_counter()
clf.fit(X, y)
elapsed = time.perf_counter() - start
print(f"n={n:5d} fit={elapsed:6.2f}s support vectors={clf.n_support_.sum()}")Exact timings depend on your machine. The pattern to look for is that each doubling of n raises the time by more than a factor of two, and the support vector count rises along with n.
Linear SVMs have a different solver
A linear SVM does not need the kernel matrix. It can keep the primal weight vector w explicitly, which has only d entries for d features. Specialized solvers exploit this:
- Dual coordinate descent, used by liblinear. It updates one α_i at a time and maintains w incrementally, so each update costs O(d) for dense data, or proportional to the number of non-zero features for sparse data.
- Stochastic gradient descent (SGD) on the hinge loss. It processes one sample or a small batch at a time and scales to very large datasets.
In scikit-learn, LinearSVC uses liblinear, and SGDClassifier(loss="hinge") uses SGD. Their cost grows roughly linearly in n, which makes them practical for millions of samples and for sparse text features with many dimensions.
import time
from sklearn.datasets import make_classification
from sklearn.svm import LinearSVC, SVC
X, y = make_classification(n_samples=20000, n_features=50, random_state=0)
for name, model in [
("SVC(kernel='linear')", SVC(kernel="linear")),
("LinearSVC", LinearSVC(dual=False)),
]:
start = time.perf_counter()
model.fit(X, y)
print(f"{name:22s} fit={time.perf_counter() - start:6.2f}s")SVC(kernel="linear") goes through the kernel-based libsvm path. LinearSVC is usually much faster on large n, but the two differ slightly. LinearSVC penalizes the intercept by default and uses squared hinge loss by default, so the fitted models are not identical.
Practical options for large data
When a kernel SVM becomes too slow, you have several choices.
| Option | Idea | Trade-off |
|---|---|---|
| `LinearSVC` or `SGDClassifier` | Linear boundary with a linear-time solver | Cannot represent nonlinear boundaries on the raw features |
| Kernel approximation (`Nystroem`, `RBFSampler`) followed by a linear SVM | Map data to an explicit approximate feature space, then train linearly | Adds approximation error, plus a choice of number of components |
| Subsample the training set | Fit the kernel SVM on a subset | Loses information, so accuracy may drop |
| Tree ensembles or neural networks | Use a different model family | Different tuning and different inductive bias |
The kernel approximation route is a useful middle ground. The sketch below approximates an RBF kernel with 300 components and trains a linear SVM on the result.
from sklearn.datasets import make_moons
from sklearn.kernel_approximation import Nystroem
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC
X, y = make_moons(n_samples=5000, noise=0.25, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
model = make_pipeline(
StandardScaler(),
Nystroem(kernel="rbf", gamma=1.0, n_components=300, random_state=0),
LinearSVC(C=1.0, dual=False),
)
model.fit(X_train, y_train)
print("test accuracy:", model.score(X_test, y_test))Common pitfalls
- Slow convergence from unscaled features. Unscaled data makes the kernel values poorly conditioned, so the solver needs more iterations. Scale first, as covered earlier.
- Very large C. A large C allows the α values to grow big and pushes more points toward the margin. Training can become much slower. If the solver hits
max_iter, scikit-learn warns about non-convergence for the linear solvers. - Memory from a precomputed kernel. With
kernel="precomputed", you must supply the full n × n matrix. At n = 50,000 this alone needs about 20 GB in float64. - Tuning cost is multiplied. Grid search with 5-fold CV and 16 parameter pairs fits the model 80 times. Slow fits make this expensive, so tune on a subsample first.
- Expecting probabilities to be free.
SVC(probability=True)runs an internal 5-fold cross-validation to calibrate scores, which multiplies the training time by roughly five.
Summary of costs
| Method | Training cost (typical) | Memory | Prediction cost |
|---|---|---|---|
| Kernel SVM (libsvm, SMO) | Between O(n²) and O(n³) | Kernel cache, plus support vectors | O(n_SV × d) per sample |
| `LinearSVC` (liblinear) | Roughly O(n × d) per pass | O(n × d) data, O(d) weights | O(d) per sample |
| `SGDClassifier` (hinge) | O(n × d) per epoch | O(d) beyond the data | O(d) per sample |
Exercise
You have 500,000 rows with 100 features and need a linear decision boundary. A colleague proposes SVC(kernel="linear"). What would you use instead, and why? Also state what happens to prediction cost for a kernel SVM as the number of support vectors grows.
Show answer
Use LinearSVC (liblinear) or SGDClassifier(loss="hinge"). They store only the weight vector w and have training cost roughly linear in n, whereas SVC uses the libsvm kernel path, whose cost grows between O(n²) and O(n³) and which needs a kernel cache. For a kernel SVM, prediction needs one kernel evaluation per support vector, so prediction cost grows in proportion to the number of support vectors.
Exercise
Why does SMO optimize exactly two α values at a time rather than one?
Show answer
The dual has the equality constraint Σ αi yi = 0. Changing a single α_i would violate it. Changing two together can keep the constraint satisfied, and the two-variable sub-problem has a closed-form solution, so no numerical QP solver is needed in each step.