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.
Lesson notebook
The lesson as a Jupyter notebook: the credit project cell by cell, from the raw file and every preprocessing step to the SVM, its kernels, C and gamma, the models of earlier topics, their hard and soft vote and the bank's cost, and the sixteen solved problems.
topic-35-svm-and-voting-classification.ipynb, 83 KB
Practice notebook
The same project on the credit data in twelve steps, from reading the raw file and scaling to an SVM, its support vectors, C, a balanced SVM and a hard and a soft vote, with a hint and a hidden solution for each step.
topic-35-practice.ipynb, 19 KB
Data file: the loan applicants
1,000 loan applicants of a German bank with 21 columns, the UCI Statlog (German Credit Data) data set (donated by Prof. Hans Hofmann, University of Hamburg; UCI Machine Learning Repository, licence CC BY 4.0) with its codes written as words. Not cleaned in any other way.
german_credit.csv, 142 KB
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.What a support vector machine is, where and when it is used, and its strengths and weaknesses
- 2.The widest street: the separating line, the margin and the support vectors, worked by hand
- 3.The soft margin: why
Cdecides between a wide street with some mistakes and a narrow street with none - 4.The kernel trick, and how the linear, polynomial, RBF and sigmoid kernels draw their borders
- 5.Every hyperparameter of
SVCand its role:C,kernel,gamma,degree,coef0,class_weight,probabilityand the rest - 6.Why scaling is essential for an SVM, and the preprocessing of this and the coming models
- 7.Voting: why several models can be better than one, hard voting and soft voting, and
VotingClassifier - 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
| Word | Meaning |
|---|---|
| Support vector machine (SVM) | a model that separates the classes by the widest possible street |
| Hyperplane | the separating border: a line in two dimensions, a plane in three, a "hyperplane" in more |
| Margin | the width of the street between the classes |
| Support vectors | the training rows on the edge of the street (or inside it): only they decide where the border lies |
| Soft margin | a street that allows some rows inside it or on the wrong side, controlled by C |
| Kernel | a function that measures how similar two rows are; it lets the SVM draw curved borders |
| Hard voting | each model votes for a class; the class with the most votes wins |
| Soft voting | the 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
| Situation | SVM? |
|---|---|
| Hundreds to tens of thousands of rows | yes: its strength |
| Many features, even more features than rows | yes: it works well in high dimensions |
| A clear gap between the classes | yes: the widest street finds it |
| Millions of rows | no: training grows roughly with the square of the rows; use LinearSVC, a linear model or boosting |
| You need exact probabilities | with care: they need probability=True and are an add-on |
| You must explain each decision | not with curved kernels: a tree or logistic regression is easier to explain |
1.4Strengths and weaknesses
| Strengths | Weaknesses |
|---|---|
| Works well with many features, also more features than rows | Slow on large data sets: the training time grows fast with the number of rows |
The widest street resists overfitting when C is chosen well | Needs scaled features, otherwise it fails (the project shows how badly) |
| Kernels draw curved borders without new columns | C, kernel and gamma must be chosen, and they matter |
| Only the support vectors are needed to predict | No 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
Show a hint
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).
| Applicant | Duration | Amount | Class |
|---|---|---|---|
| A | 1 | 1 | good (−1) |
| B | 2 | 1 | good (−1) |
| C | 1 | 2 | good (−1) |
| D | 3 | 3 | bad (+1) |
| E | 4 | 3 | bad (+1) |
| F | 3 | 4 | bad (+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
and predicts class +1 when and class −1 when . The two edges of the street are the lines and .
The good applicants nearest to the bad ones are B and C (both with ); the nearest bad applicant is D (). The widest street runs between the lines and , and its middle is . With equal weights , the two edges give two equations:
Subtracting the first from the second: , so , and .
2.3The width of the street
The margin is 2 divided by the length of w:
This is exactly the distance between the lines and . The support vectors are B, C and D: they lie on the edges (, and ). A, E and F lie further away and do not matter for the street.
- good
- bad
- the border
2.4Deciding for new applicants
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.
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
Show a hint
Show the solution
Answer: (a) 0.333; (b) yes; (c) 1.414.
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:
with for bad and for good. A row beyond its edge () pays 0. G under the old line of Part 2:
3.3What the SVM minimises
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:
| The old wide line | A narrow line through G's edge | |
|---|---|---|
| w and b | , | , |
| Sum of the losses | 1.667 (only G) | 0 |
| Margin | 2.121 | |
| Total with C = 1 | 8 | |
| Total with C = 1000 | 8 |
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).
C = 1
margin 2.53, one mistake
C = 1000
margin 0.5, no mistakes
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.
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
Show a hint
Show the solution
Answer: (a) 1.4; (b) 0; (c) 3.8; (d) narrower.
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 | −3 | −2 | −1 | 0 | 1 | 2 | 3 |
|---|---|---|---|---|---|---|---|
| 9 | 4 | 1 | 0 | 1 | 4 | 9 | |
| class | bad | bad | good | good | good | bad | bad |
In the new column the good ones have and the bad ones : the straight line 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.
one feature x
no single threshold works
the points (x, x²)
the line x² = 2.5 separates them
- good
- bad
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 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
| Kernel | kernel= | Similarity | The border | When to use |
|---|---|---|---|---|
| Linear | "linear" | a straight line (a flat hyperplane) | many features (texts), or when a simple model is enough | |
| Polynomial | "poly" | curves of the given degree | when features interact; rarely the best | |
| RBF (Gaussian) | "rbf" (default) | any shape: islands and bends | the usual first choice | |
| Sigmoid | "sigmoid" | S-shaped borders, like a small neural network | rarely; 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 gets a weight , and the decision function adds up its similarities to the new row :
The sum runs over the support vectors only; every other training row has and plays no part. Each weight 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 :
gamma sets how fast the similarity falls with the distance:
- small : even distant rows are similar; every row influences a wide area; the border is smooth (risk: underfitting);
- large : 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 ; after a StandardScaler the variance is 1, so it is .
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:
kernel="linear"
kernel="poly"
kernel="rbf"
kernel="sigmoid"
- bad
- good
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.
gamma = 0.1
gamma = 1
gamma = 10
- bad
- good
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").
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
Show a hint
Show the solution
Answer: (a) 0.368; (b) 9; (c) RBF; (d) linear.
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).
| Hyperparameter | Default | Role |
|---|---|---|
C | 1.0 | the 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 , \"auto\" is . |
degree | 3 | only for poly: the degree of the curves |
coef0 | 0.0 | only for poly and sigmoid: the constant inside the kernel |
class_weight | None | "balanced" makes a mistake on the smaller class more expensive (C is multiplied by the class weight): more of the rare class is found |
probability | False | True adds predict_proba (needed for soft voting); the training is about five times slower, because it uses an inner cross-validation |
random_state | None | only used when probability=True |
shrinking | True | a speed trick of the solver; the result is the same |
tol | 0.001 | when the solver may stop |
cache_size | 200 | memory (MB) for kernel values: a speed setting |
max_iter | -1 | a 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_ties | False | for 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
predict_proba? (d) Which one is used only by the polynomial kernel?Show a hint
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.
SVCdoes 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.
| Model (topic) | Scaling | Encoding of text | Outliers in the features | Missing values |
|---|---|---|---|---|
| Linear regression (22) | not needed for the predictions | needed | sensitive | fill |
| Ridge, Lasso, logistic regression (26, 27) | needed | needed | sensitive | fill |
| Decision tree, random forest, bagged trees (29, 30, 31) | not needed | needed | robust | fill (recent scikit-learn can handle them) |
| k-nearest neighbours (32, 33) | essential: distances | needed; few, useful columns | sensitive | fill |
| Naive Bayes (34) | not needed | codes for Categorical, one-hot for Gaussian | sensitive (Gaussian) | fill |
| Support vector machines (35, 36) | essential: distances and dot products | needed (one-hot) | a little: they can become support vectors | fill |
| Voting (35, 36) | as the models inside | as the models inside | as the models inside | fill |
| Gradient boosting, XGBoost, LightGBM, CatBoost (37 to 40) | not needed | needed (CatBoost and LightGBM can also take categories directly) | robust | XGBoost, LightGBM and CatBoost handle them |
| k-means, DBSCAN, PCA (43, 44) | essential: distances and variances | needed | sensitive | fill |
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
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
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.
Loading the table ...
7.1Step 1: read and look
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:
| Column | Meaning |
|---|---|
checking_account | the balance of the checking account: < 0 DM, 0 to 200 DM, >= 200 DM, or no account (DM: Deutsche Mark) |
duration_months | the duration of the loan in months |
credit_history | how earlier loans were paid back |
purpose | what the loan is for: new car, used car, furniture, radio or TV, education, business, ... |
credit_amount | the amount of the loan in DM |
savings | the savings: < 100 DM up to >= 1000 DM, or unknown |
employment_years | how long the applicant has worked for the present employer |
installment_rate | the monthly payment as a share of the disposable income (1 to 4) |
personal_status | sex and marital status |
other_debtors | none, a co-applicant or a guarantor |
residence_years | years at the present home (1 to 4) |
property | the most valuable property: real estate, savings or insurance, car or other, none known |
age | the age in years |
other_installments | other loans being paid off: bank, stores, none |
housing | rent, own, for free |
existing_credits | the number of loans at this bank |
job | the kind of job |
dependents | the number of people the applicant supports |
telephone | a telephone registered in the applicant's name |
foreign_worker | whether the applicant is a foreign worker |
risk | the target: good or bad |
7.2Step 2: check for gaps and repeated rows
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
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.
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
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:
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
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
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
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
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
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
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
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
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
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
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
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 ), plus the bias intercept_:
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": (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:
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
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
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 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:
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).
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
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
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
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
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:
| Logistic regression | Random forest | SVM | Hard vote | Soft vote (the mean) | |
|---|---|---|---|---|---|
| Applicant 1 | 0.90 → bad | 0.40 → good | 0.45 → good | 1 against 2: good | : bad |
| Applicant 2 | 0.55 → bad | 0.60 → bad | 0.10 → good | 2 against 1: bad | : 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
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
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:
| Hyperparameter | Default | Role |
|---|---|---|
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) |
weights | None | how much each model counts; None means equally |
n_jobs | None | how many models are trained at the same time |
flatten_transform | True | the shape of the output of transform (the models' probabilities side by side) |
verbose | False | print 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
Show a hint
Show the solution
Answer: (a) good; (b) 0.483; (c) good; (d) 0.53.
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)
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)
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)
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)
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)
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
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
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:
hard.predict_proba(X_test_scaled)Error
AttributeError: This 'VotingClassifier' has no attribute 'predict_proba'
10.8Soft voting
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
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
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.
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:
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
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.
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()
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:
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:
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
LogisticRegression(), RandomForestClassifier(random_state=42) and SVC(probability=True, random_state=42). Print its test accuracy, rounded to 4 decimals.Show a hint
VotingClassifier(estimators=..., voting="soft"), fit and score.Show the solution
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
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
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
| Step | What is done | In this project |
|---|---|---|
| 1. Look | shape, first rows, the meaning of the columns | 1,000 applicants, 21 columns |
| 2. Check | gaps and repeated rows | none; "unknown" is a category |
| 3. Numbers | sizes and spread | very different sizes: scaling will be needed |
| 4. Outliers | count them, decide | real loans: kept |
| 5. Target | text to 0 and 1, the share of each class | bad = 1, 30 percent |
| 6. Unfair columns | remove what a decision must not use | personal_status, foreign_worker |
| 7. Encode | one-hot | 44 features |
| 8. Split | training and test data | 800 and 200; baseline 0.705 |
| 9. Scale | StandardScaler fitted on the training data | essential for the SVM |
| 10. Model | SVC() | accuracy 0.76, recall 0.42 |
| 11. Tune | kernel, C, gamma with cross-validation; class_weight | RBF, C=1; balanced: recall 0.76 |
| 12. Other models | the classifiers of earlier topics, each alone | forest 0.805, Naive Bayes weakest |
| 13. Vote | hard and soft VotingClassifier; compared with cross-validation | soft: 0.80, F1 0.60, AUC 0.82 |
| 14. Compare | the same test data, the same measures, and the bank's cost | balanced SVM (cost 105) and the soft vote with threshold 0.3 (101) |
Try it yourself
Show a hint
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
| Mistake | Why it is wrong | Right |
|---|---|---|
| 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 . How wide is its street?
Idea. The margin is (Part 2).
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 and . Compute for the applicants (3, 1) and (1, 1), and say where each one lies.
Idea. ; positive means class +1, and means inside the street (Part 2).
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 and with .
Idea. (Part 4).
Why: the rows are 2.24 apart, so with they are only a little similar; with the similarity would be .
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).
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).
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).
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).
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.
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).
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).
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).
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).
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).
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).
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).
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).
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.A linear SVM has the weights . How wide is its street?
Show a hint
The margin is .Show one possible solution
Answer: 0.2.
- 2.A linear SVM has and . Compute 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
; an edge is or .Show one possible solution
Answer: : class −1, on the edge; : class +1.
- 3.(a) Compute the RBF similarity of two rows with and . Give 3 decimals. (b) Compute the polynomial kernel for and .
Show a hint
(a) ; (b) first the dot product .Show one possible solution
Answer: (a) 0.368; (b) 25.
- 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 .Show one possible solution
Answer: (a) good; (b) bad (0.533); (c) good (0.46).
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.
- 5.Read
german_credit.csvintodf. Print the shape, then the number of bad credits.Show a hint
df = pd.read_csv("german_credit.csv"), thenprint(df.shape)andprint((df["risk"] == "bad").sum()).Show one possible solution
Pythonimport pandas as pd df = pd.read_csv("german_credit.csv") print(df.shape) print((df["risk"] == "bad").sum())Output
(1000, 21) 300
- 6.Turn
riskinto 1 for bad and 0 for good, and droppersonal_statusandforeign_worker. Print the number of columns. This step continues from Step 5.Show a hint
df["risk"] = (df["risk"] == "bad").astype(int), thendf.drop(columns=[...])andlen(df.columns).Show one possible solution
Python, continues from the cells abovedf["risk"] = (df["risk"] == "bad").astype(int) df = df.drop(columns=["personal_status", "foreign_worker"]) print(len(df.columns))Output
19
- 7.One-hot encode the columns of
text_columnswithdrop_first=Trueanddtype=int. Print the number of columns.Show a hint
df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int), thenlen(df.columns).Show one possible solution
Python, continues from the cells abovetext_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
- 8.Make
X(all columns withoutrisk) andy. Split them withtest_size=0.3andrandom_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), thenlen(y_test)andy_test.sum().Show one possible solution
Python, continues from the cells abovefrom 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.
- 9.Fit a
StandardScaleron the training data and scale both parts intoX_train_scaledandX_test_scaled. Print the shape ofX_test_scaled.Show a hint
scaler.fit_transform(X_train)andscaler.transform(X_test).Show one possible solution
Python, continues from the cells abovefrom 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)
- 10.Train an
SVC()calledsvmon the scaled data. Print its test accuracy, rounded to 4 decimals.Show a hint
svm = SVC(),svm.fit(X_train_scaled, y_train), thensvm.score(X_test_scaled, y_test).Show one possible solution
Python, continues from the cells abovefrom 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
- 11.Print the number of support vectors of
svmfor 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 aboveprint(svm.n_support_) print(svm.n_support_.sum())Output
[272 207] 479
- 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]withcross_val_score(SVC(C=C), X_train_scaled, y_train, cv=5).mean().Show one possible solution
Python, continues from the cells abovefrom 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.
- 13.Train an
SVC(class_weight="balanced")and print its test recall, rounded to 4 decimals.Show a hint
fiton the scaled training data, thenrecall_score(y_test, model.predict(X_test_scaled)).Show one possible solution
Python, continues from the cells abovefrom 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
- 14.Train a
LogisticRegression()and aRandomForestClassifier(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, thenscore(X_test_scaled, y_test).Show one possible solution
Python, continues from the cells abovefrom 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
- 15.Make a hard
VotingClassifiercalledhardwith the voters invotersand print its test accuracy, rounded to 4 decimals.Show a hint
hard = VotingClassifier(estimators=voters, voting="hard"),fiton the scaled training data, thenscore.Show one possible solution
Python, continues from the cells abovefrom 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
- 16.Make a soft
VotingClassifiercalledsoftwith the same voters. Print its test accuracy and its AUC, rounded to 4 decimals. Then draw the test accuracies ofsvm,hardandsoftas a bar chart.Show a hint
voting="soft";roc_auc_score(y_test, soft.predict_proba(X_test_scaled)[:, 1]);plt.bar(names, accuracies)andplt.show().Show one possible solution
Python, continues from the cells aboveimport 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

15Check yourself
Twelve questions. Every question has one right answer.
0 of 12 answered.
16Summary
| Formula or rule | Meaning | |
|---|---|---|
| Decision function | positive: class +1; negative: class −1; : inside the street | |
| Margin | the width of the street | |
| Hinge loss | the penalty of a row inside the street or on the wrong side | |
| Soft margin | C: the cost of a mistake | |
| RBF kernel | the similarity of two rows; : how far a row reaches | |
| Soft vote | the mean of the probabilities | the class with the larger mean wins |
| Code | What 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) | 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
- An SVM separates the classes by the widest street; only the support vectors decide where it lies.
- Always scale the features of an SVM, and encode the text columns.
- Choose
C(andgammafor RBF) with cross-validation: small values underfit, large values overfit. - Start with the RBF kernel; try the linear one for many features.
- When the rare class matters, use
class_weight="balanced"and judge by recall and F1. - Vote with good and different models; soft voting needs
predict_probafrom 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.