Week 8 · SVMs in sklearn
Read the words of the video
- Imagine a playground with two teams of kids, red and blue. A Support Vector Machine, or SVM, helps find the widest possible empty road separating these two groups. Only the kids standing right at the very edges of this road truly matter for defining its path. These special kids are called support vectors.
- Now, imagine three types of vehicles for finding these roads. LinearSVC finds a fast, straight road, great for lots of data. SVC can find curvy roads using special tricks. SVR builds a 'tube' for predicting numbers. Remember one hard rule: always scale your features first! Think of it as making all your measurements fair.
- C and gamma are like steering wheels. C controls how much you punish mistakes onto the road. If C is very large, the road gets very wiggly and tries to classify every point perfectly, risking overfitting. If gamma is large, the curves become very local. Tune them carefully to find the perfect balance.
- For your exams, always remember: scale your features! A small C means more regularisation and a wider road, helping prevent overfitting. LinearSVC with 'l1' penalty gives sparse, simpler models. We learned about LinearSVC, SVC, SVR, and how C and gamma steer your model to find the best separation.
The one-minute story
Remember the playground road? An SVM finds the widest empty road between two groups, and only the kids at the road's edge (support vectors) matter. The maths was last term's job (MLT week 10). This week is about driving the machine in scikit-learn: three classes, a handful of dials, and one hard rule: scale your features.
Your three vehicles:
LinearSVC: a fast, straight road. Great for huge data and text.SVC: a road that can curve, using the kernel trick (polynomial or RBF). Slower, for small and medium data.SVR: the same idea for regression (a "tube" around the data).
And two dials do most of the steering: C (how much you punish cars that stray onto the road) and gamma (how local a curvy kernel is).
By the end of this week you can:
- choose between
LinearSVC,SVCandSVR; - set
C,kernel,degree,gamma,coef0, and predict what each does; - read
support_vectors_,n_support_,coef_and compute the margin; - explain why SVMs need scaled features and why
l1LinearSVCgives sparse weights.
Words you need
- Support vectors - the training points that define the boundary.
C- penalty for margin violations. LargeC= strict = narrow margin = overfitting risk.gamma- for RBF (and poly/sigmoid): how far one training point's influence reaches. Largegamma= very local = overfitting.- Kernel -
'linear','poly','rbf'(default),'sigmoid'. degree,coef0- parameters of the polynomial kernel .- (epsilon) - the width of the no-penalty tube in
SVR.
Idea 1: The three classes
| Class | Boundary | Defaults | Good for |
|---|---|---|---|
LinearSVC | linear | C=1.0, penalty='l2', loss='squared_hinge', max_iter=1000 | large data sets, many features, text |
SVC | linear or non-linear via kernels | C=1.0, kernel='rbf', degree=3, gamma='scale', coef0=0 | small to medium data sets |
SVR | regression | C=1.0, kernel='rbf', epsilon=0.1 | smooth regression |
- Training time.
LinearSVCgrows roughly linearly with the number of examples; kernelSVCgrows between quadratically and cubically, so it is impractical beyond tens of thousands of rows. SVC(kernel="linear")is slower thanLinearSVCbut equivalent in spirit. (SGDClassifier(loss="hinge")is a third way to train a linear SVM, and the only one withpartial_fit.)- Multiclass:
SVCuses one-vs-one internally;LinearSVCuses one-vs-rest (week 7). - No probabilities by default. SVMs output scores (
decision_function).SVC(probability=True)can calibrate probabilities by running an extra internal cross-validation: slow.
Idea 2: Always scale
Distances and dot products drive an SVM, so a feature with big numbers dominates the margin. Put a StandardScaler first, in a pipeline:
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
model = make_pipeline(StandardScaler(), SVC(kernel="rbf", C=1, gamma="scale"))
Idea 3: Curvy boundaries two ways
(a) Add features yourself, then use a linear SVM:
make_pipeline(PolynomialFeatures(3), StandardScaler(), LinearSVC(C=10, max_iter=20000))
(b) Use the kernel trick (no explicit new features):
SVC(kernel="poly", degree=3, coef0=1, C=5) # polynomial kernel
SVC(kernel="rbf", gamma=0.5, C=1) # Gaussian / RBF kernel
Option (b) avoids the explosion in the number of features (high degrees are cheap), while (a) can be slower or impossible as the degree and number of features grow. We tried both on the "two moons" data set (300 points with noise, 70/30 split):
| Model | Train acc. | Test acc. | Support vectors |
|---|---|---|---|
LinearSVC (a straight line) | 0.852 | 0.889 | |
PolynomialFeatures(3) + LinearSVC(C=10) | 0.929 | 0.922 | |
SVC(kernel="poly", degree=3, coef0=1, C=5) | 0.924 | 0.922 | 53 |
SVC(rbf, gamma="scale", C=1) | 0.910 | 0.900 | 74 |
The straight line underfits the curved moons; both polynomial routes fix it.
coef0 controls how much the polynomial kernel is influenced by high-degree vs low-degree terms (a constant added inside). gamma="scale" (the default) means ; on standardised data with 2 features this equals . The RBF kernel is .
Idea 4: C and gamma change everything
Same moons data, RBF kernel:
gamma | C | Train | Test | Support vectors | Diagnosis |
|---|---|---|---|---|---|
| 5 | 0.001 | 0.533 | 0.422 | 197 | under-fit (tiny C: almost anything is allowed) |
"scale" (0.5) | 1 | 0.910 | 0.900 | 74 | good |
| 0.1 | 1 | 0.852 | 0.900 | 85 | smooth, a little stiff |
| 5 | 1000 | 0.990 | 0.867 | 64 | over-fit (huge C) |
| 100 | 1 | 0.990 | 0.822 | 202 | over-fit (huge gamma: tiny islands around each point) |
How to steer (increase / decrease means to reduce overfitting):
C: decrease it (more regularisation, wider margin, more violations allowed).gamma: decrease it (smoother, less wiggly boundary).degree: decrease it.- Too low a
Corgammaunderfits; too high overfits. Tune both together withGridSearchCVon a logarithmic grid like[0.01, 0.1, 1, 10, 100].
Notice the support-vector counts: the under-fit and very-local models use lots of support vectors (about 200 of 210 training points), while a neat model uses far fewer.
Idea 5: Looking inside
svc = SVC(kernel="linear", C=1).fit(X_train_scaled, y_train)
svc.support_vectors_.shape # (74, 2): the 74 points that define the road
svc.n_support_ # [38, 36]: how many per class
svc.dual_coef_.shape # (1, 74): alpha_i * y_i for each support vector
svc.coef_, svc.intercept_ # the weights: ONLY for kernel="linear"
On our scaled moons data so the margin width . For non-linear kernels coef_ does not exist; predictions use dual_coef_ and support_vectors_. Only the support vectors matter: you could delete every other point and the fitted model would not change.
Idea 6: LinearSVC details and sparsity
- The
lossdefault is'squared_hinge';loss='hinge'is the plain SVM loss. penalty='l2'(default) shrinks weights.penalty='l1'gives a sparsecoef_(many exact zeros) and needsdual=False. On a 20-feature problem with only 3 informative features, we got 0 zero weights withl2and 8 withl1.LinearSVCalso penalises the bias and benefits from scaling more than most.
Idea 7: SVR (regression)
SVR fits a function surrounded by a tube of half-width : errors inside the tube are free; only points on or outside the tube become support vectors. A wider tube (larger epsilon) means fewer support vectors and a smoother fit: with we had 23 support vectors, with only 4. C again controls how hard points outside the tube are punished.
Solved examples
Question. An RBF SVC gets train accuracy 0.99 and test accuracy 0.80. What would you change?
Solution. The big gap says overfitting. Reduce C and/or reduce gamma (and make sure the features are scaled), then re-check with cross-validation.
Question. A trained linear SVM has coef_ = [[3, 4]]. What is the margin width?
Solution. , so the margin is .
Question. (a) 500,000 emails, text features (sparse, 100,000 words). (b) 2,000 patients, 15 numeric features, a curved boundary. (c) Predict a house price from 5 features with a smooth curve.
Solution. (a) LinearSVC (large and sparse; linear is enough). (b) SVC(kernel="rbf") with scaling and tuned C, gamma. (c) SVR.
Your turn
You see a very wiggly boundary around single points. Which of these should go down: C, gamma, both, or neither?
Need a hint?
Think about which makes the kernel local.
Show the full solution
Both can be reduced: a huge gamma makes tiny islands around points and a huge C forces every training point to be classified correctly. Lower either (try gamma first), tuning on a log grid.
After training, svc.n_support_ is [10, 12]. How many support vectors? What shape is support_vectors_ if there are 4 features?
Need a hint?
Add the per-class counts.
Show the full solution
support vectors, so support_vectors_ has shape .
Which LinearSVC setting produces a sparse coef_: penalty="l2", penalty="l1", dual=False, or neither?
Need a hint?
Recall the corner.
Show the full solution
penalty="l1", dual=False. The penalty zeroes out weights; only shrinks them.
Feature A is in rupees (10,000s) and feature B in years (10s). Without scaling, what happens in an RBF SVM?
Need a hint?
The kernel uses distances.
Show the full solution
Distances are dominated by feature A, so feature B is practically ignored and the boundary depends almost only on A. Scaling puts both on the same footing.
Increasing epsilon in SVR makes the number of support vectors go which way?
Need a hint?
Wider tube means more points inside it.
Show the full solution
Down: more points fall inside the tube (no penalty, not support vectors), giving a simpler model (23 vs 4 support vectors in our test).
Exam radar
MLP Quiz 2 (the SVM weeks): "l1 penalty in LinearSVC leads to coef_ vectors which are ... (sparse)", pipeline questions with an SVM classifier (scaler + SVC), "for a text-classification task which snippet is better suited" (LinearSVC on a sparse vectoriser output, not RBF SVC). The End Term asks which settings give the largest regularisation / lowest overfitting (small C, small gamma), and the effect of kernel parameters.
Remember: small C = more regularisation for SVMs, and an SVM without scaling is almost always a mistake.
- SVM
Cis inverse regularisation: smallC= more regularisation (same as logistic regression). coef_exists only for the linear kernel (andLinearSVC).LinearSVCSVC(kernel="linear")in speed or loss (squared hinge by default).- Large
gamma= narrow influence = overfitting. l1LinearSVCrequiresdual=False.- Don't forget to scale.
Quick quiz
To reduce overfitting in an RBF SVC you should...
- increase C and increase gamma
- decrease C and/or decrease gamma
- remove scaling
- increase degree
Which scikit-learn SVM class is best for a very large sparse text data set?
- LinearSVC
- SVC with rbf kernel
- SVR
- SVC with poly kernel
Which attribute lists the points that define the SVM boundary?
- coef_
- classes_
- support_vectors_
- feature_importances_
Select all TRUE statements. (select all that apply)
- A LinearSVC with penalty l1 can give a sparse coef_.
- SVMs should be trained on scaled features.
- SVC outputs class probabilities by default.
- coef_ is available for every kernel.
Recap
LinearSVC(fast, large/sparse data;l1sparse),SVC(kernels; small/medium data),SVR(regression with an tube).- Scale first. Curvy boundaries:
PolynomialFeatures+LinearSVCor kernelSVC(poly/rbf). - Large
Corgammaoverfit; small underfit. Tune both on a log grid. support_vectors_,n_support_,dual_coef_;coef_only for linear; margin . SVC: no probabilities unlessprobability=True(slow).
- Poly kernel ; RBF ;
gamma="scale" - Margin
- Defaults:
SVC(C=1, kernel="rbf", degree=3, gamma="scale", coef0=0);LinearSVC(C=1, penalty="l2", loss="squared_hinge");SVR(epsilon=0.1)
- MLT week 10 - Support vector machines: SVMs: the theory, then the code.
Practise with real exam questions
These come straight from past papers (with the real figures and the official answer key). Open 22 real questions on this week All Quiz 2 papers