Asiman Data School

Module 3, topic 35, week 18, Tuesday

Support Vector Machines and Voting - Classification

The widest street between two classes: the margin and the support vectors by hand, the soft margin and C, the kernel trick and the four kernels, every hyperparameter; then a vote of the SVM with the models of earlier topics, hard and soft, on raw credit data from the first line of preprocessing to the bank's cost.

Introduction: the widest street, and a vote

The fifteenth lesson of Module 3. A decision tree asks questions, k-nearest neighbours looks at the closest rows, Naive Bayes multiplies probabilities. A support vector machine (SVM) does something else again: it looks for the widest possible street between the two classes, and decides by the side of the street a new row falls on. It was the strongest all-round model of the late 1990s and 2000s, and it is still one of the best models for medium-sized data with many features.

The second half of the lesson brings the models of the whole module together. Voting lets several different models decide together, like a panel of experts: each model gives its answer, and the panel's answer is the majority (hard voting) or the average of their probabilities (soft voting).

The lesson has two steps. On paper: what an SVM is and when it is used, the widest street worked by hand with six loan applicants, the soft margin and its hyperparameter C, the kernel trick and the four kernels, all the hyperparameters, and what preprocessing an SVM needs. Then one project on a new data file, german_credit.csv: 1,000 loan applicants of a German bank, from the raw file to an SVM and its scores, then voting with the models of earlier topics, all in the same notebook on the same data.

You need: logistic regression (Topic 27), the measures of Topic 28, decision trees and random forests (Topics 29 and 30), k-nearest neighbours (Topic 32), Naive Bayes (Topic 34), scaling and encoding (Topics 24 and 25), and the train/test split with cross-validation (Topic 23).

What you will learn

  1. 1.What a support vector machine is, where and when it is used, and its strengths and weaknesses
  2. 2.The widest street: the separating line, the margin and the support vectors, worked by hand
  3. 3.The soft margin: why C decides between a wide street with some mistakes and a narrow street with none
  4. 4.The kernel trick, and how the linear, polynomial, RBF and sigmoid kernels draw their borders
  5. 5.Every hyperparameter of SVC and its role: C, kernel, gamma, degree, coef0, class_weight, probability and the rest
  6. 6.Why scaling is essential for an SVM, and the preprocessing of this and the coming models
  7. 7.Voting: why several models can be better than one, hard voting and soft voting, and VotingClassifier
  8. 8.A whole project on credit data: from the raw file to an SVM, its measures and its tuning, then the models of earlier topics and their vote
The words of this lesson
WordMeaning
Support vector machine (SVM)a model that separates the classes by the widest possible street
Hyperplanethe separating border: a line in two dimensions, a plane in three, a "hyperplane" in more
Marginthe width of the street between the classes
Support vectorsthe training rows on the edge of the street (or inside it): only they decide where the border lies
Soft margina street that allows some rows inside it or on the wrong side, controlled by C
Kernela function that measures how similar two rows are; it lets the SVM draw curved borders
Hard votingeach model votes for a class; the class with the most votes wins
Soft votingthe probabilities of the models are averaged; the class with the larger average wins

1What a support vector machine is

1.1The idea: the widest street

Imagine the loan applicants of a bank as points on a sheet of paper, good applicants on one side and bad ones on the other. Many lines can separate them. Which one is best? An SVM chooses the line with the largest distance to the nearest points of both classes: the line in the middle of the widest street that fits between the classes.

Why the widest street? A line that only just passes the training points will misjudge new applicants that are a little different. A line with a wide margin on both sides leaves room for new rows that do not look exactly like the old ones: it generalises better.

Only the points on the edge of the street matter: they support the street, like pillars, and are called the support vectors. All the other points could move (without crossing the edge) and the street would stay exactly where it is.

1.2Where SVMs are used

  • Banking and insurance: credit scoring, fraud detection (the project of this lesson).
  • Medicine and biology: classifying tumours from thousands of gene measurements, protein classification. With many features and few rows SVMs are among the best models.
  • Images: handwritten digit recognition, face detection (an SVM on image features was the standard face detector for years).
  • Text: sorting documents and emails by topic, spam filtering; texts have thousands of word columns, where SVMs do well (the NLP topics, from Topic 49 on).
  • Industry: detecting faulty products from sensor readings.

1.3When to use an SVM

When to use an SVM
SituationSVM?
Hundreds to tens of thousands of rowsyes: its strength
Many features, even more features than rowsyes: it works well in high dimensions
A clear gap between the classesyes: the widest street finds it
Millions of rowsno: training grows roughly with the square of the rows; use LinearSVC, a linear model or boosting
You need exact probabilitieswith care: they need probability=True and are an add-on
You must explain each decisionnot with curved kernels: a tree or logistic regression is easier to explain

1.4Strengths and weaknesses

Strengths and weaknesses
StrengthsWeaknesses
Works well with many features, also more features than rowsSlow on large data sets: the training time grows fast with the number of rows
The widest street resists overfitting when C is chosen wellNeeds scaled features, otherwise it fails (the project shows how badly)
Kernels draw curved borders without new columnsC, kernel and gamma must be chosen, and they matter
Only the support vectors are needed to predictNo probabilities by default; probability=True is slower and only an estimate
The training has one best answer (no random start, no local minimum)A curved border is hard to explain to a customer

Try it yourself

(a) Is an SVM a good choice for 5,000 rows with 200 features? (b) For 10 million rows? (c) Does an SVM give probabilities by default? (d) Which rows decide where the street lies?

Show a hint
Look at the tables "When to use an SVM" and "Strengths and weaknesses".
Show the solution

Answer: (a) yes; (b) no; (c) no; (d) the support vectors.

Medium data with many features is the SVM's strength; the training time grows fast with the rows; probabilities need probability=True; only the rows on the edge support the street.

2The widest street, worked by hand

2.1Six applicants

Six applicants of a bank with two features: the duration of the loan in years and the amount in thousands of euros. Three were good customers (class −1), three were bad (class +1).

Six applicants
ApplicantDurationAmountClass
A11good (−1)
B21good (−1)
C12good (−1)
D33bad (+1)
E43bad (+1)
F34bad (+1)

2.2The border and the decision function

A linear SVM looks for a line w₁x₁ + w₂x₂ + b = 0 with weights w and a bias b. For a row x it computes the decision function

f(x)=w1x1+w2x2+bf(x) = w_1 x_1 + w_2 x_2 + b

and predicts class +1 when f(x)>0f(x) > 0 and class −1 when f(x)<0f(x) < 0. The two edges of the street are the lines f(x)=+1f(x) = +1 and f(x)=−1f(x) = -1.

The good applicants nearest to the bad ones are B and C (both with x1+x2=3x_1 + x_2 = 3); the nearest bad applicant is D (x1+x2=6x_1 + x_2 = 6). The widest street runs between the lines x1+x2=3x_1 + x_2 = 3 and x1+x2=6x_1 + x_2 = 6, and its middle is x1+x2=4.5x_1 + x_2 = 4.5. With equal weights w1=w2=aw_1 = w_2 = a, the two edges give two equations:

on B and C:3a+b=−1on D:6a+b=+1\begin{aligned} \text{on B and C:}\quad & 3a + b = -1 \\[4pt] \text{on D:}\quad & 6a + b = +1 \end{aligned}

Subtracting the first from the second: 3a=23a = 2, so a=23=0.667a = \frac{2}{3} = 0.667, and b=−1−3×0.667=−3b = -1 - 3 \times 0.667 = -3.

f(x)=0.667 x1+0.667 x2−3f(x) = 0.667\,x_1 + 0.667\,x_2 - 3

2.3The width of the street

The margin is 2 divided by the length of w:

∥w∥=0.6672+0.6672=0.889=0.943margin=2∥w∥=20.943=2.121\begin{aligned} \lVert w \rVert &= \sqrt{0.667^2 + 0.667^2} = \sqrt{0.889} = 0.943 \\[6pt] \text{margin} &= \frac{2}{\lVert w \rVert} = \frac{2}{0.943} = 2.121 \end{aligned}

This is exactly the distance between the lines x1+x2=3x_1 + x_2 = 3 and x1+x2=6x_1 + x_2 = 6. The support vectors are B, C and D: they lie on the edges (f=−1f = -1, −1-1 and +1+1). A, E and F lie further away and do not matter for the street.

001122334455ABCDEF
  • good
  • bad
  • the border
The six applicants by duration and amount (teal: good, orange: bad). The middle line x₁ + x₂ = 4.5 is the border; the dashed lines x₁ + x₂ = 3 and 6 are the edges of the street, which is 2.121 wide. B, C and D lie on the edges: they are the support vectors (ringed). The new applicant (2, 3), the diamond, gets f = 0.333: predicted bad, but inside the street.

2.4Deciding for new applicants

f(2,3)=0.667×2+0.667×3−3=3.333−3=0.333f(1,1)=0.667×1+0.667×1−3=1.333−3=−1.667\begin{aligned} f(2, 3) &= 0.667 \times 2 + 0.667 \times 3 - 3 \\[2pt] &= 3.333 - 3 = 0.333 \\[8pt] f(1, 1) &= 0.667 \times 1 + 0.667 \times 1 - 3 \\[2pt] &= 1.333 - 3 = -1.667 \end{aligned}

The first applicant gets f = 0.333 > 0: predicted bad, but with |f| < 1 the point lies inside the street: an uncertain case. The second gets f = −1.667: clearly good, far outside the street. The size of f is a measure of confidence; scikit-learn returns it with decision_function.

scikit-learn's SVC(kernel="linear") finds the same line on these six applicants: weights 0.667 and 0.667, bias −3, support vectors B, C and D.

Move a new applicant (the diamond) and watch the decision function of the street of Part 2.

001122334455ABCDEF

f(2, 3) = 0.667 × 2 + 0.667 × 3 − 3 = 0.333

Predicted bad, inside the street: an uncertain case.

The street is the band where −1 < f < 1. Points with the same x₁ + x₂ get the same f, because both weights are equal.

Try it yourself

The street of the six applicants: f(x)=0.667 x1+0.667 x2−3f(x) = 0.667\,x_1 + 0.667\,x_2 - 3. (a) Compute ff for the applicant (3, 2). Give 3 decimals. (b) Is that applicant inside the street? (c) Another SVM has w=(1,1)w = (1, 1). How wide is its street? Give 3 decimals.

Show a hint
Inside the street means −1<f<1-1 < f < 1. The margin is 2∥w∥\frac{2}{\lVert w \rVert}, with ∥w∥=12+12\lVert w \rVert = \sqrt{1^2 + 1^2}.
Show the solution

Answer: (a) 0.333; (b) yes; (c) 1.414.

f(3,2)=0.667×3+0.667×2−3=3.333−3=0.333margin=212+12=21.414=1.414\begin{aligned} f(3, 2) &= 0.667 \times 3 + 0.667 \times 2 - 3 \\[2pt] &= 3.333 - 3 = 0.333 \\[8pt] \text{margin} &= \frac{2}{\sqrt{1^2 + 1^2}} = \frac{2}{1.414} = 1.414 \end{aligned}

0.333 lies between −1 and +1: predicted bad, but inside the street, an uncertain case.

3The soft margin and C

3.1When no street fits

Real data is not that clean. Add a seventh applicant G at (3, 2.5), a good customer between the bad ones. Now no straight street separates the classes without a mistake, or only a very narrow one. The SVM must choose between:

  • a wide street that accepts G on the wrong side (one mistake),
  • a narrow street that squeezes past G (no mistake).

3.2The hinge loss

A row that is on the wrong side of its edge pays a penalty, the hinge loss:

loss=max⁡(0, 1−y f(x))\text{loss} = \max\bigl(0,\ 1 - y\,f(x)\bigr)

with y=+1y = +1 for bad and y=−1y = -1 for good. A row beyond its edge (y×f≥1y \times f \ge 1) pays 0. G under the old line of Part 2:

f(G)=0.667×3+0.667×2.5−3=0.667loss(G)=max⁡(0, 1−(−1)×0.667)=1.667\begin{aligned} f(G) &= 0.667 \times 3 + 0.667 \times 2.5 - 3 = 0.667 \\[6pt] \text{loss}(G) &= \max\bigl(0,\ 1 - (-1) \times 0.667\bigr) = 1.667 \end{aligned}

3.3What the SVM minimises

12∥w∥2+C×(sum of the losses)\tfrac{1}{2}\lVert w \rVert^2 + C \times (\text{sum of the losses})

The first part is small when the street is wide (a short w); the second part is small when few rows break the rules. C decides how much a mistake costs. Compare two lines for the seven applicants:

What the SVM minimises
The old wide lineA narrow line through G's edge
w and bw=(0.667,0.667)w = (0.667, 0.667), b=−3b = -3w=(0,4)w = (0, 4), b=−11b = -11
12∥w∥2\tfrac{1}{2}\lVert w \rVert^212×0.889=0.444\tfrac{1}{2} \times 0.889 = 0.44412×16=8\tfrac{1}{2} \times 16 = 8
Sum of the losses1.667 (only G)0
Margin2.12124=0.5\frac{2}{4} = 0.5
Total with C = 10.444+1×1.667=2.1110.444 + 1 \times 1.667 = 2.1118
Total with C = 10000.444+1000×1.667=1,667.40.444 + 1000 \times 1.667 = 1{,}667.48

With C = 1 the wide street wins: one mistake is cheap. With C = 1000 the narrow street wins: mistakes are very expensive, so the SVM bends to fit every training row.

  • Small C: wide street, more mistakes on the training data, smoother and simpler model (risk: underfitting).
  • Large C: narrow street, few mistakes on the training data, a model that follows every row (risk: overfitting).
001122334455ABCDEFG

C = 1

margin 2.53, one mistake

001122334455ABCDEFG

C = 1000

margin 0.5, no mistakes

The seven applicants with G, a good customer among the bad ones. Left, C = 1: a wide street (2.53) with G inside it, on the wrong side; four support vectors. Right, C = 1000: a narrow horizontal street (0.5) that keeps every applicant on its side; two support vectors. These are the streets scikit-learn finds.

The picture shows what scikit-learn really finds. With C = 1 the street is wide (2.53) and G lies inside it, on the wrong side; with C = 1000 the street is narrow (0.5), runs horizontally, and every row is on its side. In the project, C is chosen with cross-validation.

The seven applicants with G (a good customer among the bad ones). Choose C and see the street scikit-learn finds.

001122334455ABCDEFG

C = 1: w = (0.45, 0.65), b = −2.75; margin 2.53, 4 support vectors (ringed), 1 mistake on the training applicants.

A small C: mistakes are cheap, so the SVM keeps a wide street and lets G stay on the wrong side.

Try it yourself

(a) A bad applicant (y=+1y = +1) gets f=−0.4f = -0.4. What is its hinge loss? (b) A good applicant (y=−1y = -1) gets f=−1.5f = -1.5. Its hinge loss? (c) With ∥w∥2=2\lVert w \rVert^2 = 2, C=2C = 2 and only these two rows, what does the SVM's objective give? (d) Does a larger C make the street wider or narrower?

Show a hint
The hinge loss is max⁡(0, 1−y f)\max(0,\ 1 - y\,f); the objective is 12∥w∥2+C×\tfrac{1}{2}\lVert w \rVert^2 + C \times (sum of the losses).
Show the solution

Answer: (a) 1.4; (b) 0; (c) 3.8; (d) narrower.

(a)max⁡(0, 1−(+1)(−0.4))=1.4(b)max⁡(0, 1−(−1)(−1.5))=max⁡(0, −0.5)=0(c)12×2+2×(1.4+0)=1+2.8=3.8\begin{aligned} \text{(a)}\quad & \max(0,\ 1 - (+1)(-0.4)) = 1.4 \\[4pt] \text{(b)}\quad & \max(0,\ 1 - (-1)(-1.5)) \\[2pt] & = \max(0,\ -0.5) = 0 \\[4pt] \text{(c)}\quad & \tfrac{1}{2} \times 2 + 2 \times (1.4 + 0) = 1 + 2.8 = 3.8 \end{aligned}

The bad applicant is on the wrong side and pays; the good one is beyond its edge and pays nothing. A larger C makes every loss more expensive, so the SVM narrows the street to avoid them.

4Kernels: curved borders

4.1The kernel trick

Some classes cannot be separated by a straight line at all. Take seven applicants on one number line (a scaled feature): the ones at −3, −2, 2 and 3 are bad, the ones at −1, 0 and 1 are good. No single threshold separates them: the bad ones are on both sides.

Add a second column, the square of the value: x→(x,x2)x \to (x, x^2).

The kernel trick
x−3−2−10123
x2x^29410149
classbadbadgoodgoodgoodbadbad

In the new column the good ones have x2≤1x^2 \le 1 and the bad ones x2≥4x^2 \ge 4: the straight line x2=2.5x^2 = 2.5 separates them. A straight border in the bigger space is a curved border (here two thresholds, at −1.58 and +1.58) in the original one.

−3−2−10123

one feature x

no single threshold works

x² = 2.5−3−2−10123

the points (x, x²)

the line x² = 2.5 separates them

  • good
  • bad
Left: seven points on one line; the bad ones (orange) lie on both sides of the good ones (teal), so no single threshold separates them. Right: the same points with their square x² as a second coordinate. Now the straight line x² = 2.5 separates them, which is a curved border (two thresholds) on the original line.

Adding columns by hand would be slow with many features. The SVM never needs the new columns themselves: its calculations only use the similarity of two rows, a dot product. A kernel is a function K(a,b)K(a, b) that gives this similarity as if the rows had been moved to the bigger space, without moving them. This is the kernel trick.

4.2The four kernels of scikit-learn

The four kernels of scikit-learn
Kernelkernel=Similarity K(a,b)K(a, b)The borderWhen to use
Linear"linear"a⋅ba \cdot ba straight line (a flat hyperplane)many features (texts), or when a simple model is enough
Polynomial"poly"(γ a⋅b+coef0)degree(\gamma\, a \cdot b + \text{coef0})^{\text{degree}}curves of the given degreewhen features interact; rarely the best
RBF (Gaussian)"rbf" (default)e−γ∥a−b∥2e^{-\gamma \lVert a - b \rVert^2}any shape: islands and bendsthe usual first choice
Sigmoid"sigmoid"tanh⁡(γ a⋅b+coef0)\tanh(\gamma\, a \cdot b + \text{coef0})S-shaped borders, like a small neural networkrarely; often worse than RBF

4.3How an SVM predicts with a kernel

With a kernel there is no line w to write down any more. The SVM predicts with the support vectors themselves: every support vector xix_i gets a weight αi\alpha_i, and the decision function adds up its similarities to the new row xx:

f(x)=α1y1K(x1,x)+α2y2K(x2,x)+⋯+bf(x) = \alpha_1 y_1 K(x_1, x) + \alpha_2 y_2 K(x_2, x) + \dots + b

The sum runs over the support vectors only; every other training row has α=0\alpha = 0 and plays no part. Each weight αi\alpha_i lies between 0 and C, so C also limits how much a single row can pull the border. A new row that is very similar to many bad support vectors gets a large positive f(x): bad. The project computes this sum by hand for one applicant and gets exactly the model's answer.

4.4The RBF kernel by hand

The RBF kernel turns a distance into a similarity between 0 and 1: identical rows get 1, distant rows almost 0. With γ=0.5\gamma = 0.5:

∥a−b∥2=1:K=e−0.5×1=0.607∥a−b∥2=4:K=e−0.5×4=0.135∥a−b∥2=9:K=e−0.5×9=0.011\begin{aligned} \lVert a - b \rVert^2 = 1:\quad & K = e^{-0.5 \times 1} = 0.607 \\[4pt] \lVert a - b \rVert^2 = 4:\quad & K = e^{-0.5 \times 4} = 0.135 \\[4pt] \lVert a - b \rVert^2 = 9:\quad & K = e^{-0.5 \times 9} = 0.011 \end{aligned}

gamma sets how fast the similarity falls with the distance:

  • small γ\gamma: even distant rows are similar; every row influences a wide area; the border is smooth (risk: underfitting);
  • large γ\gamma: only very close rows are similar; each row influences a tiny area; the border wraps around single rows (risk: overfitting).

The default gamma="scale" uses 1features×variance\frac{1}{\text{features} \times \text{variance}}; after a StandardScaler the variance is 1, so it is 1features\frac{1}{\text{features}}.

4.5The kernels on the credit data

The four kernels on two features of the project's data, the duration and the credit amount (scaled), with class_weight="balanced" so that every model draws a "bad" area (Part 5 explains it). In the orange area the model predicts bad, in the teal area good; the dots are 300 training applicants, orange for bad and teal for good:

−101234−1012345duration (scaled)credit amount (scaled)

kernel="linear"

−101234−1012345duration (scaled)credit amount (scaled)

kernel="poly"

−101234−1012345duration (scaled)credit amount (scaled)

kernel="rbf"

−101234−1012345duration (scaled)credit amount (scaled)

kernel="sigmoid"

  • bad
  • good
The area where each SVM predicts bad (orange) on the scaled duration and credit amount of the training applicants, all with class_weight="balanced"; the dots are 300 of the applicants (orange: bad, teal: good). The linear kernel draws a straight border, the polynomial kernel bends it, the RBF kernel draws rounded areas, and the sigmoid kernel draws a border that does not follow the data.

The linear kernel draws a straight border: long, large loans are risky. The polynomial kernel bends it, the RBF kernel draws a rounded area, and the sigmoid kernel draws a strange border that does not follow the data. Two features are far too few to judge a loan; the project uses all of them.

−101234−1012345duration (scaled)credit amount (scaled)

gamma = 0.1

−101234−1012345duration (scaled)credit amount (scaled)

gamma = 1

−101234−1012345duration (scaled)credit amount (scaled)

gamma = 10

  • bad
  • good
The area where each SVM predicts bad (orange) on the scaled duration and credit amount of the training applicants, all with class_weight="balanced"; the dots are 300 of the applicants (orange: bad, teal: good). The RBF kernel with gamma 0.1 draws one smooth area, with gamma 1 a more detailed one, and with gamma 10 small islands around single applicants: overfitting.

The RBF kernel with three values of gamma: 0.1 draws a smooth area, 1 a more detailed one, 10 small islands around single applicants. The islands are overfitting: they learn the training rows, not the rule.

Choose a kernel (or the RBF kernel with a gamma) and see where the SVM predicts bad, on the scaled duration and credit amount (class_weight="balanced").

−101234−1012345duration (scaled)credit amount (scaled)

rbf: rounded areas; gamma = "scale" (1 / 2 with two features).

Orange area: predicted bad; teal: good. Two features are far too few for a loan decision; the project uses all 44.

Try it yourself

(a) Compute the RBF similarity with γ=0.5\gamma = 0.5 for two rows with ∥a−b∥2=2\lVert a - b \rVert^2 = 2. Give 3 decimals. (b) Compute the polynomial kernel (a⋅b+1)2(a \cdot b + 1)^2 for a⋅b=2a \cdot b = 2. (c) Which kernel draws islands around single rows when its gamma is large? (d) Which kernel draws a straight border?

Show a hint
e−γ∥a−b∥2e^{-\gamma \lVert a - b \rVert^2}; for (b) first 2+12 + 1.
Show the solution

Answer: (a) 0.368; (b) 9; (c) RBF; (d) linear.

(a)e−0.5×2=e−1=0.368(b)(2+1)2=9\begin{aligned} \text{(a)}\quad & e^{-0.5 \times 2} = e^{-1} = 0.368 \\[4pt] \text{(b)}\quad & (2 + 1)^2 = 9 \end{aligned}

The RBF similarity falls with the distance; with a large gamma it falls so fast that each row only influences its close neighbours.

5The hyperparameters of SVC

SVC is the support vector classifier of scikit-learn (from sklearn.svm import SVC).

The hyperparameters of SVC
HyperparameterDefaultRole
C1.0the cost of a mistake (Part 3). Small: wide street, simpler model; large: narrow street, follows the training rows. The most important one.
kernel"rbf"the shape of the border: "linear", "poly", "rbf", "sigmoid" (Part 4)
gamma"scale"for rbf, poly and sigmoid: how far the influence of one row reaches. Small: smooth; large: islands. \"scale\" is 1features×variance\frac{1}{\text{features} \times \text{variance}}, \"auto\" is 1features\frac{1}{\text{features}}.
degree3only for poly: the degree of the curves
coef00.0only for poly and sigmoid: the constant inside the kernel
class_weightNone"balanced" makes a mistake on the smaller class more expensive (C is multiplied by the class weight): more of the rare class is found
probabilityFalseTrue adds predict_proba (needed for soft voting); the training is about five times slower, because it uses an inner cross-validation
random_stateNoneonly used when probability=True
shrinkingTruea speed trick of the solver; the result is the same
tol0.001when the solver may stop
cache_size200memory (MB) for kernel values: a speed setting
max_iter-1a limit on the solver's steps; -1 means no limit
decision_function_shape"ovr"for more than two classes: how the answers of the pairwise SVMs are combined
break_tiesFalsefor more than two classes: break ties by the decision function

Which ones matter? First C and, for the RBF kernel, gamma: choose both with cross-validation on a few values spread out by factors of 10 (0.01, 0.1, 1, 10, 100). Then kernel (RBF first, linear for many features) and class_weight when the rare class matters. The rest are speed and technical settings.

Learned attributes (after fit): support_vectors_ (the support vectors), support_ (their positions), n_support_ (how many per class), dual_coef_ and intercept_ (the numbers of the decision function), coef_ (the weights, only for the linear kernel).

More than two classes: an SVM separates two classes. For three or more, SVC trains one SVM for every pair of classes (one-vs-one): with 3 classes that is 3 SVMs, with 4 classes 6, with k classes k(k − 1) / 2. Each SVM votes for one of its two classes, and the class with the most votes wins. decision_function_shape="ovr" only changes the shape of the answers of decision_function. Nothing has to be changed in the code: fit and predict work the same way.

Relatives: LinearSVC is a faster SVM for the linear kernel and large data. SVR is the SVM for numbers (Topic 36).

Which hyperparameter of SVC is it?

1 of 6

Small: a wide street with some mistakes. Large: a narrow street that follows every training row.

Try it yourself

(a) Which hyperparameter is the cost of a mistake? (b) Which one sets how far the influence of one row reaches? (c) Which one adds predict_proba? (d) Which one is used only by the polynomial kernel?

Show a hint
Look at the table of hyperparameters.
Show the solution

Answer: (a) C; (b) gamma; (c) probability; (d) degree.

C and gamma matter most and are chosen with cross-validation; probability makes the training slower; degree and coef0 only change the polynomial (and sigmoid) kernels.

6Preprocessing for an SVM, and for the models still to come

  • Scaling: essential. The kernels measure distances and dot products. Without scaling, the feature with the largest numbers (here the credit amount, in thousands) decides everything, and the others are ignored. The project shows the damage.
  • Encoding: needed. An SVM works with numbers only: one-hot encoding (Topic 25) for categories. Each one-hot column is then scaled like the others.
  • Missing values: must be filled. SVC does not accept gaps. (This file has none, but the step is still done.)
  • Outliers: they matter a little. With a soft margin a single strange row cannot pull the whole street, but it can become a support vector; and extreme values stretch the scaling. Real values are kept.
  • Many features: no problem for an SVM, unlike k-nearest neighbours.
  • Unbalanced classes: class_weight="balanced" (Topic 41 goes further).
  • Voting: each model inside the vote keeps its own needs. Here every model gets the same scaled data: logistic regression, k-nearest neighbours and the SVM need it, trees ignore it.
Preprocessing for an SVM, and for the models still to come
Model (topic)ScalingEncoding of textOutliers in the featuresMissing values
Linear regression (22)not needed for the predictionsneededsensitivefill
Ridge, Lasso, logistic regression (26, 27)neededneededsensitivefill
Decision tree, random forest, bagged trees (29, 30, 31)not neededneededrobustfill (recent scikit-learn can handle them)
k-nearest neighbours (32, 33)essential: distancesneeded; few, useful columnssensitivefill
Naive Bayes (34)not neededcodes for Categorical, one-hot for Gaussiansensitive (Gaussian)fill
Support vector machines (35, 36)essential: distances and dot productsneeded (one-hot)a little: they can become support vectorsfill
Voting (35, 36)as the models insideas the models insideas the models insidefill
Gradient boosting, XGBoost, LightGBM, CatBoost (37 to 40)not neededneeded (CatBoost and LightGBM can also take categories directly)robustXGBoost, LightGBM and CatBoost handle them
k-means, DBSCAN, PCA (43, 44)essential: distances and variancesneededsensitivefill

Topic 42 will put the preprocessing and the model into one object, so that every step is fitted on the right rows.

Try it yourself

(a) Must the features of an SVM be scaled? (b) Can an SVM take the text column purpose as it is? (c) Must the models inside a vote get the same preprocessing? (d) Which models of the vote do not need scaling?

Show a hint
Read the list and the table of Part 6.
Show the solution

Answer: (a) yes; (b) no; (c) each its own, here the same scaled data; (d) the trees.

Distances and dot products need equal scales; text must become numbers; every voter keeps its own needs, and trees only look at the order of the values.

7The project: from the raw file to the data for the models

The data: german_credit.csv, 1,000 people who asked a German bank for a loan, from the UCI Machine Learning Repository's Statlog (German Credit Data) data set. It was donated by Professor Hans Hofmann (University of Hamburg) and is published under the licence CC BY 4.0. The bank judged every applicant as a good or a bad credit risk. The original file writes every category as a code (A11, A12, ...); here the codes are written as short words, so that the encoding can be done in the lesson. Nothing else was changed. The file has no names or other personal identifiers. Every step is done again and explained as if it were new. The cells continue from each other like the cells of a notebook, from Part 7 to the end of Part 10.

The data file: german_credit.csv

1,000 loan applicants of a German bank, 21 columns, the codes of the original file written as words; no gaps and no repeated rows. A cell marked "empty" has no value in the file: pandas shows it as NaN.

Download

Loading the table ...

7.1Step 1: read and look

Python
import pandas as pd

df = pd.read_csv("german_credit.csv")

print(df.shape)
print(df.head())

Output

(1000, 21)
  checking_account  duration_months  ... foreign_worker  risk
0           < 0 DM                6  ...            yes  good
1      0 to 200 DM               48  ...            yes   bad
2       no account               12  ...            yes  good
3           < 0 DM               42  ...            yes  good
4           < 0 DM               24  ...            yes   bad

[5 rows x 21 columns]

1,000 applicants and 21 columns:

Step 1: read and look
ColumnMeaning
checking_accountthe balance of the checking account: < 0 DM, 0 to 200 DM, >= 200 DM, or no account (DM: Deutsche Mark)
duration_monthsthe duration of the loan in months
credit_historyhow earlier loans were paid back
purposewhat the loan is for: new car, used car, furniture, radio or TV, education, business, ...
credit_amountthe amount of the loan in DM
savingsthe savings: < 100 DM up to >= 1000 DM, or unknown
employment_yearshow long the applicant has worked for the present employer
installment_ratethe monthly payment as a share of the disposable income (1 to 4)
personal_statussex and marital status
other_debtorsnone, a co-applicant or a guarantor
residence_yearsyears at the present home (1 to 4)
propertythe most valuable property: real estate, savings or insurance, car or other, none known
agethe age in years
other_installmentsother loans being paid off: bank, stores, none
housingrent, own, for free
existing_creditsthe number of loans at this bank
jobthe kind of job
dependentsthe number of people the applicant supports
telephonea telephone registered in the applicant's name
foreign_workerwhether the applicant is a foreign worker
riskthe target: good or bad

7.2Step 2: check for gaps and repeated rows

Python, continues from the cells above
print(df.isna().sum().sum())
print(df.duplicated().sum())

Output

0
0

No gaps and no repeated rows: the file needs no filling and no removing. The step is still done, because a model would fail on a gap, and a repeated applicant in the training and the test data would make the test score too good (Topic 31). Notice that missing information is written as a category of its own here: "unknown" savings, "no account", "none known" property. These are kept as categories: "the bank does not know the savings" can itself say something about the risk.

7.3Step 3: the numbers

Python, continues from the cells above
print(df.describe().round(1))

Output

       duration_months  credit_amount  ...  existing_credits  dependents
count           1000.0         1000.0  ...            1000.0      1000.0
mean              20.9         3271.3  ...               1.4         1.2
std               12.1         2822.7  ...               0.6         0.4
min                4.0          250.0  ...               1.0         1.0
25%               12.0         1365.5  ...               1.0         1.0
50%               18.0         2319.5  ...               1.0         1.0
75%               24.0         3972.2  ...               2.0         1.0
max               72.0        18424.0  ...               4.0         2.0

[8 rows x 7 columns]

Seven number columns. The credit amount goes from 250 to 18,424 DM, the duration from 4 to 72 months, the age from 19 to 75. The columns have very different sizes: the credit amount is in thousands, the installment rate between 1 and 4. For an SVM this is the first warning sign (Part 6).

7.4Step 4: outliers

The rule of Topic 25: a value more than 1.5 IQR below the first quartile or above the third.

Python, continues from the cells above
for column in ["duration_months", "credit_amount", "age"]:
    q1 = df[column].quantile(0.25)
    q3 = df[column].quantile(0.75)
    iqr = q3 - q1
    outside = ((df[column] < q1 - 1.5 * iqr) | (df[column] > q3 + 1.5 * iqr)).sum()
    print(column, outside)

Output

duration_months 70
credit_amount 72
age 23

70 durations, 72 credit amounts and 23 ages lie outside: long loans, large amounts and older applicants. They are real loans, not typing errors, and large, long loans are exactly the risky ones the bank wants to recognise. They stay. With a soft margin they cannot pull the whole street (Part 6).

7.5Step 5: the target

Python, continues from the cells above
print(df["risk"].value_counts())

Output

risk
good    700
bad     300
Name: count, dtype: int64

70 percent good, 30 percent bad. The model will predict "bad", so "bad" becomes 1, the positive class of Topic 28:

Python, continues from the cells above
df["risk"] = (df["risk"] == "bad").astype(int)

print(df["risk"].mean())

Output

0.3

For a bank a bad credit that is accepted costs much more than a good customer who is turned away (the data set's own description says five times more). So the recall of the bad class matters: how many of the bad credits does the model find?

7.6Step 6: drop two columns that a fair model must not use

Python, continues from the cells above
df = df.drop(columns=["personal_status", "foreign_worker"])

print(df.shape)

Output

(1000, 19)

personal_status holds the sex of the applicant and foreign_worker the nationality. A credit decision must not depend on them: it would be unfair, and in many countries it is against the law. A model learns whatever pattern the data contains, also an unfair one, so such columns are removed before training. (Even then other columns can carry part of the same information; checking a model for fairness is a field of its own.)

7.7Step 7: encode the text columns

Python, continues from the cells above
text_columns = ["checking_account", "credit_history", "purpose", "savings", "employment_years", "other_debtors", "property", "other_installments", "housing", "job", "telephone"]

df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)

print(df.shape)

Output

(1000, 45)

Eleven text columns become one-hot columns (Topic 25): 44 features and the target. drop_first=True leaves out one category of each column, which the others already describe.

7.8Step 8: split

Python, continues from the cells above
from sklearn.model_selection import train_test_split

X = df.drop(columns=["risk"])
y = df["risk"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

print(X_train.shape, X_test.shape)
print(round(y_test.mean(), 3))

Output

(800, 44) (200, 44)
0.295

Change it and run: change test_size to 0.3 and run: 300 applicants become test data.

800 applicants to learn from, 200 to judge with; 29.5 percent of the test applicants are bad. The baseline (Topic 27): a model that says "good" for everyone is right for 70.5 percent of the test applicants. Every model must beat 0.705.

7.9Step 9: scale

Python, continues from the cells above
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

print(X_train_scaled[:3, :3].round(2))

Output

[[ 3.3   1.2   0.03]
 [-0.01 -0.36 -0.86]
 [-1.28 -0.73 -0.86]]

The scaler is fitted on the training applicants only and then applied to both parts: every column now has the mean 0 and the standard deviation 1 in the training data. The first three columns of three applicants are shown: duration, credit amount and installment rate, all on the same scale.

Try it yourself

This task continues from the first cells of Part 7 (the file read, risk as 0 and 1). Print the share of bad credits among the applicants with "no account", then among those with "< 0 DM" in checking_account, each rounded to 4 decimals.
Show a hint
df[df["checking_account"] == "no account"] keeps those applicants; the mean of risk is the share of 1s.
Show the solution
Python, continues from the cells above
no_account = df[df["checking_account"] == "no account"]
negative = df[df["checking_account"] == "< 0 DM"]

print(round(no_account["risk"].mean(), 4))
print(round(negative["risk"].mean(), 4))

Output

0.1168
0.4927

8The SVM on the credit data

8.1Train and judge

Python, continues from the cells above
from sklearn.svm import SVC

svm = SVC()
svm.fit(X_train_scaled, y_train)

print(round(svm.score(X_train_scaled, y_train), 4))
print(round(svm.score(X_test_scaled, y_test), 4))

Output

0.8812
0.76

Change it and run: write SVC(C=10) and run: the training accuracy rises, the test accuracy falls.

The default SVM (RBF kernel, C=1, gamma="scale") reaches a test accuracy of 0.76, above the baseline of 0.705. The training accuracy is higher: some overfitting, but not much.

8.2The measures of Topic 28

Python, continues from the cells above
from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score

predicted = svm.predict(X_test_scaled)

print(confusion_matrix(y_test, predicted))
print(round(precision_score(y_test, predicted), 4))
print(round(recall_score(y_test, predicted), 4))
print(round(f1_score(y_test, predicted), 4))
print(round(roc_auc_score(y_test, svm.decision_function(X_test_scaled)), 4))

Output

[[127  14]
 [ 34  25]]
0.641
0.4237
0.5102
0.7949

Of the 59 bad credits in the test data the model finds 25: a recall of only 0.42. The precision is better: when it says "bad", it is right in 64 of 100 cases. The AUC needs a score for every applicant: an SVM has no probabilities by default, so its decision function (the f(x) of Part 2) is used. The AUC only cares about the order of the scores, so f(x) works as well as a probability.

8.3Without scaling

Python, continues from the cells above
svm_raw = SVC()
svm_raw.fit(X_train, y_train)

predicted_raw = svm_raw.predict(X_test)

print(round(svm_raw.score(X_test, y_test), 4))
print(round(recall_score(y_test, predicted_raw), 4))

Output

0.715
0.0508

Without scaling the SVM finds only 3 of the 59 bad credits (a recall of 0.05) and is barely better than saying "good" for everyone. The credit amount, in thousands, decides every distance alone. Scaling is essential.

8.4Inside the model: the support vectors

Python, continues from the cells above
print(svm.n_support_)
print(len(svm.support_), len(X_train_scaled))

Output

[313 234]
547 800

313 good and 234 bad applicants are support vectors: 547 of the 800, more than two thirds. In the six applicants of Part 2 only three were needed; here the classes overlap so much that most rows lie inside the street or on the wrong side. This is typical for hard, noisy problems such as credit risk. (A model with very few support vectors on clean data is fast and simple; one with many is slow to predict.)

8.5The decision function of a few applicants

Python, continues from the cells above
print(svm.decision_function(X_test_scaled[:5]).round(3))
print(predicted[:5])
print(y_test.iloc[:5].tolist())

Output

[-0.344  0.537  1.007 -0.866 -1.356]
[0 1 1 0 0]
[1, 0, 0, 0, 0]

Change it and run: change [:5] to [5:10] in all three lines and run.

Positive values mean "bad", negative "good"; values between −1 and +1 lie inside the street. The first applicant (−0.344) is predicted good but was bad: an uncertain case inside the street. The third (1.007) is predicted bad with more confidence, but was good.

8.6The decision function by hand

The formula of Part 4 with the model's own numbers: the RBF similarity of the first test applicant to each of the 547 support vectors, multiplied by their weights (dual_coef_ holds αiyi\alpha_i y_i), plus the bias intercept_:

Python, continues from the cells above
from sklearn.metrics.pairwise import rbf_kernel

gamma = 1 / (X_train_scaled.shape[1] * X_train_scaled.var())
similarity = rbf_kernel(svm.support_vectors_, X_test_scaled[:1], gamma=gamma)

print(round(gamma, 4))
print(svm.dual_coef_.min(), svm.dual_coef_.max())
print((svm.dual_coef_ @ similarity + svm.intercept_).round(3))

Output

0.0227
-1.0 1.0
[[-0.344]]

The first line is the value of gamma="scale": 144×1\frac{1}{44 \times 1} (44 features, variance 1). The second shows that every weight lies between −1 and +1: between −C and C, with C = 1. The third is the sum of Part 4 (@ is the matrix product of Topic 14): −0.344, exactly the decision function of the first applicant above.

8.7Which kernel?

The kernel is chosen with cross-validation on the training data (Topic 23), never with the test data:

Python, continues from the cells above
from sklearn.model_selection import cross_val_score

for kernel in ["linear", "poly", "rbf", "sigmoid"]:
    scores = cross_val_score(SVC(kernel=kernel), X_train_scaled, y_train, cv=5)
    print(kernel, round(scores.mean(), 4))

Output

linear 0.7388
poly 0.7175
rbf 0.7475
sigmoid 0.73

Every line shows a kernel and its mean accuracy over five folds. The RBF kernel is the best, the linear and the sigmoid kernels are close behind, and the polynomial kernel is the weakest. The default RBF stays.

8.8C with cross-validation

Python, continues from the cells above
for C in [0.01, 0.1, 1, 10, 100]:
    model = SVC(C=C)
    model.fit(X_train_scaled, y_train)
    scores = cross_val_score(SVC(C=C), X_train_scaled, y_train, cv=5)
    print(C, round(model.score(X_train_scaled, y_train), 4), round(scores.mean(), 4))

Output

0.01 0.6987 0.6988
0.1 0.6987 0.6988
1 0.8812 0.7475
10 0.9862 0.7188
100 1.0 0.6962

Change it and run: add 0.5 and 3 to the list and run.

Every line shows C, the training accuracy and the cross-validated accuracy:

  • C = 0.01 and 0.1: the street is so wide that the model says "good" for everyone (0.699 is the share of good applicants in the training data): underfitting.
  • C = 1: the best cross-validated accuracy.
  • C = 10 and 100: the training accuracy climbs to almost 1, the cross-validated one falls: overfitting, the narrow street follows every training row.

8.9gamma with cross-validation

Python, continues from the cells above
for gamma in [0.001, 0.01, 0.03, 0.1, 1]:
    scores = cross_val_score(SVC(gamma=gamma), X_train_scaled, y_train, cv=5)
    print(gamma, round(scores.mean(), 4))

Output

0.001 0.6975
0.01 0.7375
0.03 0.7512
0.1 0.7088
1 0.7013

Very small gamma underfits (everyone good again), very large gamma overfits (islands around single applicants). The best values lie around 0.03, close to the default "scale", which is 144=0.023\frac{1}{44} = 0.023 here. The differences between 0.01 and 0.03 are small: on 800 applicants the default is as good as the tuned value.

8.10More bad credits found: class_weight

The bank cares most about the bad credits. class_weight="balanced" makes a mistake on the smaller class (bad) more expensive:

Python, continues from the cells above
svm_balanced = SVC(class_weight="balanced")
svm_balanced.fit(X_train_scaled, y_train)

predicted_balanced = svm_balanced.predict(X_test_scaled)

print(confusion_matrix(y_test, predicted_balanced))
print(round(recall_score(y_test, predicted_balanced), 4))
print(round(precision_score(y_test, predicted_balanced), 4))
print(round(f1_score(y_test, predicted_balanced), 4))

Output

[[106  35]
 [ 14  45]]
0.7627
0.5625
0.6475

The recall rises from 0.42 to 0.76: the model now finds 45 of the 59 bad credits. The price is more false alarms (the precision falls to 0.56), but the F1-score rises from 0.51 to 0.65. For a bank, where an accepted bad credit costs five times more, this model is clearly better.

8.11Probabilities for an SVM

Soft voting (Part 9) needs probabilities. probability=True adds them: after training, scikit-learn fits a small logistic curve on the decision function with an inner cross-validation (Platt scaling).

Python, continues from the cells above
svm_prob = SVC(probability=True, random_state=42)
svm_prob.fit(X_train_scaled, y_train)

probabilities = svm_prob.predict_proba(X_test_scaled)[:, 1]

print(probabilities[:5].round(3))
print(((probabilities >= 0.5).astype(int) != predicted).sum())

Output

[0.382 0.745 0.87  0.196 0.093]
3

The first line shows the probabilities of "bad" for the first five test applicants. The second line counts the test applicants for whom "probability at least 0.5" and predict disagree: the probabilities come from a separate small model, so for a few applicants near the border they tell a slightly different story. This is why probability is off by default.

Try it yourself

This task continues from the cells of Parts 7 and 8. Train an SVM with kernel="linear" on the scaled data. Print its test accuracy, then its recall, each rounded to 4 decimals.
Show a hint
SVC(kernel="linear"), fit, predict, then accuracy_score and recall_score with y_test.
Show the solution
Python, continues from the cells above
linear = SVC(kernel="linear")
linear.fit(X_train_scaled, y_train)

predicted_linear = linear.predict(X_test_scaled)

print(round(accuracy_score(y_test, predicted_linear), 4))
print(round(recall_score(y_test, predicted_linear), 4))

Output

0.765
0.4746

Try it yourself

This task continues from the cells of Parts 7 and 8. Train an SVC(C=10) and print its training accuracy, then its test accuracy, each rounded to 4 decimals. Is it overfitting?
Show a hint
score on X_train_scaled, y_train and on X_test_scaled, y_test.
Show the solution
Python, continues from the cells above
model = SVC(C=10)
model.fit(X_train_scaled, y_train)

print(round(model.score(X_train_scaled, y_train), 4))
print(round(model.score(X_test_scaled, y_test), 4))

Output

0.9862
0.75

9Voting: several models decide together

9.1Why vote?

The SVM reaches an accuracy of 0.76. The earlier topics gave us other classifiers: logistic regression, a decision tree, a random forest, k-nearest neighbours, Naive Bayes. Each one makes mistakes, but not the same mistakes: they look at the data in different ways (a border, questions, neighbours, probabilities). When several good models with different mistakes vote, a mistake of one model is often outvoted by the others. This is the idea of ensembles, the "wisdom of the crowd". A random forest (Topic 30) is a vote of many trees of one kind; voting combines models of different kinds.

The rule of thumb: a vote helps when the models are good (each clearly above the baseline) and different (their mistakes differ). Three copies of the same model add nothing; a weak model can pull the vote down.

9.2Hard voting and soft voting

Three models give the probability of "bad" for two applicants:

Hard voting and soft voting
Logistic regressionRandom forestSVMHard voteSoft vote (the mean)
Applicant 10.90 → bad0.40 → good0.45 → good1 against 2: good0.90+0.40+0.453=0.583\frac{0.90 + 0.40 + 0.45}{3} = 0.583: bad
Applicant 20.55 → bad0.60 → bad0.10 → good2 against 1: bad0.55+0.60+0.103=0.417\frac{0.55 + 0.60 + 0.10}{3} = 0.417: good
  • Hard voting: each model gives its class; the majority wins. Applicant 1: two models say good, so good.
  • Soft voting: the probabilities are averaged; the class with the larger mean wins. Applicant 1: logistic regression is very sure of "bad" (0.90), the other two are only just below 0.5, so the mean is 0.583: bad.

Soft voting uses how sure each model is: a confident model counts more than an undecided one. When the probabilities are reasonable, soft voting is usually better. Hard voting is the choice when some models have no probabilities, or bad ones.

Applicant 1

hard: good, soft: bad

Applicant 2

hard: bad, soft: good

The probability of bad that three models give each applicant (orange: at least 0.5, so a vote for bad; teal: a vote for good), and the soft vote, their mean. Applicant 1: two votes for good, so the hard vote is good; the mean is 0.583, so the soft vote is bad. Applicant 2: the other way round.

Weights can make some models count more: with weights=[2, 1, 1] the logistic regression counts twice, in both kinds of voting.

Three models give an applicant a probability of bad. Move them, choose the weights, and compare hard and soft voting.

logistic

forest

SVM

weights

Hard vote: 1 of 3 votes for bad, so good.

Soft vote: 1 × 0.9 + 1 × 0.4 + 1 × 0.45 divided by 3 = 0.583, so bad.

Start with 0.9, 0.4 and 0.45: the hard vote says good, the soft vote bad, because the first model is very sure.

9.3VotingClassifier

VotingClassifier (from sklearn.ensemble import VotingClassifier) does the vote:

VotingClassifier
HyperparameterDefaultRole
estimators(required)a list of (name, model) pairs: the voters
voting"hard""hard": majority of the classes; "soft": the mean of the probabilities (every model needs predict_proba, so an SVM needs probability=True)
weightsNonehow much each model counts; None means equally
n_jobsNonehow many models are trained at the same time
flatten_transformTruethe shape of the output of transform (the models' probabilities side by side)
verboseFalseprint the time of every model while training

fit trains a fresh copy of every model on the data; the trained models are in named_estimators_. A hard vote has no predict_proba, so no AUC; a soft vote has both.

Try it yourself

Three models give an applicant the probabilities of "bad" 0.6, 0.45 and 0.4. (a) What does hard voting decide? (b) What is the soft vote? Give 3 decimals. (c) What does soft voting decide? (d) With the weights 3, 1 and 1, what is the soft vote? Give 2 decimals.

Show a hint
The weighted soft vote is ∑weight×probability∑weights\frac{\sum \text{weight} \times \text{probability}}{\sum \text{weights}}.
Show the solution

Answer: (a) good; (b) 0.483; (c) good; (d) 0.53.

(b)0.6+0.45+0.43=1.453=0.483(d)3×0.6+1×0.45+1×0.45=2.655=0.53\begin{aligned} \text{(b)}\quad & \frac{0.6 + 0.45 + 0.4}{3} = \frac{1.45}{3} = 0.483 \\[6pt] \text{(d)}\quad & \frac{3 \times 0.6 + 1 \times 0.45 + 1 \times 0.4}{5} \\[4pt] & = \frac{2.65}{5} = 0.53 \end{aligned}

Hard: bad, good, good, so good; soft: 0.483 is below 0.5, so good too; with the first model counting three times the vote turns to bad.

10The other models, and their vote

The same scaled data, the same 200 test applicants, the models of earlier topics, each one alone first.

10.1Logistic regression (Topic 27)

Python, continues from the cells above
from sklearn.linear_model import LogisticRegression

logistic = LogisticRegression()
logistic.fit(X_train_scaled, y_train)

predicted_logistic = logistic.predict(X_test_scaled)

print(round(accuracy_score(y_test, predicted_logistic), 4), round(recall_score(y_test, predicted_logistic), 4), round(f1_score(y_test, predicted_logistic), 4))

Output

0.765 0.5593 0.5841

Every line of this part shows the test accuracy, the recall of the bad credits and the F1-score. Logistic regression is about as accurate as the SVM (0.765 against 0.76) and finds more bad credits (33 of 59 instead of 25).

10.2A decision tree (Topic 29)

Python, continues from the cells above
from sklearn.tree import DecisionTreeClassifier

tree = DecisionTreeClassifier(max_depth=4, random_state=42)
tree.fit(X_train_scaled, y_train)

predicted_tree = tree.predict(X_test_scaled)

print(round(accuracy_score(y_test, predicted_tree), 4), round(recall_score(y_test, predicted_tree), 4), round(f1_score(y_test, predicted_tree), 4))

Output

0.75 0.6441 0.6032

A tree of depth 4 (a full tree would overfit, Topic 29): a little less accurate, but it finds more bad credits.

10.3A random forest (Topic 30)

Python, continues from the cells above
from sklearn.ensemble import RandomForestClassifier

forest = RandomForestClassifier(random_state=42)
forest.fit(X_train_scaled, y_train)

predicted_forest = forest.predict(X_test_scaled)

print(round(accuracy_score(y_test, predicted_forest), 4), round(recall_score(y_test, predicted_forest), 4), round(f1_score(y_test, predicted_forest), 4))

Output

0.805 0.4407 0.5714

The forest has the highest accuracy so far, but a low recall: it is careful about saying "bad".

10.4k-nearest neighbours (Topic 32)

Python, continues from the cells above
from sklearn.neighbors import KNeighborsClassifier

knn = KNeighborsClassifier(n_neighbors=15)
knn.fit(X_train_scaled, y_train)

predicted_knn = knn.predict(X_test_scaled)

print(round(accuracy_score(y_test, predicted_knn), 4), round(recall_score(y_test, predicted_knn), 4), round(f1_score(y_test, predicted_knn), 4))

Output

0.73 0.339 0.4255

k-nearest neighbours suffers from the 44 one-hot columns (the curse of dimensionality, Topic 33): the weakest recall so far.

10.5Naive Bayes (Topic 34)

Python, continues from the cells above
from sklearn.naive_bayes import GaussianNB

naive_bayes = GaussianNB()
naive_bayes.fit(X_train_scaled, y_train)

predicted_nb = naive_bayes.predict(X_test_scaled)

print(round(accuracy_score(y_test, predicted_nb), 4), round(recall_score(y_test, predicted_nb), 4), round(f1_score(y_test, predicted_nb), 4))

Output

0.705 0.6271 0.5564

The lowest accuracy: most features are one-hot columns of 0 and 1, which are not bell-shaped, and Topic 34 showed that the Gaussian kind is weak on them. It finds many bad credits, but with many false alarms. It stays out of the vote; the end of this part shows what it would do there.

10.6The voters

Python, continues from the cells above
from sklearn.ensemble import VotingClassifier

voters = [
    ("logistic", LogisticRegression()),
    ("tree", DecisionTreeClassifier(max_depth=4, random_state=42)),
    ("forest", RandomForestClassifier(random_state=42)),
    ("knn", KNeighborsClassifier(n_neighbors=15)),
    ("svm", SVC(probability=True, random_state=42)),
]

print(len(voters))

Output

5

Five voters: four models of earlier topics and the SVM, each with the settings used above. The SVM gets probability=True, so that the same list can be used for soft voting.

10.7Hard voting

Python, continues from the cells above
hard = VotingClassifier(estimators=voters, voting="hard")
hard.fit(X_train_scaled, y_train)

predicted_hard = hard.predict(X_test_scaled)

print(round(accuracy_score(y_test, predicted_hard), 4), round(recall_score(y_test, predicted_hard), 4), round(f1_score(y_test, predicted_hard), 4))

Output

0.77 0.4746 0.549

The majority of five models: more accurate than the SVM, logistic regression, the tree and k-nearest neighbours alone.

A hard vote has no probabilities, so no AUC:

Python, continues from the cells above
hard.predict_proba(X_test_scaled)

Error

AttributeError: This 'VotingClassifier' has no attribute 'predict_proba'

10.8Soft voting

Python, continues from the cells above
soft = VotingClassifier(estimators=voters, voting="soft")
soft.fit(X_train_scaled, y_train)

predicted_soft = soft.predict(X_test_scaled)

print(round(accuracy_score(y_test, predicted_soft), 4), round(recall_score(y_test, predicted_soft), 4), round(f1_score(y_test, predicted_soft), 4))
print(round(roc_auc_score(y_test, soft.predict_proba(X_test_scaled)[:, 1]), 4))

Output

0.8 0.5085 0.6
0.8223

The mean of the five probabilities: an accuracy of 0.80, the second best after the forest (0.805), with more bad credits found than the forest (a recall of 0.51 against 0.44) and an AUC of 0.82.

10.9Inside the soft vote

Python, continues from the cells above
for name, model in soft.named_estimators_.items():
    print(name, model.predict_proba(X_test_scaled[:3])[:, 1].round(2))

print("vote", soft.predict_proba(X_test_scaled[:3])[:, 1].round(2))

Output

logistic [0.39 0.56 0.75]
tree [0.36 0.3  0.25]
forest [0.3  0.47 0.58]
knn [0.2  0.67 0.8 ]
svm [0.38 0.74 0.87]
vote [0.33 0.55 0.65]

The probabilities of "bad" that each of the five models gives the first three test applicants, and their mean, the soft vote. Look at how the models disagree, and how the mean settles between them.

10.10Weights, and a weak voter

Python, continues from the cells above
weighted = VotingClassifier(estimators=voters, voting="soft", weights=[2, 1, 2, 1, 2])
weighted.fit(X_train_scaled, y_train)

print(round(weighted.score(X_test_scaled, y_test), 4))

Output

0.79

Change it and run: change the weights to [1, 1, 3, 1, 1] and run.

The logistic regression, the forest and the SVM count twice. The accuracy does not rise here: the equal vote was already good, and the weights are one more thing that would have to be chosen with cross-validation.

Python, continues from the cells above
with_nb = VotingClassifier(estimators=voters + [("nb", GaussianNB())], voting="soft")
with_nb.fit(X_train_scaled, y_train)

print(round(with_nb.score(X_test_scaled, y_test), 4))

Output

0.77

With Naive Bayes as a sixth voter the accuracy falls from 0.80 to 0.77: a weak voter with very confident, often wrong probabilities pulls the soft vote down. More voters are not always better.

10.11Hard or soft, with cross-validation

One test split of 200 applicants can mislead. The two votes compared with five folds of the training data:

Python, continues from the cells above
for voting in ["hard", "soft"]:
    scores = cross_val_score(VotingClassifier(estimators=voters, voting=voting), X_train_scaled, y_train, cv=5)
    print(voting, round(scores.mean(), 4))

Output

hard 0.7562
soft 0.75

In cross-validation hard voting is a little ahead, on the test data soft voting was: the difference between the two is smaller than the noise of a single split. Choose the kind of vote with cross-validation, like every other setting.

10.12The scores of every model

Python, continues from the cells above
results = [
    ("SVM", predicted),
    ("SVM, balanced", predicted_balanced),
    ("logistic regression", predicted_logistic),
    ("decision tree", predicted_tree),
    ("random forest", predicted_forest),
    ("k-nearest neighbours", predicted_knn),
    ("Naive Bayes", predicted_nb),
    ("hard voting", predicted_hard),
    ("soft voting", predicted_soft),
]

for name, model_predicted in results:
    print(name, round(accuracy_score(y_test, model_predicted), 4), round(recall_score(y_test, model_predicted), 4), round(f1_score(y_test, model_predicted), 4))

Output

SVM 0.76 0.4237 0.5102
SVM, balanced 0.755 0.7627 0.6475
logistic regression 0.765 0.5593 0.5841
decision tree 0.75 0.6441 0.6032
random forest 0.805 0.4407 0.5714
k-nearest neighbours 0.73 0.339 0.4255
Naive Bayes 0.705 0.6271 0.5564
hard voting 0.77 0.4746 0.549
soft voting 0.8 0.5085 0.6

Every line: the test accuracy, the recall of the bad credits and the F1-score, all on the same 200 applicants.

Python, continues from the cells above
import matplotlib.pyplot as plt

names = [name for name, model_predicted in results]
f1_scores = [f1_score(y_test, model_predicted) for name, model_predicted in results]

plt.barh(names, f1_scores)
plt.xlabel("test F1-score of the bad credits")
plt.title("The SVM, the models of earlier topics, and their vote")
plt.show()
Chart: The SVM, the models of earlier topics, and their vote

What the comparison shows:

  • Scaled and with the default settings, the SVM beats the baseline clearly (0.76 against 0.705); without scaling it was useless.
  • class_weight="balanced" made the SVM the best model for the bank's real goal: it finds the most bad credits and has the best F1-score.
  • Soft voting is more accurate than four of its five voters (0.80) and better balanced than the fifth, the random forest: almost the same accuracy, but more bad credits found and a higher F1-score. The forest is itself a vote of 100 trees, so it is a strong voter and a strong rival.
  • Soft voting beat hard voting on this test data, hard voting won in cross-validation: the difference is small. Weights and a weak voter did not help.

10.13What the mistakes cost the bank

The data set comes with a rule of the bank: a bad credit that is accepted (a false negative) costs 5, a good customer who is turned away (a false positive) costs 1. The cost of every model on the 200 test applicants:

Python, continues from the cells above
for name, model_predicted in results:
    matrix = confusion_matrix(y_test, model_predicted)
    cost = 5 * matrix[1, 0] + matrix[0, 1]
    print(name, cost)

Output

SVM 184
SVM, balanced 105
logistic regression 151
decision tree 134
random forest 171
k-nearest neighbours 210
Naive Bayes 147
hard voting 170
soft voting 156

matrix[1, 0] is the number of bad credits predicted good (FN), matrix[0, 1] the number of good ones predicted bad (FP). By the bank's own measure the balanced SVM is by far the best model: it misses the fewest bad credits. The plain SVM is one of the most expensive: only k-nearest neighbours costs more.

10.14A lower threshold for the soft vote

The soft vote has probabilities, so its threshold can be lowered, as in Topic 28:

Python, continues from the cells above
soft_prob = soft.predict_proba(X_test_scaled)[:, 1]
predicted_soft_03 = (soft_prob >= 0.3).astype(int)

matrix = confusion_matrix(y_test, predicted_soft_03)

print(matrix)
print(5 * matrix[1, 0] + matrix[0, 1])
print(round(recall_score(y_test, predicted_soft_03), 4))

Output

[[100  41]
 [ 12  47]]
101
0.7966

Change it and run: change 0.3 to 0.4 and run.

With the threshold 0.3 the vote misses only 12 bad credits and its cost falls to 101, a little below the balanced SVM. A threshold, like any other setting, should be chosen with cross-validation on the training data; here the test data only shows the effect. Two roads lead to the same goal: make mistakes on the rare class more expensive (class_weight), or lower the threshold of the probabilities.

Move the threshold of the soft vote of the project. A missed bad credit costs 5, a turned-away good customer 1.

Cost = 5 × 29 + 11 = 156. The balanced SVM of Part 8 costs 105.

At 0.5 the vote costs 156; around 0.3 it is cheapest. A very low threshold calls almost everyone bad, and the false alarms add up again.

Try it yourself

This task continues from the cells of Parts 7 to 10. Make a soft vote of only three voters: LogisticRegression(), RandomForestClassifier(random_state=42) and SVC(probability=True, random_state=42). Print its test accuracy, rounded to 4 decimals.
Show a hint
A list of three (name, model) pairs, then VotingClassifier(estimators=..., voting="soft"), fit and score.
Show the solution
Python, continues from the cells above
three = [("logistic", LogisticRegression()), ("forest", RandomForestClassifier(random_state=42)), ("svm", SVC(probability=True, random_state=42))]

vote = VotingClassifier(estimators=three, voting="soft")
vote.fit(X_train_scaled, y_train)

print(round(vote.score(X_test_scaled, y_test), 4))

Output

0.785

Try it yourself

This task continues from the cells of Parts 7 to 10. Predict "bad" when the soft vote's probability is at least 0.4. Print the bank's cost (5 × FN + FP), then the recall, rounded to 4 decimals.
Show a hint
(soft.predict_proba(X_test_scaled)[:, 1] >= 0.4).astype(int); in confusion_matrix(y_test, ...) FN is [1, 0] and FP is [0, 1].
Show the solution
Python, continues from the cells above
soft_prob = soft.predict_proba(X_test_scaled)[:, 1]
predicted_04 = (soft_prob >= 0.4).astype(int)

matrix = confusion_matrix(y_test, predicted_04)

print(5 * matrix[1, 0] + matrix[0, 1])
print(round(recall_score(y_test, predicted_04), 4))

Output

137
0.6102

11The workflow, step by step

The workflow, step by step
StepWhat is doneIn this project
1. Lookshape, first rows, the meaning of the columns1,000 applicants, 21 columns
2. Checkgaps and repeated rowsnone; "unknown" is a category
3. Numberssizes and spreadvery different sizes: scaling will be needed
4. Outlierscount them, decidereal loans: kept
5. Targettext to 0 and 1, the share of each classbad = 1, 30 percent
6. Unfair columnsremove what a decision must not usepersonal_status, foreign_worker
7. Encodeone-hot44 features
8. Splittraining and test data800 and 200; baseline 0.705
9. ScaleStandardScaler fitted on the training dataessential for the SVM
10. ModelSVC()accuracy 0.76, recall 0.42
11. Tunekernel, C, gamma with cross-validation; class_weightRBF, C=1; balanced: recall 0.76
12. Other modelsthe classifiers of earlier topics, each aloneforest 0.805, Naive Bayes weakest
13. Votehard and soft VotingClassifier; compared with cross-validationsoft: 0.80, F1 0.60, AUC 0.82
14. Comparethe same test data, the same measures, and the bank's costbalanced SVM (cost 105) and the soft vote with threshold 0.3 (101)

Try it yourself

(a) Which step comes before the split: the scaling or the one-hot encoding? (b) On which data is the scaler fitted? (c) Which kind of vote has an AUC? (d) Which measure follows the bank's real goal best?

Show a hint
Look at Steps 7 to 14 of the table.
Show the solution

Answer: (a) the one-hot encoding; (b) the training data; (c) the soft vote; (d) the cost (or the recall of bad).

The encoding only renames categories, so it may come first; the scaler learns means and spreads and must see only the training data; a soft vote has probabilities; the bank pays five times more for a missed bad credit.

12Common mistakes

Common mistakes
MistakeWhy it is wrongRight
Training an SVM on unscaled data.The largest numbers decide every distance; the model found 3 of 59 bad credits.Scale with StandardScaler fitted on the training data.
Choosing C or gamma with the test data.The test score is then no longer an honest judge.Cross-validation on the training data.
Making C very large "to fit better".The street becomes narrow and follows every training row: overfitting.Try 0.01 to 100 and compare with cross-validation.
Judging the credit model by its accuracy only.70 percent of the applicants are good: saying "good" to everyone gives 0.705.Look at the recall and the F1-score of the bad class.
Asking an SVC() for predict_proba.It has no probabilities by default.probability=True, or decision_function for the AUC.
Using soft voting with an SVM without probability=True.Soft voting needs predict_proba from every voter.SVC(probability=True) in the list of voters.
Asking a hard vote for predict_proba or the AUC.A majority of classes has no probabilities.Soft voting, or compare hard votes by accuracy, recall and F1.
Putting every model into the vote.A weak voter pulls a soft vote down.Good and different voters, each checked alone first.
Expecting a vote to beat every model.A strong single model (here the forest) can stay better.Compare honestly on the same test data.
Training an SVM on millions of rows.The training time grows very fast with the rows.LinearSVC, logistic regression or boosting.

13Solved problems

The first four problems are short and solved by hand. Problems 5 to 16 are one project on german_credit.csv, solved step by step like a notebook: every cell continues from the cells above it. It is the workflow of the lesson once more, with another split.

Problem 1: The width of the street

A linear SVM has the weights w=(3,4)w = (3, 4). How wide is its street?

Idea. The margin is 2∥w∥\frac{2}{\lVert w \rVert} (Part 2).

∥w∥=32+42=25=5margin=25=0.4\begin{aligned} \lVert w \rVert &= \sqrt{3^2 + 4^2} = \sqrt{25} = 5 \\[6pt] \text{margin} &= \frac{2}{5} = 0.4 \end{aligned}

Why: large weights mean a narrow street; the SVM tries to keep the weights small.

Problem 2: Which side of the street?

A linear SVM has w=(1,−2)w = (1, -2) and b=0.5b = 0.5. Compute f(x)f(x) for the applicants (3, 1) and (1, 1), and say where each one lies.

Idea. f(x)=w1x1+w2x2+bf(x) = w_1 x_1 + w_2 x_2 + b; positive means class +1, and ∣f∣<1\lvert f \rvert < 1 means inside the street (Part 2).

f(3,1)=1×3−2×1+0.5=1.5f(1,1)=1×1−2×1+0.5=−0.5\begin{aligned} f(3, 1) &= 1 \times 3 - 2 \times 1 + 0.5 = 1.5 \\[4pt] f(1, 1) &= 1 \times 1 - 2 \times 1 + 0.5 = -0.5 \end{aligned}

Why: (3, 1) is class +1 and outside the street (1.5 ≥ 1). (1, 1) is class −1 but inside the street (|−0.5| < 1): an uncertain case.

Problem 3: The RBF kernel

Compute the RBF similarity of the rows a=(1,2)a = (1, 2) and b=(2,4)b = (2, 4) with γ=0.5\gamma = 0.5.

Idea. K(a,b)=e−γ∥a−b∥2K(a, b) = e^{-\gamma \lVert a - b \rVert^2} (Part 4).

∥a−b∥2=(1−2)2+(2−4)2=1+4=5K=e−0.5×5=e−2.5=0.082\begin{aligned} \lVert a - b \rVert^2 &= (1 - 2)^2 + (2 - 4)^2 = 1 + 4 = 5 \\[6pt] K &= e^{-0.5 \times 5} = e^{-2.5} = 0.082 \end{aligned}

Why: the rows are 2.24 apart, so with γ=0.5\gamma = 0.5 they are only a little similar; with γ=0.1\gamma = 0.1 the similarity would be e−0.5=0.607e^{-0.5} = 0.607.

Problem 4: Hard and soft voting

Three models give an applicant the probabilities of "bad" 0.8, 0.3 and 0.45. What do hard and soft voting decide?

Idea. Hard: the majority of the classes; soft: the mean of the probabilities (Part 9).

hard:bad, good, good  ⇒  good (1 against 2)soft:0.8+0.3+0.453=1.553=0.517  ⇒  bad\begin{aligned} \text{hard:}\quad & \text{bad, good, good} \;\Rightarrow\; \text{good (1 against 2)} \\[8pt] \text{soft:}\quad & \frac{0.8 + 0.3 + 0.45}{3} = \frac{1.55}{3} = 0.517 \;\Rightarrow\; \text{bad} \end{aligned}

Why: the first model is very sure of "bad", the other two only a little sure of "good"; soft voting hears how sure they are.

Problem 5: Read and check

Read the file. Print its shape, the number of gaps and the number of repeated rows.

Idea. The first look (Part 7).

Python
import pandas as pd

df = pd.read_csv("german_credit.csv")

print(df.shape)
print(df.isna().sum().sum())
print(df.duplicated().sum())

Output

(1000, 21)
0
0

Why: 1,000 applicants, nothing to fill, nothing to drop.

Problem 6: The target and two columns

Turn risk into 1 for bad and 0 for good, drop personal_status and foreign_worker, and print the share of bad credits.

Idea. The positive class is the one to find; columns a fair decision must not use are removed (Part 7).

Python, continues from the cells above
df["risk"] = (df["risk"] == "bad").astype(int)
df = df.drop(columns=["personal_status", "foreign_worker"])

print(df["risk"].mean())

Output

0.3

Why: 30 percent bad: the baseline is 70 percent.

Problem 7: Encode

One-hot encode the eleven text columns with drop_first=True and dtype=int. Print the shape.

Idea. An SVM needs numbers (Part 6).

Python, continues from the cells above
text_columns = ["checking_account", "credit_history", "purpose", "savings", "employment_years", "other_debtors", "property", "other_installments", "housing", "job", "telephone"]

df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)

print(df.shape)

Output

(1000, 45)

Why: 44 features and the target.

Problem 8: Split

Make X and y and split them with test_size=0.25 and random_state=7. Print the shapes and the share of bad credits in the test data.

Idea. The split comes before any value is learned from the data.

Python, continues from the cells above
from sklearn.model_selection import train_test_split

X = df.drop(columns=["risk"])
y = df["risk"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=7)

print(X_train.shape, X_test.shape)
print(round(y_test.mean(), 3))

Output

(750, 44) (250, 44)
0.26

Why: 750 and 250 applicants; the baseline on this test data is 1 minus the printed share.

Problem 9: Scale

Fit a StandardScaler on the training data and scale both parts. Print the mean of the first scaled training column, rounded to 3 decimals.

Idea. Scaling is essential for an SVM (Part 6).

Python, continues from the cells above
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

print(abs(X_train_scaled[:, 0].mean().round(3)))

Output

0.0

Why: 0: the scaler centres every training column.

Problem 10: The default SVM

Train an SVC() on the scaled data. Print its test accuracy and its recall, rounded to 4 decimals.

Idea. The RBF kernel with C=1 (Part 8).

Python, continues from the cells above
from sklearn.svm import SVC
from sklearn.metrics import recall_score, f1_score

svm = SVC()
svm.fit(X_train_scaled, y_train)

print(round(svm.score(X_test_scaled, y_test), 4))
print(round(recall_score(y_test, svm.predict(X_test_scaled)), 4))

Output

0.796
0.4462

Why: above the baseline, but less than half of the bad credits are found.

Problem 11: Without scaling

Train an SVC() on the unscaled data. Print its test accuracy and recall.

Idea. The damage of missing scaling (Part 8).

Python, continues from the cells above
svm_raw = SVC()
svm_raw.fit(X_train, y_train)

print(round(svm_raw.score(X_test, y_test), 4))
print(round(recall_score(y_test, svm_raw.predict(X_test)), 4))

Output

0.736
0.0615

Why: almost no bad credit is found: the credit amount decides alone.

Problem 12: C with cross-validation

For C = 0.1, 1 and 10, print C and the mean accuracy of a 5-fold cross-validation on the scaled training data, rounded to 4 decimals.

Idea. C is chosen without the test data (Part 8).

Python, continues from the cells above
from sklearn.model_selection import cross_val_score

for C in [0.1, 1, 10]:
    scores = cross_val_score(SVC(C=C), X_train_scaled, y_train, cv=5)
    print(C, round(scores.mean(), 4))

Output

0.1 0.6867
1 0.7307
10 0.7067

Why: C = 1 is best; 0.1 says "good" for everyone, 10 overfits.

Problem 13: Balanced

Train an SVC(class_weight="balanced"). Print its recall and F1-score, rounded to 4 decimals.

Idea. A mistake on the bad class costs more (Part 8).

Python, continues from the cells above
svm_balanced = SVC(class_weight="balanced")
svm_balanced.fit(X_train_scaled, y_train)

predicted_balanced = svm_balanced.predict(X_test_scaled)

print(round(recall_score(y_test, predicted_balanced), 4))
print(round(f1_score(y_test, predicted_balanced), 4))

Output

0.6462
0.5833

Why: many more bad credits are found.

Problem 14: Two other models

Train a LogisticRegression() and a RandomForestClassifier(random_state=42). Print the test accuracy of each, rounded to 4 decimals.

Idea. Every voter is checked alone first (Part 10).

Python, continues from the cells above
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier

logistic = LogisticRegression()
logistic.fit(X_train_scaled, y_train)

forest = RandomForestClassifier(random_state=42)
forest.fit(X_train_scaled, y_train)

print(round(logistic.score(X_test_scaled, y_test), 4))
print(round(forest.score(X_test_scaled, y_test), 4))

Output

0.82
0.804

Why: both are clearly above the baseline: good voters.

Problem 15: Hard and soft voting

Vote with logistic regression, the random forest and SVC(probability=True, random_state=42), once hard and once soft. Print both test accuracies, rounded to 4 decimals.

Idea. The same voters, two ways to combine them (Part 9).

Python, continues from the cells above
from sklearn.ensemble import VotingClassifier

voters = [("logistic", LogisticRegression()), ("forest", RandomForestClassifier(random_state=42)), ("svm", SVC(probability=True, random_state=42))]

hard = VotingClassifier(estimators=voters, voting="hard")
hard.fit(X_train_scaled, y_train)

soft = VotingClassifier(estimators=voters, voting="soft")
soft.fit(X_train_scaled, y_train)

print(round(hard.score(X_test_scaled, y_test), 4))
print(round(soft.score(X_test_scaled, y_test), 4))

Output

0.82
0.812

Why: on this split hard voting is a little better: the order of the two can change from split to split.

Problem 16: The AUC of the soft vote

Print the AUC of the soft vote, rounded to 4 decimals.

Idea. Only a soft vote has probabilities (Part 9).

Python, continues from the cells above
from sklearn.metrics import roc_auc_score

print(round(roc_auc_score(y_test, soft.predict_proba(X_test_scaled)[:, 1]), 4))

Output

0.8393

Why: the soft vote ranks the applicants well; the hard vote has no AUC.

14Practice

Sixteen problems. The first four are solved on paper. Problems 5 to 16 are one project in Python on german_credit.csv, the file of the lesson (the whole table): its steps continue from one another, like the cells of a notebook, from reading the raw file to the vote. Under every problem there is a hint and a solution.

14.1Group A: by hand

  1. 1.A linear SVM has the weights w=(6,8)w = (6, 8). How wide is its street?

    Show a hint
    The margin is 2∥w∥\frac{2}{\lVert w \rVert}.
    Show one possible solution

    Answer: 0.2.

    ∥w∥=62+82=100=10margin=210=0.2\begin{aligned} \lVert w \rVert &= \sqrt{6^2 + 8^2} = \sqrt{100} = 10 \\[6pt] \text{margin} &= \frac{2}{10} = 0.2 \end{aligned}
  2. 2.A linear SVM has w=(2,1)w = (2, 1) and b=−4b = -4. Compute f(x)f(x) for (1, 1) and (3, 1). Which class does each get, and which one lies exactly on an edge of the street?

    Show a hint
    f(x)=2x1+x2−4f(x) = 2x_1 + x_2 - 4; an edge is f=+1f = +1 or f=−1f = -1.
    Show one possible solution

    Answer: f(1,1)=−1f(1, 1) = -1: class −1, on the edge; f(3,1)=3f(3, 1) = 3: class +1.

    f(1,1)=2+1−4=−1f(3,1)=6+1−4=3\begin{aligned} f(1, 1) &= 2 + 1 - 4 = -1 \\[4pt] f(3, 1) &= 6 + 1 - 4 = 3 \end{aligned}
  3. 3.(a) Compute the RBF similarity of two rows with ∥a−b∥2=10\lVert a - b \rVert^2 = 10 and γ=0.1\gamma = 0.1. Give 3 decimals. (b) Compute the polynomial kernel (a⋅b+1)2(a \cdot b + 1)^2 for a=(1,2)a = (1, 2) and b=(2,1)b = (2, 1).

    Show a hint
    (a) e−γ∥a−b∥2e^{-\gamma \lVert a - b \rVert^2}; (b) first the dot product a⋅b=1×2+2×1a \cdot b = 1 \times 2 + 2 \times 1.
    Show one possible solution

    Answer: (a) 0.368; (b) 25.

    (a)e−0.1×10=e−1=0.368(b)a⋅b=1×2+2×1=4(4+1)2=25\begin{aligned} \text{(a)}\quad & e^{-0.1 \times 10} = e^{-1} = 0.368 \\[6pt] \text{(b)}\quad & a \cdot b = 1 \times 2 + 2 \times 1 = 4 \\[2pt] & (4 + 1)^2 = 25 \end{aligned}
  4. 4.Three models give an applicant the probabilities of "bad" 0.9, 0.3 and 0.4. (a) What does hard voting decide? (b) Soft voting with equal weights? Give the soft vote with 3 decimals. (c) Soft voting with the weights 1, 2 and 2?

    Show a hint
    With weights, the soft vote is the weighted mean ∑weight×probability∑weights\frac{\sum \text{weight} \times \text{probability}}{\sum \text{weights}}.
    Show one possible solution

    Answer: (a) good; (b) bad (0.533); (c) good (0.46).

    (b)0.9+0.3+0.43=1.63=0.533⇒  bad(c)1×0.9+2×0.3+2×0.45=2.35=0.46  ⇒  good\begin{aligned} \text{(b)}\quad & \frac{0.9 + 0.3 + 0.4}{3} = \frac{1.6}{3} = 0.533 \\[2pt] & \Rightarrow\; \text{bad} \\[8pt] \text{(c)}\quad & \frac{1 \times 0.9 + 2 \times 0.3 + 2 \times 0.4}{5} \\[4pt] & = \frac{2.3}{5} = 0.46 \;\Rightarrow\; \text{good} \end{aligned}

    Hard: bad, good, good, so good.

14.2Group B: one project in Python

The same workflow as in the lesson, on the same raw file, with another split: test_size=0.3 with random_state=1. The steps continue from one another, like the cells of a notebook: every step uses what the steps before it created.

Steps 5 to 8: from the raw file to the split

Read the file, the target as 0 and 1, the fair columns, the one-hot encoding, the split.

  1. 5.Read german_credit.csv into df. Print the shape, then the number of bad credits.
    Show a hint
    df = pd.read_csv("german_credit.csv"), then print(df.shape) and print((df["risk"] == "bad").sum()).
    Show one possible solution
    Python
    import pandas as pd
    
    df = pd.read_csv("german_credit.csv")
    
    print(df.shape)
    print((df["risk"] == "bad").sum())

    Output

    (1000, 21)
    300
  2. 6.Turn risk into 1 for bad and 0 for good, and drop personal_status and foreign_worker. Print the number of columns. This step continues from Step 5.
    Show a hint
    df["risk"] = (df["risk"] == "bad").astype(int), then df.drop(columns=[...]) and len(df.columns).
    Show one possible solution
    Python, continues from the cells above
    df["risk"] = (df["risk"] == "bad").astype(int)
    df = df.drop(columns=["personal_status", "foreign_worker"])
    
    print(len(df.columns))

    Output

    19
  3. 7.One-hot encode the columns of text_columns with drop_first=True and dtype=int. Print the number of columns.
    Show a hint
    df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int), then len(df.columns).
    Show one possible solution
    Python, continues from the cells above
    text_columns = ["checking_account", "credit_history", "purpose", "savings", "employment_years", "other_debtors", "property", "other_installments", "housing", "job", "telephone"]
    
    df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)
    
    print(len(df.columns))

    Output

    45
  4. 8.Make X (all columns without risk) and y. Split them with test_size=0.3 and random_state=1. Print the number of test applicants, then how many of them are bad.
    Show a hint
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1), then len(y_test) and y_test.sum().
    Show one possible solution
    Python, continues from the cells above
    from sklearn.model_selection import train_test_split
    
    X = df.drop(columns=["risk"])
    y = df["risk"]
    
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
    
    print(len(y_test))
    print(y_test.sum())

    Output

    300
    86

Steps 9 to 12: scaling and the SVM

The StandardScaler, an SVC and its accuracy, the support vectors, C with cross-validation.

  1. 9.Fit a StandardScaler on the training data and scale both parts into X_train_scaled and X_test_scaled. Print the shape of X_test_scaled.
    Show a hint
    scaler.fit_transform(X_train) and scaler.transform(X_test).
    Show one possible solution
    Python, continues from the cells above
    from sklearn.preprocessing import StandardScaler
    
    scaler = StandardScaler()
    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)
    
    print(X_test_scaled.shape)

    Output

    (300, 44)
  2. 10.Train an SVC() called svm on the scaled data. Print its test accuracy, rounded to 4 decimals.
    Show a hint
    svm = SVC(), svm.fit(X_train_scaled, y_train), then svm.score(X_test_scaled, y_test).
    Show one possible solution
    Python, continues from the cells above
    from sklearn.svm import SVC
    
    svm = SVC()
    svm.fit(X_train_scaled, y_train)
    
    print(round(svm.score(X_test_scaled, y_test), 4))

    Output

    0.74
  3. 11.Print the number of support vectors of svm for each class, then their total.
    Show a hint
    svm.n_support_ holds one number per class; .sum() adds them up.
    Show one possible solution
    Python, continues from the cells above
    print(svm.n_support_)
    print(svm.n_support_.sum())

    Output

    [272 207]
    479
  4. 12.For C = 0.1, 1 and 10, print C and the mean accuracy of a 5-fold cross-validation of SVC(C=C) on the scaled training data, rounded to 4 decimals.
    Show a hint
    A loop over [0.1, 1, 10] with cross_val_score(SVC(C=C), X_train_scaled, y_train, cv=5).mean().
    Show one possible solution
    Python, continues from the cells above
    from sklearn.model_selection import cross_val_score
    
    for C in [0.1, 1, 10]:
        scores = cross_val_score(SVC(C=C), X_train_scaled, y_train, cv=5)
        print(C, round(scores.mean(), 4))

    Output

    0.1 0.6943
    1 0.7457
    10 0.7314

Steps 13 to 16: the class weight and the vote

A balanced SVM, two other models, a hard and a soft vote, the AUC and a chart.

  1. 13.Train an SVC(class_weight="balanced") and print its test recall, rounded to 4 decimals.
    Show a hint
    fit on the scaled training data, then recall_score(y_test, model.predict(X_test_scaled)).
    Show one possible solution
    Python, continues from the cells above
    from sklearn.metrics import recall_score
    
    svm_balanced = SVC(class_weight="balanced")
    svm_balanced.fit(X_train_scaled, y_train)
    
    print(round(recall_score(y_test, svm_balanced.predict(X_test_scaled)), 4))

    Output

    0.5814
  2. 14.Train a LogisticRegression() and a RandomForestClassifier(random_state=42) on the scaled data. Print the test accuracy of each, rounded to 4 decimals.
    Show a hint
    fit(X_train_scaled, y_train) for each model, then score(X_test_scaled, y_test).
    Show one possible solution
    Python, continues from the cells above
    from sklearn.linear_model import LogisticRegression
    from sklearn.ensemble import RandomForestClassifier
    
    logistic = LogisticRegression()
    logistic.fit(X_train_scaled, y_train)
    
    forest = RandomForestClassifier(random_state=42)
    forest.fit(X_train_scaled, y_train)
    
    print(round(logistic.score(X_test_scaled, y_test), 4))
    print(round(forest.score(X_test_scaled, y_test), 4))

    Output

    0.7567
    0.7767
  3. 15.Make a hard VotingClassifier called hard with the voters in voters and print its test accuracy, rounded to 4 decimals.
    Show a hint
    hard = VotingClassifier(estimators=voters, voting="hard"), fit on the scaled training data, then score.
    Show one possible solution
    Python, continues from the cells above
    from sklearn.ensemble import VotingClassifier
    
    voters = [("logistic", LogisticRegression()), ("forest", RandomForestClassifier(random_state=42)), ("svm", SVC(probability=True, random_state=42))]
    
    hard = VotingClassifier(estimators=voters, voting="hard")
    hard.fit(X_train_scaled, y_train)
    
    print(round(hard.score(X_test_scaled, y_test), 4))

    Output

    0.7533
  4. 16.Make a soft VotingClassifier called soft with the same voters. Print its test accuracy and its AUC, rounded to 4 decimals. Then draw the test accuracies of svm, hard and soft as a bar chart.
    Show a hint
    voting="soft"; roc_auc_score(y_test, soft.predict_proba(X_test_scaled)[:, 1]); plt.bar(names, accuracies) and plt.show().
    Show one possible solution
    Python, continues from the cells above
    import matplotlib.pyplot as plt
    from sklearn.metrics import roc_auc_score
    
    soft = VotingClassifier(estimators=voters, voting="soft")
    soft.fit(X_train_scaled, y_train)
    
    print(round(soft.score(X_test_scaled, y_test), 4))
    print(round(roc_auc_score(y_test, soft.predict_proba(X_test_scaled)[:, 1]), 4))
    
    names = ["SVM", "hard vote", "soft vote"]
    accuracies = [svm.score(X_test_scaled, y_test), hard.score(X_test_scaled, y_test), soft.score(X_test_scaled, y_test)]
    
    plt.bar(names, accuracies)
    plt.ylabel("test accuracy")
    plt.show()

    Output

    0.76
    0.7652
    The chart this code draws

15Check yourself

Twelve questions. Every question has one right answer.

Question 1

1.Which line does a support vector machine choose between two classes?

Question 2

2.What are the support vectors?

Question 3

3.A linear SVM has the weights w=(3,4)w = (3, 4). How wide is its street?

Question 4

4.What happens when C is made very large?

Question 5

5.What does the kernel trick do?

Question 6

6.What does a very large gamma do to an RBF kernel?

Question 7

7.Why must the features of an SVM be scaled?

Question 8

8.What does class_weight="balanced" do in the project?

Question 9

9.Three models give the probabilities 0.8, 0.3 and 0.45 of "bad". What does soft voting decide?

Question 10

10.Why can a hard VotingClassifier not give an AUC?

Question 11

11.What does an SVM need for soft voting?

Question 12

12.When does a vote help most?

0 of 12 answered.

16Summary

Summary
Formula or ruleMeaning
Decision functionf(x)=w⋅x+bf(x) = w \cdot x + bpositive: class +1; negative: class −1; ∣f∣<1\lvert f \rvert < 1: inside the street
Margin2∥w∥\frac{2}{\lVert w \rVert}the width of the street
Hinge lossmax⁡(0, 1−y f(x))\max\bigl(0,\ 1 - y\,f(x)\bigr)the penalty of a row inside the street or on the wrong side
Soft margin12∥w∥2+C∑losses\tfrac{1}{2}\lVert w \rVert^2 + C \sum \text{losses}C: the cost of a mistake
RBF kernele−γ∥a−b∥2e^{-\gamma \lVert a - b \rVert^2}the similarity of two rows; γ\gamma: how far a row reaches
Soft votethe mean of the probabilitiesthe class with the larger mean wins
Summary
CodeWhat it does
SVC()the support vector classifier (RBF kernel, C=1, gamma="scale")
SVC(kernel="linear")a straight border; also "poly", "sigmoid"
SVC(C=..., gamma=...)the cost of a mistake, the reach of a row
SVC(class_weight="balanced")more weight for the smaller class
SVC(probability=True)adds predict_proba
svm.decision_function(X)f(x)f(x) for every row
svm.n_support_, svm.support_vectors_the support vectors
VotingClassifier(estimators=..., voting="hard")majority of the classes
VotingClassifier(estimators=..., voting="soft", weights=...)mean of the probabilities

Rules to keep

  1. An SVM separates the classes by the widest street; only the support vectors decide where it lies.
  2. Always scale the features of an SVM, and encode the text columns.
  3. Choose C (and gamma for RBF) with cross-validation: small values underfit, large values overfit.
  4. Start with the RBF kernel; try the linear one for many features.
  5. When the rare class matters, use class_weight="balanced" and judge by recall and F1.
  6. Vote with good and different models; soft voting needs predict_proba from every voter.

What comes next

Topic 36 uses support vector machines and voting for numbers: SVR, which puts a street of tolerance around a regression line, and VotingRegressor, which averages the predictions of several regression models.