ML Study Hub

Home / MLP / Week 8

Week 8 · SVMs in sklearn

Official syllabus line: Support Vector Machines using scikit-learn
About 90 minQuiz 2 material (see exam radar)BSCS2008 · Ashish Tendulkar
Before you start: MLP weeks 5-7 (classification in sklearn). MLT week 10 explains the maths of margins, support vectors and kernels.
Watch first: the animated story of this weekAbout 1-2 minutes of real 3D animation with a friendly voice. Pause any time.
Read the words of the video
  1. 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.
  2. 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.
  3. 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.
  4. 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

Think of it like this

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, SVC and SVR;
  • 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 l1 LinearSVC gives sparse weights.

Words you need

Words you need
  • Support vectors - the training points that define the boundary.
  • C - penalty for margin violations. Large C = strict = narrow margin = overfitting risk.
  • gamma - for RBF (and poly/sigmoid): how far one training point's influence reaches. Large gamma = very local = overfitting.
  • Kernel - 'linear', 'poly', 'rbf' (default), 'sigmoid'.
  • degree, coef0 - parameters of the polynomial kernel (γ⟨x,x′⟩+coef0)degree(\gamma\langle\mathbf x,\mathbf x'\rangle+\texttt{coef0})^{\texttt{degree}}.
  • ε\varepsilon (epsilon) - the width of the no-penalty tube in SVR.

Idea 1: The three classes

ClassBoundaryDefaultsGood for
LinearSVClinearC=1.0, penalty='l2', loss='squared_hinge', max_iter=1000large data sets, many features, text
SVClinear or non-linear via kernelsC=1.0, kernel='rbf', degree=3, gamma='scale', coef0=0small to medium data sets
SVRregressionC=1.0, kernel='rbf', epsilon=0.1smooth regression
  • Training time. LinearSVC grows roughly linearly with the number of examples; kernel SVC grows between quadratically and cubically, so it is impractical beyond tens of thousands of rows.
  • SVC(kernel="linear") is slower than LinearSVC but equivalent in spirit. (SGDClassifier(loss="hinge") is a third way to train a linear SVM, and the only one with partial_fit.)
  • Multiclass: SVC uses one-vs-one internally; LinearSVC uses 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):

ModelTrain acc.Test acc.Support vectors
LinearSVC (a straight line)0.8520.889
PolynomialFeatures(3) + LinearSVC(C=10)0.9290.922
SVC(kernel="poly", degree=3, coef0=1, C=5)0.9240.92253
SVC(rbf, gamma="scale", C=1)0.9100.90074

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 γ=1/(nfeatures⋅Var⁡(X))\gamma=1/(n_{\text{features}}\cdot\operatorname{Var}(X)); on standardised data with 2 features this equals 0.50.5. The RBF kernel is e−γ∥x−x′∥2e^{-\gamma\|\mathbf x-\mathbf x'\|^2}.

Idea 4: C and gamma change everything

Same moons data, RBF kernel:

gammaCTrainTestSupport vectorsDiagnosis
50.0010.5330.422197under-fit (tiny C: almost anything is allowed)
"scale" (0.5)10.9100.90074good
0.110.8520.90085smooth, a little stiff
510000.9900.86764over-fit (huge C)
10010.9900.822202over-fit (huge gamma: tiny islands around each point)
The idea

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 C or gamma underfits; too high overfits. Tune both together with GridSearchCV on 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 w=(0.743, −1.299)\mathbf w=(0.743,\,-1.299) so the margin width =2∥w∥=21.497=1.337=\frac2{\|\mathbf w\|}=\frac{2}{1.497}=1.337. 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 loss default is 'squared_hinge'; loss='hinge' is the plain SVM loss.
  • penalty='l2' (default) shrinks weights. penalty='l1' gives a sparse coef_ (many exact zeros) and needs dual=False. On a 20-feature problem with only 3 informative features, we got 0 zero weights with l2 and 8 with l1.
  • LinearSVC also 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 ε\varepsilon: 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 ε=0.05\varepsilon=0.05 we had 23 support vectors, with ε=0.3\varepsilon=0.3 only 4. C again controls how hard points outside the tube are punished.

Solved examples

Solved example: 1. Overfit or underfit?

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.

Solved example: 2. Margin from a trained linear SVM

Question. A trained linear SVM has coef_ = [[3, 4]]. What is the margin width?

Solution. ∥w∥=5\|\mathbf w\|=5, so the margin is 2∥w∥=0.4\frac2{\|\mathbf w\|}=\mathbf{0.4}.

Solved example: 3. Choose the class

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

Your turn: 1. Spot the dial

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.

Your turn: 2. Count the support vectors

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

10+12=2210+12=22 support vectors, so support_vectors_ has shape (22,4)(22,4).

Your turn: 3. Which is sparse?

Which LinearSVC setting produces a sparse coef_: penalty="l2", penalty="l1", dual=False, or neither?

Need a hint?

Recall the ℓ1\ell_1 corner.

Show the full solution

penalty="l1", dual=False. The ℓ1\ell_1 penalty zeroes out weights; ℓ2\ell_2 only shrinks them.

Your turn: 4. Why scale?

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.

Your turn: 5. SVR tube

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

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.

Watch out - real exam trap
  • SVM C is inverse regularisation: small C = more regularisation (same as logistic regression).
  • coef_ exists only for the linear kernel (and LinearSVC).
  • LinearSVC ≠\neq SVC(kernel="linear") in speed or loss (squared hinge by default).
  • Large gamma = narrow influence = overfitting.
  • l1 LinearSVC requires dual=False.
  • Don't forget to scale.

Quick quiz

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
Smaller C widens the margin and smaller gamma smooths the boundary.

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
LinearSVC scales roughly linearly with the data; kernel SVC scales poorly.

Which attribute lists the points that define the SVM boundary?

  • coef_
  • classes_
  • support_vectors_
  • feature_importances_
support_vectors_ holds the training points on or inside the margin.

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.
SVC gives scores by default and coef_ exists only for the linear kernel.

Recap

Remember this
  • LinearSVC (fast, large/sparse data; l1 →\to sparse), SVC (kernels; small/medium data), SVR (regression with an ε\varepsilon tube).
  • Scale first. Curvy boundaries: PolynomialFeatures+LinearSVC or kernel SVC(poly/rbf).
  • Large C or gamma ⇒\Rightarrow overfit; small ⇒\Rightarrow underfit. Tune both on a log grid.
  • support_vectors_, n_support_, dual_coef_; coef_ only for linear; margin =2/∥w∥=2/\|\mathbf w\|. SVC: no probabilities unless probability=True (slow).
Formulas to keep
  • Poly kernel (γ⟨x,x′⟩+coef0)degree(\gamma\langle\mathbf x,\mathbf x'\rangle+\texttt{coef0})^{\texttt{degree}}; RBF e−γ∥x−x′∥2e^{-\gamma\|\mathbf x-\mathbf x'\|^2}; gamma="scale" =1/(nfeat Var(X))=1/(n_{feat}\,\mathrm{Var}(X))
  • Margin =2/∥w∥=2/\|\mathbf w\|
  • Defaults: SVC(C=1, kernel="rbf", degree=3, gamma="scale", coef0=0); LinearSVC(C=1, penalty="l2", loss="squared_hinge"); SVR(epsilon=0.1)
Connected weeks (learn them together)

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