{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 35: Support Vector Machines and Voting - Classification\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 18, Tuesday.\n",
    "\n",
    "This notebook follows the lesson page. Read the text, run the cell under it with Shift + Enter, then change the values in the cell and run it again. Seeing the output change is how the rules become clear.\n",
    "\n",
    "Run the cells from top to bottom. A cell that draws a chart shows it under the cell when you run it. The practice problems are in a separate notebook, topic-35-practice.ipynb.\n",
    "\n",
    "The cells continue from each other: a cell uses the variables of the cells above it. Parts 7 to 10 are one project that starts from the raw file, so start at the first cell of Part 7. The solved problems 5 to 16 are a second project that starts again from reading the file. Cells late in the project train several models and take a few seconds.\n",
    "\n",
    "This notebook reads the file german_credit.csv. Put the file into the same folder as the notebook. On the Asiman Data School website the file is already there.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. What a support vector machine is\n",
    "2. The widest street, worked by hand\n",
    "3. The soft margin and C\n",
    "4. Kernels: curved borders\n",
    "5. The hyperparameters of SVC\n",
    "6. Preprocessing for an SVM, and for the models still to come\n",
    "7. The project: from the raw file to the data for the models\n",
    "8. The SVM on the credit data\n",
    "9. Voting: several models decide together\n",
    "10. The other models, and their vote\n",
    "11. The workflow, step by step\n",
    "12. Common mistakes\n",
    "13. Solved problems\n",
    "14. Practice (in topic-35-practice.ipynb)\n",
    "15. Check yourself (on the website)\n",
    "16. Summary"
   ],
   "id": "t35-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: the widest street, and a vote\n",
    "\n",
    "What matters most in this lesson. Five things matter most today. First, an SVM separates the classes by the widest street, and only the support vectors on its edges decide where it lies. Second, `C` sets the price of a mistake (small: a wide street, large: overfitting) and the kernel sets the shape of the border; the RBF kernel with its `gamma` is the usual first choice. Third, an SVM needs scaled, encoded features: without scaling it found 3 of 59 bad credits. Fourth, voting combines different models: hard voting counts their classes, soft voting averages their probabilities, and it helps when the voters are good and make different mistakes. Fifth, judge the models by what the mistakes cost: here the balanced SVM and the soft vote with a lower threshold.\n",
    "\n",
    "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.\n",
    "\n",
    "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).\n",
    "\n",
    "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.\n",
    "\n",
    "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).\n",
    "\n",
    "| Word | Meaning |\n",
    "| --- | --- |\n",
    "| Support vector machine (SVM) | a model that separates the classes by the widest possible street |\n",
    "| Hyperplane | the separating border: a line in two dimensions, a plane in three, a \"hyperplane\" in more |\n",
    "| Margin | the width of the street between the classes |\n",
    "| Support vectors | the training rows on the edge of the street (or inside it): only they decide where the border lies |\n",
    "| Soft margin | a street that allows some rows inside it or on the wrong side, controlled by `C` |\n",
    "| Kernel | a function that measures how similar two rows are; it lets the SVM draw curved borders |\n",
    "| Hard voting | each model votes for a class; the class with the most votes wins |\n",
    "| Soft voting | the probabilities of the models are averaged; the class with the larger average wins |\n",
    "\n",
    "## 1. What a support vector machine is\n",
    "\n",
    "### 1.1 The idea: the widest street\n",
    "\n",
    "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.\n",
    "\n",
    "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.\n",
    "\n",
    "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.\n",
    "\n",
    "### 1.2 Where SVMs are used\n",
    "\n",
    "- Banking and insurance: credit scoring, fraud detection (the project of this lesson).\n",
    "- Medicine and biology: classifying tumours from thousands of gene measurements, protein classification. With many features and few rows SVMs are among the best models.\n",
    "- Images: handwritten digit recognition, face detection (an SVM on image features was the standard face detector for years).\n",
    "- 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).\n",
    "- Industry: detecting faulty products from sensor readings.\n",
    "\n",
    "### 1.3 When to use an SVM\n",
    "\n",
    "| Situation | SVM? |\n",
    "| --- | --- |\n",
    "| Hundreds to tens of thousands of rows | yes: its strength |\n",
    "| Many features, even more features than rows | yes: it works well in high dimensions |\n",
    "| A clear gap between the classes | yes: the widest street finds it |\n",
    "| Millions of rows | no: training grows roughly with the square of the rows; use `LinearSVC`, a linear model or boosting |\n",
    "| You need exact probabilities | with care: they need `probability=True` and are an add-on |\n",
    "| You must explain each decision | not with curved kernels: a tree or logistic regression is easier to explain |\n",
    "\n",
    "### 1.4 Strengths and weaknesses\n",
    "\n",
    "| Strengths | Weaknesses |\n",
    "| --- | --- |\n",
    "| 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 |\n",
    "| The widest street resists overfitting when `C` is chosen well | Needs scaled features, otherwise it fails (the project shows how badly) |\n",
    "| Kernels draw curved borders without new columns | `C`, `kernel` and `gamma` must be chosen, and they matter |\n",
    "| Only the support vectors are needed to predict | No probabilities by default; `probability=True` is slower and only an estimate |\n",
    "| The training has one best answer (no random start, no local minimum) | A curved border is hard to explain to a customer |\n",
    "\n",
    "## 2. The widest street, worked by hand\n",
    "\n",
    "### 2.1 Six applicants\n",
    "\n",
    "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).\n",
    "\n",
    "| Applicant | Duration | Amount | Class |\n",
    "| --- | --- | --- | --- |\n",
    "| A | 1 | 1 | good (−1) |\n",
    "| B | 2 | 1 | good (−1) |\n",
    "| C | 1 | 2 | good (−1) |\n",
    "| D | 3 | 3 | bad (+1) |\n",
    "| E | 4 | 3 | bad (+1) |\n",
    "| F | 3 | 4 | bad (+1) |\n",
    "\n",
    "### 2.2 The border and the decision function\n",
    "\n",
    "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\n",
    "\n",
    "$$\n",
    "f(x) = w_1 x_1 + w_2 x_2 + b\n",
    "$$\n",
    "\n",
    "and predicts class +1 when $f(x) > 0$ and class −1 when $f(x) < 0$. The two edges of the street are the lines $f(x) = +1$ and $f(x) = -1$.\n",
    "\n",
    "The good applicants nearest to the bad ones are B and C (both with $x_1 + x_2 = 3$); the nearest bad applicant is D ($x_1 + x_2 = 6$). The widest street runs between the lines $x_1 + x_2 = 3$ and $x_1 + x_2 = 6$, and its middle is $x_1 + x_2 = 4.5$. With equal weights $w_1 = w_2 = a$, the two edges give two equations:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{on B and C:}\\quad & 3a + b = -1 \\\\[4pt]\n",
    "\\text{on D:}\\quad & 6a + b = +1\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Subtracting the first from the second: $3a = 2$, so $a = \\frac{2}{3} = 0.667$, and $b = -1 - 3 \\times 0.667 = -3$.\n",
    "\n",
    "$$\n",
    "f(x) = 0.667\\,x_1 + 0.667\\,x_2 - 3\n",
    "$$\n",
    "\n",
    "### 2.3 The width of the street\n",
    "\n",
    "The margin is 2 divided by the length of w:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\lVert w \\rVert &= \\sqrt{0.667^2 + 0.667^2} = \\sqrt{0.889} = 0.943 \\\\[6pt]\n",
    "\\text{margin} &= \\frac{2}{\\lVert w \\rVert} = \\frac{2}{0.943} = 2.121\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "This is exactly the distance between the lines $x_1 + x_2 = 3$ and $x_1 + x_2 = 6$. The support vectors are B, C and D: they lie on the edges ($f = -1$, $-1$ and $+1$). A, E and F lie further away and do not matter for the street.\n",
    "\n",
    "The picture is on the lesson page: the six applicants (duration against amount), the middle line x₁ + x₂ = 4.5, the two edges x₁ + x₂ = 3 and x₁ + x₂ = 6 with the street between them, the support vectors B, C and D ringed, and the new applicant (2, 3) inside the street.\n",
    "\n",
    "### 2.4 Deciding for new applicants\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "f(2, 3) &= 0.667 \\times 2 + 0.667 \\times 3 - 3 \\\\[2pt]\n",
    "&= 3.333 - 3 = 0.333 \\\\[8pt]\n",
    "f(1, 1) &= 0.667 \\times 1 + 0.667 \\times 1 - 3 \\\\[2pt]\n",
    "&= 1.333 - 3 = -1.667\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "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`.\n",
    "\n",
    "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.\n",
    "\n",
    "## 3. The soft margin and C\n",
    "\n",
    "### 3.1 When no street fits\n",
    "\n",
    "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:\n",
    "\n",
    "- a wide street that accepts G on the wrong side (one mistake),\n",
    "- a narrow street that squeezes past G (no mistake).\n",
    "\n",
    "### 3.2 The hinge loss\n",
    "\n",
    "A row that is on the wrong side of its edge pays a penalty, the hinge loss:\n",
    "\n",
    "$$\n",
    "\\text{loss} = \\max\\bigl(0,\\ 1 - y\\,f(x)\\bigr)\n",
    "$$\n",
    "\n",
    "with $y = +1$ for bad and $y = -1$ for good. A row beyond its edge ($y \\times f \\ge 1$) pays 0. G under the old line of Part 2:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "f(G) &= 0.667 \\times 3 + 0.667 \\times 2.5 - 3 = 0.667 \\\\[6pt]\n",
    "\\text{loss}(G) &= \\max\\bigl(0,\\ 1 - (-1) \\times 0.667\\bigr) = 1.667\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "### 3.3 What the SVM minimises\n",
    "\n",
    "$$\n",
    "\\tfrac{1}{2}\\lVert w \\rVert^2 + C \\times (\\text{sum of the losses})\n",
    "$$\n",
    "\n",
    "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:\n",
    "\n",
    "|  | The old wide line | A narrow line through G's edge |\n",
    "| --- | --- | --- |\n",
    "| w and b | $w = (0.667, 0.667)$, $b = -3$ | $w = (0, 4)$, $b = -11$ |\n",
    "| $\\tfrac{1}{2}\\lVert w \\rVert^2$ | $\\tfrac{1}{2} \\times 0.889 = 0.444$ | $\\tfrac{1}{2} \\times 16 = 8$ |\n",
    "| Sum of the losses | 1.667 (only G) | 0 |\n",
    "| Margin | 2.121 | $\\frac{2}{4} = 0.5$ |\n",
    "| Total with C = 1 | $0.444 + 1 \\times 1.667 = 2.111$ | 8 |\n",
    "| Total with C = 1000 | $0.444 + 1000 \\times 1.667 = 1{,}667.4$ | 8 |\n",
    "\n",
    "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.\n",
    "\n",
    "- Small C: wide street, more mistakes on the training data, smoother and simpler model (risk: underfitting).\n",
    "- Large C: narrow street, few mistakes on the training data, a model that follows every row (risk: overfitting).\n",
    "\n",
    "The picture is on the lesson page: the seven applicants with G at (3, 2.5); with C = 1 a wide street (margin 2.53) with G inside it on the wrong side, with C = 1000 a narrow horizontal street (margin 0.5) with every applicant on its side.\n",
    "\n",
    "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.\n",
    "\n",
    "## 4. Kernels: curved borders\n",
    "\n",
    "### 4.1 The kernel trick\n",
    "\n",
    "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.\n",
    "\n",
    "Add a second column, the square of the value: $x \\to (x, x^2)$.\n",
    "\n",
    "| x | −3 | −2 | −1 | 0 | 1 | 2 | 3 |\n",
    "| --- | --- | --- | --- | --- | --- | --- | --- |\n",
    "| $x^2$ | 9 | 4 | 1 | 0 | 1 | 4 | 9 |\n",
    "| class | bad | bad | good | good | good | bad | bad |\n",
    "\n",
    "In the new column the good ones have $x^2 \\le 1$ and the bad ones $x^2 \\ge 4$: the straight line $x^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.\n",
    "\n",
    "The picture is on the lesson page: left, the seven points on one line, bad on both sides of the good ones; right, the same points with x² as a second coordinate, separated by the straight line x² = 2.5.\n",
    "\n",
    "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)$ that gives this similarity as if the rows had been moved to the bigger space, without moving them. This is the kernel trick.\n",
    "\n",
    "### 4.2 The four kernels of scikit-learn\n",
    "\n",
    "| Kernel | `kernel=` | Similarity $K(a, b)$ | The border | When to use |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| Linear | `\"linear\"` | $a \\cdot b$ | a straight line (a flat hyperplane) | many features (texts), or when a simple model is enough |\n",
    "| Polynomial | `\"poly\"` | $(\\gamma\\, a \\cdot b + \\text{coef0})^{\\text{degree}}$ | curves of the given degree | when features interact; rarely the best |\n",
    "| RBF (Gaussian) | `\"rbf\"` (default) | $e^{-\\gamma \\lVert a - b \\rVert^2}$ | any shape: islands and bends | the usual first choice |\n",
    "| Sigmoid | `\"sigmoid\"` | $\\tanh(\\gamma\\, a \\cdot b + \\text{coef0})$ | S-shaped borders, like a small neural network | rarely; often worse than RBF |\n",
    "\n",
    "### 4.3 How an SVM predicts with a kernel\n",
    "\n",
    "With a kernel there is no line `w` to write down any more. The SVM predicts with the support vectors themselves: every support vector $x_i$ gets a weight $\\alpha_i$, and the decision function adds up its similarities to the new row $x$:\n",
    "\n",
    "$$\n",
    "f(x) = \\alpha_1 y_1 K(x_1, x) + \\alpha_2 y_2 K(x_2, x) + \\dots + b\n",
    "$$\n",
    "\n",
    "The sum runs over the support vectors only; every other training row has $\\alpha = 0$ and plays no part. Each weight $\\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.\n",
    "\n",
    "### 4.4 The RBF kernel by hand\n",
    "\n",
    "The RBF kernel turns a distance into a similarity between 0 and 1: identical rows get 1, distant rows almost 0. With $\\gamma = 0.5$:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\lVert a - b \\rVert^2 = 1:\\quad & K = e^{-0.5 \\times 1} = 0.607 \\\\[4pt]\n",
    "\\lVert a - b \\rVert^2 = 4:\\quad & K = e^{-0.5 \\times 4} = 0.135 \\\\[4pt]\n",
    "\\lVert a - b \\rVert^2 = 9:\\quad & K = e^{-0.5 \\times 9} = 0.011\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "gamma sets how fast the similarity falls with the distance:\n",
    "\n",
    "- small $\\gamma$: even distant rows are similar; every row influences a wide area; the border is smooth (risk: underfitting);\n",
    "- large $\\gamma$: only very close rows are similar; each row influences a tiny area; the border wraps around single rows (risk: overfitting).\n",
    "\n",
    "The default `gamma=\"scale\"` uses $\\frac{1}{\\text{features} \\times \\text{variance}}$; after a `StandardScaler` the variance is 1, so it is $\\frac{1}{\\text{features}}$.\n",
    "\n",
    "### 4.5 The kernels on the credit data\n",
    "\n",
    "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:\n",
    "\n",
    "The picture is on the lesson page: four panels for the linear, polynomial, RBF and sigmoid kernels on the scaled duration and credit amount of the training applicants, each with the area where the model predicts bad.\n",
    "\n",
    "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.\n",
    "\n",
    "The picture is on the lesson page: three panels for the RBF kernel with gamma 0.1 (a smooth area), 1 (a more detailed one) and 10 (small islands around single applicants).\n",
    "\n",
    "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.\n",
    "\n",
    "## 5. The hyperparameters of SVC\n",
    "\n",
    "`SVC` is the support vector classifier of scikit-learn (`from sklearn.svm import SVC`).\n",
    "\n",
    "| Hyperparameter | Default | Role |\n",
    "| --- | --- | --- |\n",
    "| `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. |\n",
    "| `kernel` | `\"rbf\"` | the shape of the border: `\"linear\"`, `\"poly\"`, `\"rbf\"`, `\"sigmoid\"` (Part 4) |\n",
    "| `gamma` | `\"scale\"` | for `rbf`, `poly` and `sigmoid`: how far the influence of one row reaches. Small: smooth; large: islands. `\\\"scale\\\"` is $\\frac{1}{\\text{features} \\times \\text{variance}}$, `\\\"auto\\\"` is $\\frac{1}{\\text{features}}$. |\n",
    "| `degree` | `3` | only for `poly`: the degree of the curves |\n",
    "| `coef0` | `0.0` | only for `poly` and `sigmoid`: the constant inside the kernel |\n",
    "| `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 |\n",
    "| `probability` | `False` | `True` adds `predict_proba` (needed for soft voting); the training is about five times slower, because it uses an inner cross-validation |\n",
    "| `random_state` | `None` | only used when `probability=True` |\n",
    "| `shrinking` | `True` | a speed trick of the solver; the result is the same |\n",
    "| `tol` | `0.001` | when the solver may stop |\n",
    "| `cache_size` | `200` | memory (MB) for kernel values: a speed setting |\n",
    "| `max_iter` | `-1` | a limit on the solver's steps; -1 means no limit |\n",
    "| `decision_function_shape` | `\"ovr\"` | for more than two classes: how the answers of the pairwise SVMs are combined |\n",
    "| `break_ties` | `False` | for more than two classes: break ties by the decision function |\n",
    "\n",
    "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.\n",
    "\n",
    "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).\n",
    "\n",
    "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.\n",
    "\n",
    "Relatives: `LinearSVC` is a faster SVM for the linear kernel and large data. `SVR` is the SVM for numbers (Topic 36).\n",
    "\n",
    "## 6. Preprocessing for an SVM, and for the models still to come\n",
    "\n",
    "- 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.\n",
    "- 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.\n",
    "- Missing values: must be filled. `SVC` does not accept gaps. (This file has none, but the step is still done.)\n",
    "- 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.\n",
    "- Many features: no problem for an SVM, unlike k-nearest neighbours.\n",
    "- Unbalanced classes: `class_weight=\"balanced\"` (Topic 41 goes further).\n",
    "- 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.\n",
    "\n",
    "| Model (topic) | Scaling | Encoding of text | Outliers in the features | Missing values |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| Linear regression (22) | not needed for the predictions | needed | sensitive | fill |\n",
    "| Ridge, Lasso, logistic regression (26, 27) | needed | needed | sensitive | fill |\n",
    "| Decision tree, random forest, bagged trees (29, 30, 31) | not needed | needed | robust | fill (recent scikit-learn can handle them) |\n",
    "| k-nearest neighbours (32, 33) | essential: distances | needed; few, useful columns | sensitive | fill |\n",
    "| Naive Bayes (34) | not needed | codes for Categorical, one-hot for Gaussian | sensitive (Gaussian) | fill |\n",
    "| Support vector machines (35, 36) | essential: distances and dot products | needed (one-hot) | a little: they can become support vectors | fill |\n",
    "| Voting (35, 36) | as the models inside | as the models inside | as the models inside | fill |\n",
    "| 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 |\n",
    "| k-means, DBSCAN, PCA (43, 44) | essential: distances and variances | needed | sensitive | fill |\n",
    "\n",
    "Topic 42 will put the preprocessing and the model into one object, so that every step is fitted on the right rows.\n",
    "\n",
    "## 7. The project: from the raw file to the data for the models\n",
    "\n",
    "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.\n",
    "\n",
    "### 7.1 Step 1: read and look"
   ],
   "id": "t35-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"german_credit.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.head())"
   ],
   "id": "t35-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1,000 applicants and 21 columns:\n",
    "\n",
    "| Column | Meaning |\n",
    "| --- | --- |\n",
    "| `checking_account` | the balance of the checking account: < 0 DM, 0 to 200 DM, >= 200 DM, or no account (DM: Deutsche Mark) |\n",
    "| `duration_months` | the duration of the loan in months |\n",
    "| `credit_history` | how earlier loans were paid back |\n",
    "| `purpose` | what the loan is for: new car, used car, furniture, radio or TV, education, business, ... |\n",
    "| `credit_amount` | the amount of the loan in DM |\n",
    "| `savings` | the savings: < 100 DM up to >= 1000 DM, or unknown |\n",
    "| `employment_years` | how long the applicant has worked for the present employer |\n",
    "| `installment_rate` | the monthly payment as a share of the disposable income (1 to 4) |\n",
    "| `personal_status` | sex and marital status |\n",
    "| `other_debtors` | none, a co-applicant or a guarantor |\n",
    "| `residence_years` | years at the present home (1 to 4) |\n",
    "| `property` | the most valuable property: real estate, savings or insurance, car or other, none known |\n",
    "| `age` | the age in years |\n",
    "| `other_installments` | other loans being paid off: bank, stores, none |\n",
    "| `housing` | rent, own, for free |\n",
    "| `existing_credits` | the number of loans at this bank |\n",
    "| `job` | the kind of job |\n",
    "| `dependents` | the number of people the applicant supports |\n",
    "| `telephone` | a telephone registered in the applicant's name |\n",
    "| `foreign_worker` | whether the applicant is a foreign worker |\n",
    "| `risk` | the target: good or bad |\n",
    "\n",
    "### 7.2 Step 2: check for gaps and repeated rows"
   ],
   "id": "t35-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.isna().sum().sum())\n",
    "print(df.duplicated().sum())"
   ],
   "id": "t35-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 7.3 Step 3: the numbers"
   ],
   "id": "t35-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.describe().round(1))"
   ],
   "id": "t35-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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).\n",
    "\n",
    "### 7.4 Step 4: outliers\n",
    "\n",
    "The rule of Topic 25: a value more than 1.5 IQR below the first quartile or above the third."
   ],
   "id": "t35-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for column in [\"duration_months\", \"credit_amount\", \"age\"]:\n",
    "    q1 = df[column].quantile(0.25)\n",
    "    q3 = df[column].quantile(0.75)\n",
    "    iqr = q3 - q1\n",
    "    outside = ((df[column] < q1 - 1.5 * iqr) | (df[column] > q3 + 1.5 * iqr)).sum()\n",
    "    print(column, outside)"
   ],
   "id": "t35-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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).\n",
    "\n",
    "### 7.5 Step 5: the target"
   ],
   "id": "t35-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[\"risk\"].value_counts())"
   ],
   "id": "t35-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "70 percent good, 30 percent bad. The model will predict \"bad\", so \"bad\" becomes 1, the positive class of Topic 28:"
   ],
   "id": "t35-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"risk\"] = (df[\"risk\"] == \"bad\").astype(int)\n",
    "\n",
    "print(df[\"risk\"].mean())"
   ],
   "id": "t35-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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?\n",
    "\n",
    "### 7.6 Step 6: drop two columns that a fair model must not use"
   ],
   "id": "t35-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop(columns=[\"personal_status\", \"foreign_worker\"])\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t35-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`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.)\n",
    "\n",
    "### 7.7 Step 7: encode the text columns"
   ],
   "id": "t35-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text_columns = [\"checking_account\", \"credit_history\", \"purpose\", \"savings\", \"employment_years\", \"other_debtors\", \"property\", \"other_installments\", \"housing\", \"job\", \"telephone\"]\n",
    "\n",
    "df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t35-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 7.8 Step 8: split\n",
    "\n",
    "Change it and run: change `test_size` to `0.3` and run: 300 applicants become test data."
   ],
   "id": "t35-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df.drop(columns=[\"risk\"])\n",
    "y = df[\"risk\"]\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "print(X_train.shape, X_test.shape)\n",
    "print(round(y_test.mean(), 3))"
   ],
   "id": "t35-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 7.9 Step 9: scale"
   ],
   "id": "t35-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "print(X_train_scaled[:3, :3].round(2))"
   ],
   "id": "t35-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "## 8. The SVM on the credit data\n",
    "\n",
    "### 8.1 Train and judge\n",
    "\n",
    "Change it and run: write `SVC(C=10)` and run: the training accuracy rises, the test accuracy falls."
   ],
   "id": "t35-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.svm import SVC\n",
    "\n",
    "svm = SVC()\n",
    "svm.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(svm.score(X_train_scaled, y_train), 4))\n",
    "print(round(svm.score(X_test_scaled, y_test), 4))"
   ],
   "id": "t35-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 8.2 The measures of Topic 28"
   ],
   "id": "t35-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score\n",
    "\n",
    "predicted = svm.predict(X_test_scaled)\n",
    "\n",
    "print(confusion_matrix(y_test, predicted))\n",
    "print(round(precision_score(y_test, predicted), 4))\n",
    "print(round(recall_score(y_test, predicted), 4))\n",
    "print(round(f1_score(y_test, predicted), 4))\n",
    "print(round(roc_auc_score(y_test, svm.decision_function(X_test_scaled)), 4))"
   ],
   "id": "t35-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 8.3 Without scaling"
   ],
   "id": "t35-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "svm_raw = SVC()\n",
    "svm_raw.fit(X_train, y_train)\n",
    "\n",
    "predicted_raw = svm_raw.predict(X_test)\n",
    "\n",
    "print(round(svm_raw.score(X_test, y_test), 4))\n",
    "print(round(recall_score(y_test, predicted_raw), 4))"
   ],
   "id": "t35-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 8.4 Inside the model: the support vectors"
   ],
   "id": "t35-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(svm.n_support_)\n",
    "print(len(svm.support_), len(X_train_scaled))"
   ],
   "id": "t35-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.)\n",
    "\n",
    "### 8.5 The decision function of a few applicants\n",
    "\n",
    "Change it and run: change `[:5]` to `[5:10]` in all three lines and run."
   ],
   "id": "t35-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(svm.decision_function(X_test_scaled[:5]).round(3))\n",
    "print(predicted[:5])\n",
    "print(y_test.iloc[:5].tolist())"
   ],
   "id": "t35-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 8.6 The decision function by hand\n",
    "\n",
    "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 $\\alpha_i y_i$), plus the bias `intercept_`:"
   ],
   "id": "t35-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics.pairwise import rbf_kernel\n",
    "\n",
    "gamma = 1 / (X_train_scaled.shape[1] * X_train_scaled.var())\n",
    "similarity = rbf_kernel(svm.support_vectors_, X_test_scaled[:1], gamma=gamma)\n",
    "\n",
    "print(round(gamma, 4))\n",
    "print(svm.dual_coef_.min(), svm.dual_coef_.max())\n",
    "print((svm.dual_coef_ @ similarity + svm.intercept_).round(3))"
   ],
   "id": "t35-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first line is the value of `gamma=\"scale\"`: $\\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.\n",
    "\n",
    "### 8.7 Which kernel?\n",
    "\n",
    "The kernel is chosen with cross-validation on the training data (Topic 23), never with the test data:"
   ],
   "id": "t35-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "for kernel in [\"linear\", \"poly\", \"rbf\", \"sigmoid\"]:\n",
    "    scores = cross_val_score(SVC(kernel=kernel), X_train_scaled, y_train, cv=5)\n",
    "    print(kernel, round(scores.mean(), 4))"
   ],
   "id": "t35-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 8.8 C with cross-validation\n",
    "\n",
    "Change it and run: add `0.5` and `3` to the list and run."
   ],
   "id": "t35-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for C in [0.01, 0.1, 1, 10, 100]:\n",
    "    model = SVC(C=C)\n",
    "    model.fit(X_train_scaled, y_train)\n",
    "    scores = cross_val_score(SVC(C=C), X_train_scaled, y_train, cv=5)\n",
    "    print(C, round(model.score(X_train_scaled, y_train), 4), round(scores.mean(), 4))"
   ],
   "id": "t35-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows C, the training accuracy and the cross-validated accuracy:\n",
    "\n",
    "- 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.\n",
    "- C = 1: the best cross-validated accuracy.\n",
    "- C = 10 and 100: the training accuracy climbs to almost 1, the cross-validated one falls: overfitting, the narrow street follows every training row.\n",
    "\n",
    "### 8.9 gamma with cross-validation"
   ],
   "id": "t35-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for gamma in [0.001, 0.01, 0.03, 0.1, 1]:\n",
    "    scores = cross_val_score(SVC(gamma=gamma), X_train_scaled, y_train, cv=5)\n",
    "    print(gamma, round(scores.mean(), 4))"
   ],
   "id": "t35-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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 $\\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.\n",
    "\n",
    "### 8.10 More bad credits found: class_weight\n",
    "\n",
    "The bank cares most about the bad credits. `class_weight=\"balanced\"` makes a mistake on the smaller class (bad) more expensive:"
   ],
   "id": "t35-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "svm_balanced = SVC(class_weight=\"balanced\")\n",
    "svm_balanced.fit(X_train_scaled, y_train)\n",
    "\n",
    "predicted_balanced = svm_balanced.predict(X_test_scaled)\n",
    "\n",
    "print(confusion_matrix(y_test, predicted_balanced))\n",
    "print(round(recall_score(y_test, predicted_balanced), 4))\n",
    "print(round(precision_score(y_test, predicted_balanced), 4))\n",
    "print(round(f1_score(y_test, predicted_balanced), 4))"
   ],
   "id": "t35-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 8.11 Probabilities for an SVM\n",
    "\n",
    "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)."
   ],
   "id": "t35-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "svm_prob = SVC(probability=True, random_state=42)\n",
    "svm_prob.fit(X_train_scaled, y_train)\n",
    "\n",
    "probabilities = svm_prob.predict_proba(X_test_scaled)[:, 1]\n",
    "\n",
    "print(probabilities[:5].round(3))\n",
    "print(((probabilities >= 0.5).astype(int) != predicted).sum())"
   ],
   "id": "t35-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "## 9. Voting: several models decide together\n",
    "\n",
    "### 9.1 Why vote?\n",
    "\n",
    "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.\n",
    "\n",
    "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.\n",
    "\n",
    "### 9.2 Hard voting and soft voting\n",
    "\n",
    "Three models give the probability of \"bad\" for two applicants:\n",
    "\n",
    "|  | Logistic regression | Random forest | SVM | Hard vote | Soft vote (the mean) |\n",
    "| --- | --- | --- | --- | --- | --- |\n",
    "| Applicant 1 | 0.90 → bad | 0.40 → good | 0.45 → good | 1 against 2: good | $\\frac{0.90 + 0.40 + 0.45}{3} = 0.583$: bad |\n",
    "| Applicant 2 | 0.55 → bad | 0.60 → bad | 0.10 → good | 2 against 1: bad | $\\frac{0.55 + 0.60 + 0.10}{3} = 0.417$: good |\n",
    "\n",
    "- Hard voting: each model gives its class; the majority wins. Applicant 1: two models say good, so good.\n",
    "- 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.\n",
    "\n",
    "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.\n",
    "\n",
    "The picture is on the lesson page: for each of the two applicants, the three probabilities of bad as bars with the line 0.5, and the soft vote, 0.583 for the first and 0.417 for the second.\n",
    "\n",
    "Weights can make some models count more: with `weights=[2, 1, 1]` the logistic regression counts twice, in both kinds of voting.\n",
    "\n",
    "### 9.3 VotingClassifier\n",
    "\n",
    "`VotingClassifier` (`from sklearn.ensemble import VotingClassifier`) does the vote:\n",
    "\n",
    "| Hyperparameter | Default | Role |\n",
    "| --- | --- | --- |\n",
    "| `estimators` | (required) | a list of (name, model) pairs: the voters |\n",
    "| `voting` | `\"hard\"` | `\"hard\"`: majority of the classes; `\"soft\"`: the mean of the probabilities (every model needs `predict_proba`, so an SVM needs `probability=True`) |\n",
    "| `weights` | `None` | how much each model counts; `None` means equally |\n",
    "| `n_jobs` | `None` | how many models are trained at the same time |\n",
    "| `flatten_transform` | `True` | the shape of the output of `transform` (the models' probabilities side by side) |\n",
    "| `verbose` | `False` | print the time of every model while training |\n",
    "\n",
    "`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.\n",
    "\n",
    "## 10. The other models, and their vote\n",
    "\n",
    "The same scaled data, the same 200 test applicants, the models of earlier topics, each one alone first.\n",
    "\n",
    "### 10.1 Logistic regression (Topic 27)"
   ],
   "id": "t35-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LogisticRegression\n",
    "\n",
    "logistic = LogisticRegression()\n",
    "logistic.fit(X_train_scaled, y_train)\n",
    "\n",
    "predicted_logistic = logistic.predict(X_test_scaled)\n",
    "\n",
    "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))"
   ],
   "id": "t35-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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).\n",
    "\n",
    "### 10.2 A decision tree (Topic 29)"
   ],
   "id": "t35-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.tree import DecisionTreeClassifier\n",
    "\n",
    "tree = DecisionTreeClassifier(max_depth=4, random_state=42)\n",
    "tree.fit(X_train_scaled, y_train)\n",
    "\n",
    "predicted_tree = tree.predict(X_test_scaled)\n",
    "\n",
    "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))"
   ],
   "id": "t35-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A tree of depth 4 (a full tree would overfit, Topic 29): a little less accurate, but it finds more bad credits.\n",
    "\n",
    "### 10.3 A random forest (Topic 30)"
   ],
   "id": "t35-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import RandomForestClassifier\n",
    "\n",
    "forest = RandomForestClassifier(random_state=42)\n",
    "forest.fit(X_train_scaled, y_train)\n",
    "\n",
    "predicted_forest = forest.predict(X_test_scaled)\n",
    "\n",
    "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))"
   ],
   "id": "t35-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The forest has the highest accuracy so far, but a low recall: it is careful about saying \"bad\".\n",
    "\n",
    "### 10.4 k-nearest neighbours (Topic 32)"
   ],
   "id": "t35-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "\n",
    "knn = KNeighborsClassifier(n_neighbors=15)\n",
    "knn.fit(X_train_scaled, y_train)\n",
    "\n",
    "predicted_knn = knn.predict(X_test_scaled)\n",
    "\n",
    "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))"
   ],
   "id": "t35-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "k-nearest neighbours suffers from the 44 one-hot columns (the curse of dimensionality, Topic 33): the weakest recall so far.\n",
    "\n",
    "### 10.5 Naive Bayes (Topic 34)"
   ],
   "id": "t35-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.naive_bayes import GaussianNB\n",
    "\n",
    "naive_bayes = GaussianNB()\n",
    "naive_bayes.fit(X_train_scaled, y_train)\n",
    "\n",
    "predicted_nb = naive_bayes.predict(X_test_scaled)\n",
    "\n",
    "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))"
   ],
   "id": "t35-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 10.6 The voters"
   ],
   "id": "t35-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import VotingClassifier\n",
    "\n",
    "voters = [\n",
    "    (\"logistic\", LogisticRegression()),\n",
    "    (\"tree\", DecisionTreeClassifier(max_depth=4, random_state=42)),\n",
    "    (\"forest\", RandomForestClassifier(random_state=42)),\n",
    "    (\"knn\", KNeighborsClassifier(n_neighbors=15)),\n",
    "    (\"svm\", SVC(probability=True, random_state=42)),\n",
    "]\n",
    "\n",
    "print(len(voters))"
   ],
   "id": "t35-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 10.7 Hard voting"
   ],
   "id": "t35-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hard = VotingClassifier(estimators=voters, voting=\"hard\")\n",
    "hard.fit(X_train_scaled, y_train)\n",
    "\n",
    "predicted_hard = hard.predict(X_test_scaled)\n",
    "\n",
    "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))"
   ],
   "id": "t35-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The majority of five models: more accurate than the SVM, logistic regression, the tree and k-nearest neighbours alone.\n",
    "\n",
    "A hard vote has no probabilities, so no AUC:\n",
    "\n",
    "```python\n",
    "hard.predict_proba(X_test_scaled)\n",
    "```\n",
    "\n",
    "```\n",
    "AttributeError: This 'VotingClassifier' has no attribute 'predict_proba'\n",
    "```\n",
    "\n",
    "### 10.8 Soft voting"
   ],
   "id": "t35-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "soft = VotingClassifier(estimators=voters, voting=\"soft\")\n",
    "soft.fit(X_train_scaled, y_train)\n",
    "\n",
    "predicted_soft = soft.predict(X_test_scaled)\n",
    "\n",
    "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))\n",
    "print(round(roc_auc_score(y_test, soft.predict_proba(X_test_scaled)[:, 1]), 4))"
   ],
   "id": "t35-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 10.9 Inside the soft vote"
   ],
   "id": "t35-059"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for name, model in soft.named_estimators_.items():\n",
    "    print(name, model.predict_proba(X_test_scaled[:3])[:, 1].round(2))\n",
    "\n",
    "print(\"vote\", soft.predict_proba(X_test_scaled[:3])[:, 1].round(2))"
   ],
   "id": "t35-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 10.10 Weights, and a weak voter\n",
    "\n",
    "Change it and run: change the weights to `[1, 1, 3, 1, 1]` and run."
   ],
   "id": "t35-061"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "weighted = VotingClassifier(estimators=voters, voting=\"soft\", weights=[2, 1, 2, 1, 2])\n",
    "weighted.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(weighted.score(X_test_scaled, y_test), 4))"
   ],
   "id": "t35-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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."
   ],
   "id": "t35-063"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with_nb = VotingClassifier(estimators=voters + [(\"nb\", GaussianNB())], voting=\"soft\")\n",
    "with_nb.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(with_nb.score(X_test_scaled, y_test), 4))"
   ],
   "id": "t35-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 10.11 Hard or soft, with cross-validation\n",
    "\n",
    "One test split of 200 applicants can mislead. The two votes compared with five folds of the training data:"
   ],
   "id": "t35-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for voting in [\"hard\", \"soft\"]:\n",
    "    scores = cross_val_score(VotingClassifier(estimators=voters, voting=voting), X_train_scaled, y_train, cv=5)\n",
    "    print(voting, round(scores.mean(), 4))"
   ],
   "id": "t35-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 10.12 The scores of every model"
   ],
   "id": "t35-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "results = [\n",
    "    (\"SVM\", predicted),\n",
    "    (\"SVM, balanced\", predicted_balanced),\n",
    "    (\"logistic regression\", predicted_logistic),\n",
    "    (\"decision tree\", predicted_tree),\n",
    "    (\"random forest\", predicted_forest),\n",
    "    (\"k-nearest neighbours\", predicted_knn),\n",
    "    (\"Naive Bayes\", predicted_nb),\n",
    "    (\"hard voting\", predicted_hard),\n",
    "    (\"soft voting\", predicted_soft),\n",
    "]\n",
    "\n",
    "for name, model_predicted in results:\n",
    "    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))"
   ],
   "id": "t35-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line: the test accuracy, the recall of the bad credits and the F1-score, all on the same 200 applicants."
   ],
   "id": "t35-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "names = [name for name, model_predicted in results]\n",
    "f1_scores = [f1_score(y_test, model_predicted) for name, model_predicted in results]\n",
    "\n",
    "plt.barh(names, f1_scores)\n",
    "plt.xlabel(\"test F1-score of the bad credits\")\n",
    "plt.title(\"The SVM, the models of earlier topics, and their vote\")\n",
    "plt.show()"
   ],
   "id": "t35-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What the comparison shows:\n",
    "\n",
    "- Scaled and with the default settings, the SVM beats the baseline clearly (0.76 against 0.705); without scaling it was useless.\n",
    "- `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.\n",
    "- 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.\n",
    "- 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.\n",
    "\n",
    "### 10.13 What the mistakes cost the bank\n",
    "\n",
    "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:"
   ],
   "id": "t35-071"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for name, model_predicted in results:\n",
    "    matrix = confusion_matrix(y_test, model_predicted)\n",
    "    cost = 5 * matrix[1, 0] + matrix[0, 1]\n",
    "    print(name, cost)"
   ],
   "id": "t35-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`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.\n",
    "\n",
    "### 10.14 A lower threshold for the soft vote\n",
    "\n",
    "The soft vote has probabilities, so its threshold can be lowered, as in Topic 28:\n",
    "\n",
    "Change it and run: change `0.3` to `0.4` and run."
   ],
   "id": "t35-073"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "soft_prob = soft.predict_proba(X_test_scaled)[:, 1]\n",
    "predicted_soft_03 = (soft_prob >= 0.3).astype(int)\n",
    "\n",
    "matrix = confusion_matrix(y_test, predicted_soft_03)\n",
    "\n",
    "print(matrix)\n",
    "print(5 * matrix[1, 0] + matrix[0, 1])\n",
    "print(round(recall_score(y_test, predicted_soft_03), 4))"
   ],
   "id": "t35-074"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "## 11. The workflow, step by step\n",
    "\n",
    "| Step | What is done | In this project |\n",
    "| --- | --- | --- |\n",
    "| 1. Look | shape, first rows, the meaning of the columns | 1,000 applicants, 21 columns |\n",
    "| 2. Check | gaps and repeated rows | none; \"unknown\" is a category |\n",
    "| 3. Numbers | sizes and spread | very different sizes: scaling will be needed |\n",
    "| 4. Outliers | count them, decide | real loans: kept |\n",
    "| 5. Target | text to 0 and 1, the share of each class | bad = 1, 30 percent |\n",
    "| 6. Unfair columns | remove what a decision must not use | `personal_status`, `foreign_worker` |\n",
    "| 7. Encode | one-hot | 44 features |\n",
    "| 8. Split | training and test data | 800 and 200; baseline 0.705 |\n",
    "| 9. Scale | `StandardScaler` fitted on the training data | essential for the SVM |\n",
    "| 10. Model | `SVC()` | accuracy 0.76, recall 0.42 |\n",
    "| 11. Tune | kernel, `C`, `gamma` with cross-validation; `class_weight` | RBF, `C=1`; balanced: recall 0.76 |\n",
    "| 12. Other models | the classifiers of earlier topics, each alone | forest 0.805, Naive Bayes weakest |\n",
    "| 13. Vote | hard and soft `VotingClassifier`; compared with cross-validation | soft: 0.80, F1 0.60, AUC 0.82 |\n",
    "| 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) |\n",
    "\n",
    "## 12. Common mistakes\n",
    "\n",
    "| Mistake | Why it is wrong | Right |\n",
    "| --- | --- | --- |\n",
    "| 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. |\n",
    "| Choosing `C` or `gamma` with the test data. | The test score is then no longer an honest judge. | Cross-validation on the training data. |\n",
    "| 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. |\n",
    "| 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. |\n",
    "| Asking an `SVC()` for `predict_proba`. | It has no probabilities by default. | `probability=True`, or `decision_function` for the AUC. |\n",
    "| 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. |\n",
    "| 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. |\n",
    "| Putting every model into the vote. | A weak voter pulls a soft vote down. | Good and different voters, each checked alone first. |\n",
    "| Expecting a vote to beat every model. | A strong single model (here the forest) can stay better. | Compare honestly on the same test data. |\n",
    "| Training an SVM on millions of rows. | The training time grows very fast with the rows. | `LinearSVC`, logistic regression or boosting. |\n",
    "\n",
    "## 13. Solved problems\n",
    "\n",
    "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.\n",
    "\n",
    "Problem 1. The width of the street\n",
    "\n",
    "A linear SVM has the weights $w = (3, 4)$. How wide is its street?\n",
    "\n",
    "Idea. The margin is $\\frac{2}{\\lVert w \\rVert}$ (Part 2).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\lVert w \\rVert &= \\sqrt{3^2 + 4^2} = \\sqrt{25} = 5 \\\\[6pt]\n",
    "\\text{margin} &= \\frac{2}{5} = 0.4\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: large weights mean a narrow street; the SVM tries to keep the weights small.\n",
    "\n",
    "Problem 2. Which side of the street?\n",
    "\n",
    "A linear SVM has $w = (1, -2)$ and $b = 0.5$. Compute $f(x)$ for the applicants (3, 1) and (1, 1), and say where each one lies.\n",
    "\n",
    "Idea. $f(x) = w_1 x_1 + w_2 x_2 + b$; positive means class +1, and $\\lvert f \\rvert < 1$ means inside the street (Part 2).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "f(3, 1) &= 1 \\times 3 - 2 \\times 1 + 0.5 = 1.5 \\\\[4pt]\n",
    "f(1, 1) &= 1 \\times 1 - 2 \\times 1 + 0.5 = -0.5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "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.\n",
    "\n",
    "Problem 3. The RBF kernel\n",
    "\n",
    "Compute the RBF similarity of the rows $a = (1, 2)$ and $b = (2, 4)$ with $\\gamma = 0.5$.\n",
    "\n",
    "Idea. $K(a, b) = e^{-\\gamma \\lVert a - b \\rVert^2}$ (Part 4).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\lVert a - b \\rVert^2 &= (1 - 2)^2 + (2 - 4)^2 = 1 + 4 = 5 \\\\[6pt]\n",
    "K &= e^{-0.5 \\times 5} = e^{-2.5} = 0.082\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: the rows are 2.24 apart, so with $\\gamma = 0.5$ they are only a little similar; with $\\gamma = 0.1$ the similarity would be $e^{-0.5} = 0.607$.\n",
    "\n",
    "Problem 4. Hard and soft voting\n",
    "\n",
    "Three models give an applicant the probabilities of \"bad\" 0.8, 0.3 and 0.45. What do hard and soft voting decide?\n",
    "\n",
    "Idea. Hard: the majority of the classes; soft: the mean of the probabilities (Part 9).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{hard:}\\quad & \\text{bad, good, good} \\;\\Rightarrow\\; \\text{good (1 against 2)} \\\\[8pt]\n",
    "\\text{soft:}\\quad & \\frac{0.8 + 0.3 + 0.45}{3} = \\frac{1.55}{3} = 0.517 \\;\\Rightarrow\\; \\text{bad}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "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.\n",
    "\n",
    "Problem 5. Read and check\n",
    "\n",
    "Read the file. Print its shape, the number of gaps and the number of repeated rows.\n",
    "\n",
    "Idea. The first look (Part 7)."
   ],
   "id": "t35-075"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"german_credit.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.isna().sum().sum())\n",
    "print(df.duplicated().sum())"
   ],
   "id": "t35-076"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 1,000 applicants, nothing to fill, nothing to drop.\n",
    "\n",
    "Problem 6. The target and two columns\n",
    "\n",
    "Turn `risk` into 1 for bad and 0 for good, drop `personal_status` and `foreign_worker`, and print the share of bad credits.\n",
    "\n",
    "Idea. The positive class is the one to find; columns a fair decision must not use are removed (Part 7)."
   ],
   "id": "t35-077"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"risk\"] = (df[\"risk\"] == \"bad\").astype(int)\n",
    "df = df.drop(columns=[\"personal_status\", \"foreign_worker\"])\n",
    "\n",
    "print(df[\"risk\"].mean())"
   ],
   "id": "t35-078"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 30 percent bad: the baseline is 70 percent.\n",
    "\n",
    "Problem 7. Encode\n",
    "\n",
    "One-hot encode the eleven text columns with `drop_first=True` and `dtype=int`. Print the shape.\n",
    "\n",
    "Idea. An SVM needs numbers (Part 6)."
   ],
   "id": "t35-079"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text_columns = [\"checking_account\", \"credit_history\", \"purpose\", \"savings\", \"employment_years\", \"other_debtors\", \"property\", \"other_installments\", \"housing\", \"job\", \"telephone\"]\n",
    "\n",
    "df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t35-080"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 44 features and the target.\n",
    "\n",
    "Problem 8. Split\n",
    "\n",
    "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.\n",
    "\n",
    "Idea. The split comes before any value is learned from the data."
   ],
   "id": "t35-081"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df.drop(columns=[\"risk\"])\n",
    "y = df[\"risk\"]\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=7)\n",
    "\n",
    "print(X_train.shape, X_test.shape)\n",
    "print(round(y_test.mean(), 3))"
   ],
   "id": "t35-082"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 750 and 250 applicants; the baseline on this test data is 1 minus the printed share.\n",
    "\n",
    "Problem 9. Scale\n",
    "\n",
    "Fit a `StandardScaler` on the training data and scale both parts. Print the mean of the first scaled training column, rounded to 3 decimals.\n",
    "\n",
    "Idea. Scaling is essential for an SVM (Part 6)."
   ],
   "id": "t35-083"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "print(abs(X_train_scaled[:, 0].mean().round(3)))"
   ],
   "id": "t35-084"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 0: the scaler centres every training column.\n",
    "\n",
    "Problem 10. The default SVM\n",
    "\n",
    "Train an `SVC()` on the scaled data. Print its test accuracy and its recall, rounded to 4 decimals.\n",
    "\n",
    "Idea. The RBF kernel with `C=1` (Part 8)."
   ],
   "id": "t35-085"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.svm import SVC\n",
    "from sklearn.metrics import recall_score, f1_score\n",
    "\n",
    "svm = SVC()\n",
    "svm.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(svm.score(X_test_scaled, y_test), 4))\n",
    "print(round(recall_score(y_test, svm.predict(X_test_scaled)), 4))"
   ],
   "id": "t35-086"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: above the baseline, but less than half of the bad credits are found.\n",
    "\n",
    "Problem 11. Without scaling\n",
    "\n",
    "Train an `SVC()` on the unscaled data. Print its test accuracy and recall.\n",
    "\n",
    "Idea. The damage of missing scaling (Part 8)."
   ],
   "id": "t35-087"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "svm_raw = SVC()\n",
    "svm_raw.fit(X_train, y_train)\n",
    "\n",
    "print(round(svm_raw.score(X_test, y_test), 4))\n",
    "print(round(recall_score(y_test, svm_raw.predict(X_test)), 4))"
   ],
   "id": "t35-088"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: almost no bad credit is found: the credit amount decides alone.\n",
    "\n",
    "Problem 12. C with cross-validation\n",
    "\n",
    "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.\n",
    "\n",
    "Idea. C is chosen without the test data (Part 8)."
   ],
   "id": "t35-089"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "for C in [0.1, 1, 10]:\n",
    "    scores = cross_val_score(SVC(C=C), X_train_scaled, y_train, cv=5)\n",
    "    print(C, round(scores.mean(), 4))"
   ],
   "id": "t35-090"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: C = 1 is best; 0.1 says \"good\" for everyone, 10 overfits.\n",
    "\n",
    "Problem 13. Balanced\n",
    "\n",
    "Train an `SVC(class_weight=\"balanced\")`. Print its recall and F1-score, rounded to 4 decimals.\n",
    "\n",
    "Idea. A mistake on the bad class costs more (Part 8)."
   ],
   "id": "t35-091"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "svm_balanced = SVC(class_weight=\"balanced\")\n",
    "svm_balanced.fit(X_train_scaled, y_train)\n",
    "\n",
    "predicted_balanced = svm_balanced.predict(X_test_scaled)\n",
    "\n",
    "print(round(recall_score(y_test, predicted_balanced), 4))\n",
    "print(round(f1_score(y_test, predicted_balanced), 4))"
   ],
   "id": "t35-092"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: many more bad credits are found.\n",
    "\n",
    "Problem 14. Two other models\n",
    "\n",
    "Train a `LogisticRegression()` and a `RandomForestClassifier(random_state=42)`. Print the test accuracy of each, rounded to 4 decimals.\n",
    "\n",
    "Idea. Every voter is checked alone first (Part 10)."
   ],
   "id": "t35-093"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "\n",
    "logistic = LogisticRegression()\n",
    "logistic.fit(X_train_scaled, y_train)\n",
    "\n",
    "forest = RandomForestClassifier(random_state=42)\n",
    "forest.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(logistic.score(X_test_scaled, y_test), 4))\n",
    "print(round(forest.score(X_test_scaled, y_test), 4))"
   ],
   "id": "t35-094"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: both are clearly above the baseline: good voters.\n",
    "\n",
    "Problem 15. Hard and soft voting\n",
    "\n",
    "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.\n",
    "\n",
    "Idea. The same voters, two ways to combine them (Part 9)."
   ],
   "id": "t35-095"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import VotingClassifier\n",
    "\n",
    "voters = [(\"logistic\", LogisticRegression()), (\"forest\", RandomForestClassifier(random_state=42)), (\"svm\", SVC(probability=True, random_state=42))]\n",
    "\n",
    "hard = VotingClassifier(estimators=voters, voting=\"hard\")\n",
    "hard.fit(X_train_scaled, y_train)\n",
    "\n",
    "soft = VotingClassifier(estimators=voters, voting=\"soft\")\n",
    "soft.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(hard.score(X_test_scaled, y_test), 4))\n",
    "print(round(soft.score(X_test_scaled, y_test), 4))"
   ],
   "id": "t35-096"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: on this split hard voting is a little better: the order of the two can change from split to split.\n",
    "\n",
    "Problem 16. The AUC of the soft vote\n",
    "\n",
    "Print the AUC of the soft vote, rounded to 4 decimals.\n",
    "\n",
    "Idea. Only a soft vote has probabilities (Part 9)."
   ],
   "id": "t35-097"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import roc_auc_score\n",
    "\n",
    "print(round(roc_auc_score(y_test, soft.predict_proba(X_test_scaled)[:, 1]), 4))"
   ],
   "id": "t35-098"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the soft vote ranks the applicants well; the hard vote has no AUC.\n",
    "\n",
    "## 16. Summary\n",
    "\n",
    "|  | Formula or rule | Meaning |\n",
    "| --- | --- | --- |\n",
    "| Decision function | $f(x) = w \\cdot x + b$ | positive: class +1; negative: class −1; $\\lvert f \\rvert < 1$: inside the street |\n",
    "| Margin | $\\frac{2}{\\lVert w \\rVert}$ | the width of the street |\n",
    "| Hinge loss | $\\max\\bigl(0,\\ 1 - y\\,f(x)\\bigr)$ | the penalty of a row inside the street or on the wrong side |\n",
    "| Soft margin | $\\tfrac{1}{2}\\lVert w \\rVert^2 + C \\sum \\text{losses}$ | C: the cost of a mistake |\n",
    "| RBF kernel | $e^{-\\gamma \\lVert a - b \\rVert^2}$ | the similarity of two rows; $\\gamma$: how far a row reaches |\n",
    "| Soft vote | the mean of the probabilities | the class with the larger mean wins |\n",
    "\n",
    "| Code | What it does |\n",
    "| --- | --- |\n",
    "| `SVC()` | the support vector classifier (RBF kernel, `C=1`, `gamma=\"scale\"`) |\n",
    "| `SVC(kernel=\"linear\")` | a straight border; also `\"poly\"`, `\"sigmoid\"` |\n",
    "| `SVC(C=..., gamma=...)` | the cost of a mistake, the reach of a row |\n",
    "| `SVC(class_weight=\"balanced\")` | more weight for the smaller class |\n",
    "| `SVC(probability=True)` | adds `predict_proba` |\n",
    "| `svm.decision_function(X)` | $f(x)$ for every row |\n",
    "| `svm.n_support_`, `svm.support_vectors_` | the support vectors |\n",
    "| `VotingClassifier(estimators=..., voting=\"hard\")` | majority of the classes |\n",
    "| `VotingClassifier(estimators=..., voting=\"soft\", weights=...)` | mean of the probabilities |\n",
    "\n",
    "### Rules to keep\n",
    "\n",
    "1. An SVM separates the classes by the widest street; only the support vectors decide where it lies.\n",
    "2. Always scale the features of an SVM, and encode the text columns.\n",
    "3. Choose `C` (and `gamma` for RBF) with cross-validation: small values underfit, large values overfit.\n",
    "4. Start with the RBF kernel; try the linear one for many features.\n",
    "5. When the rare class matters, use `class_weight=\"balanced\"` and judge by recall and F1.\n",
    "6. Vote with good and different models; soft voting needs `predict_proba` from every voter.\n",
    "\n",
    "### What comes next\n",
    "\n",
    "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.\n",
    "\n",
    "Next: the practice notebook (topic-35-practice.ipynb), then Topic 36: Support Vector Machines and Voting - Regression."
   ],
   "id": "t35-099"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
