You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
title: "Découverte de la classification avec la technique des SVM"
3
+
title-en: "Discovering classification with the SVM technique"
3
4
categories:
4
5
- Modélisation
5
6
description: |
6
-
La classification permet d'attribuer une classe d'appartenance (_label_
7
-
dans la terminologie du _machine learning_)
8
-
discrète à des données à partir de certaines variables explicatives
9
-
(_features_ dans la même terminologie).
10
-
Les algorithmes de classification sont nombreux. L'un des plus intuitifs et
11
-
les plus fréquemment rencontrés sont les _SVM_ (*Support Vector Machine*).
12
-
Ce chapitre illustre les enjeux de la classification à partir de
13
-
ce modèle sur les données de vote aux élections présidentielles US de 2020.
7
+
La classification permet d'attribuer une classe d'appartenance (_label_ dans la terminologie du _machine learning_) discrète à des données à partir de certaines variables explicatives (_features_ dans la même terminologie). Les algorithmes de classification sont nombreux. L'un des plus intuitifs et les plus fréquemment rencontrés sont les _SVM_ (*Support Vector Machine*). Ce chapitre illustre les enjeux de la classification à partir de ce modèle sur les données de vote aux élections présidentielles US de 2020.
8
+
description-en: |
9
+
Classification enables us to assign a discrete membership class (_label_ in machine learning terminology) to data, based on certain explanatory variables (_features_ in the same terminology). Classification algorithms are numerous. One of the most intuitive and frequently encountered is _SVM_ (*Support Vector Machine*). This chapter illustrates the challenges of using this model to classify model on voting data for the 2020 US presidential elections.
14
10
echo: false
15
11
---
16
12
@@ -19,21 +15,31 @@ echo: false
19
15
printMessage="true"
20
16
>}}
21
17
18
+
::: {.content-visible when-profile="fr"}
22
19
# Introduction
23
20
24
-
Ce chapitre vise à présenter de manière très succincte le principe de l'entraînement de modèles dans un cadre de classification. L'objectif est d'illustrer la démarche à partir d'un algorithme dont le principe est assez intuitif. Il s'agit d'illustrer quelques uns des concepts évoqués dans les chapitres précédents, notamment ceux relatifs à l'entraînement d'un modèle. D'autres cours de votre scolarité vous permettront de découvrir d'autres algorithmes de classification et les limites de chaque technique.
25
-
21
+
Ce chapitre vise à présenter de manière très succincte le principe de l'entraînement de modèles dans un cadre de classification. L'objectif est d'illustrer la démarche à partir d'un algorithme dont le principe est assez intuitif. Il s'agit d'illustrer quelques uns des concepts évoqués dans les chapitres précédents, notamment ceux relatifs à l'entraînement d'un modèle. D'autres cours de votre scolarité vous permettront de découvrir d'autres algorithmes de classification et les limites de chaque technique.
26
22
27
23
## Données
24
+
:::
25
+
26
+
::: {.content-visible when-profile="en"}
27
+
# Introduction
28
+
29
+
This chapter aims to very briefly introduce the principle of training models in a classification context. The goal is to illustrate the process using an algorithm with an intuitive principle. It seeks to demonstrate some of the concepts discussed in previous chapters, particularly those related to model training. Other courses in your curriculum will allow you to explore additional classification algorithms and the limitations of each technique.
30
+
31
+
## Data
32
+
:::
28
33
29
34
30
35
{{< include _import_data_ml.qmd >}}
31
36
37
+
:::: {.content-visible when-profile="fr"}
32
38
## La méthode des _SVM_ (_Support Vector Machines_)
33
39
34
40
Les SVM (_Support Vector Machines_) font partie de la boîte à outil traditionnelle des _data scientists_.
35
41
Le principe de cette technique est relativement intuitif grâce à son interprétation géométrique.
36
-
Il s'agit de trouver une droite, avec des marges (les supports) qui discrimine au mieux le nuage de point de nos données.
42
+
Il s'agit de trouver une droite, avec des marges (les supports) qui discrimine au mieux le nuage de points de nos données.
37
43
Bien-sûr, dans la vraie vie, il est rare d'avoir des nuages de points bien ordonnés pour pouvoir les séparer par une droite. Mais une projection adéquate (un noyau ou _kernel_) peut arranger des données pour permettre de discriminer les données.
38
44
39
45
```{=html}
@@ -61,12 +67,52 @@ des _labels_ homogènes.
61
67
On peut, sans perdre de généralité,
62
68
supposer que le problème consiste à supposer l'existence d'une loi de probabilité $\mathbb{P}(x,y)$ ($\mathbb{P} \to \{-1,1\}$) qui est inconnue. Le problème de discrimination
63
69
vise à construire un estimateur de la fonction de décision idéale qui minimise la probabilité d'erreur. Autrement dit
70
+
:::
71
+
72
+
::::
73
+
74
+
:::: {.content-visible when-profile="en"}
75
+
## The SVM Method (_Support Vector Machines_)
76
+
77
+
SVM (_Support Vector Machines_) is part of the traditional toolkit for _data scientists_.
78
+
The principle of this technique is relatively intuitive thanks to its geometric interpretation.
79
+
The goal is to find a line, with margins (supports), that best separates the point cloud in our data.
80
+
Of course, in real life, it is rare to have well-organized point clouds that can be separated by a line. However, an appropriate projection (a kernel) can transform the data to enable separation.
SVM is one of the most intuitive _machine learning_ methods
90
+
due to its simple geometric interpretation. It is also
91
+
one of the least complex _machine learning_ algorithms in terms of formalization
92
+
for practitioners familiar with traditional statistics. This note provides an overview, though it is not essential for understanding this chapter.
93
+
In _machine learning_, more than the mathematical details, the key is to build intuitions.
94
+
95
+
The goal of SVM, let us recall, is to find a hyperplane that
96
+
best separates the different classes. For example, in a two-dimensional space,
97
+
it aims to find a line with margins that best divides the space into regions
98
+
with homogeneous _labels_.
99
+
100
+
Without loss of generality, we can assume the problem involves a probability distribution $\mathbb{P}(x,y)$ ($\mathbb{P} \to \{-1,1\}$) that is unknown. The goal of classification is to build an estimator of the ideal decision function that minimizes the probability of error. In other words
101
+
:::
102
+
64
103
65
104
$$
66
105
\theta = \arg\min_\Theta \mathbb{P}(h_\theta(X) \neq y |x)
67
106
$$
68
107
108
+
::: {.content-visible when-profile="fr"}
69
109
Les SVM les plus simples sont les SVM linéaires. Dans ce cas, on suppose qu'il existe un séparateur linéaire qui permet d'associer chaque classe à son signe:
110
+
:::
111
+
112
+
::: {.content-visible when-profile="en"}
113
+
The simplest SVMs are linear SVMs. In this case, it is assumed that a linear separator exists that can assign each class based on its sign:
114
+
:::
115
+
70
116
71
117
$$
72
118
h_\theta(x) = \text{signe}(f_\theta(x)) ; \text{ avec } f_\theta(x) = \theta^T x + b
@@ -77,20 +123,34 @@ avec $\theta \in \mathbb{R}^p$ et $w \in \mathbb{R}$.
77
123
<img src="https://upload.wikimedia.org/wikipedia/commons/7/72/SVM_margin.png" alt="Les SVM dans le cas linéaire" style="width: 40%;">
78
124
```
79
125
80
-
Lorsque des observations sont linéairement séparables,
81
-
il existe une infinité de frontières de décision linéaire séparant les deux classes. Le _"meilleur"_ choix est de prendre la marge maximale permettant de séparer les données. La distance entre les deux marges est $\frac{2}{||\theta||}$. Donc maximiser cette distance entre deux hyperplans revient à minimiser $||\theta||^2$ sous la contrainte $y_i(\theta^Tx_i + b) \geq 1$.
126
+
::: {.content-visible when-profile="fr"}
127
+
Lorsque des observations sont linéairement séparables, il existe une infinité de frontières de décision linéaire séparant les deux classes. Le _"meilleur"_ choix est de prendre la marge maximale permettant de séparer les données. La distance entre les deux marges est $\frac{2}{||\theta||}$. Donc maximiser cette distance entre deux hyperplans revient à minimiser $||\theta||^2$ sous la contrainte $y_i(\theta^Tx_i + b) \geq 1$.
82
128
83
129
Dans le cas non linéairement séparable, la *hinge loss* $\max\big(0,y_i(\theta^Tx_i + b)\big)$ permet de linéariser la fonction de perte, ce qui donne le programme d'optimisation suivant :
130
+
:::
131
+
132
+
::: {.content-visible when-profile="en"}
133
+
When observations are linearly separable, there is an infinite number of linear decision boundaries separating the two classes. The _"best"_ choice is to select the maximum margin that separates the data. The distance between the two margins is $\frac{2}{||\theta||}$. Thus, maximizing this distance between two hyperplanes is equivalent to minimizing $||\theta||^2$ under the constraint $y_i(\theta^Tx_i + b) \geq 1$.
134
+
135
+
In the non-linearly separable case, the *hinge loss* $\max\big(0,y_i(\theta^Tx_i + b)\big)$ allows for linearizing the loss function, resulting in the following optimization problem:
La généralisation au cas non linéaire implique d'introduire des noyaux transformant l'espace de coordonnées des observations.
144
+
:::
90
145
146
+
::: {.content-visible when-profile="en"}
147
+
Generalization to the non-linear case involves introducing kernels that transform the coordinate space of the observations.
91
148
:::
92
149
150
+
::::
151
+
93
152
153
+
::: {.content-visible when-profile="fr"}
94
154
# Application
95
155
96
156
Pour appliquer un modèle de classification, il nous faut
@@ -101,6 +161,16 @@ défaite d'un des partis.
101
161
Même si les Républicains ont perdu en 2020, ils l'ont emporté
102
162
dans plus de comtés (moins peuplés). Nous allons considérer
103
163
que la victoire des Républicains est notre _label_ 1 et la défaite _0_.
164
+
:::
165
+
166
+
::: {.content-visible when-profile="en"}
167
+
# Application
168
+
169
+
To apply a classification model, we need to find a dichotomous variable. The natural choice is to use the dichotomous variable of a party's victory or defeat.
170
+
171
+
Even though the Republicans lost in 2020, they won in more counties (less populated ones). We will consider a Republican victory as our _label_ 1 and a defeat as _0_.
172
+
:::
173
+
104
174
105
175
```{python}
106
176
#| echo: true
@@ -111,7 +181,10 @@ from sklearn.model_selection import cross_val_score
111
181
import matplotlib.pyplot as plt
112
182
```
113
183
114
-
::: {.exercise}
184
+
185
+
::: {.content-visible when-profile="fr"}
186
+
187
+
:::: {.exercise}
115
188
## Exercice 1 : Premier algorithme de classification
116
189
117
190
1. Créer une variable *dummy* appelée `y` dont la valeur vaut 1 quand les républicains l'emportent.
@@ -133,7 +206,48 @@ créer des échantillons de test (20 % des observations) et d'estimation (80 %)
133
206
6. Changer de variables *x*. Utiliser uniquement le résultat passé du vote démocrate (année 2016) et le revenu. Les variables en question sont `share_2016_republican` et `Median_Household_Income_2019`. Regarder les résultats, notamment la matrice de confusion.
134
207
135
208
7.[OPTIONNEL] Faire une 5-fold validation croisée pour déterminer le paramètre *C* idéal.
209
+
::::
210
+
211
+
:::
212
+
213
+
214
+
:::: {.content-visible when-profile="en"}
215
+
::: {.exercise}
216
+
217
+
## Exercise 1: First classification algorithm
218
+
219
+
1. Create a *dummy* variable called `y` with a value of 1 when the Republicans win.
220
+
2. Using the ready-to-use function `train_test_split` from the `sklearn.model_selection` library,
221
+
create test samples (20% of the observations) and training samples (80%) with the following *features*:
"Percent of adults with less than a high school diploma, 2015-19",
227
+
"Percent of adults with a bachelor's degree or higher, 2015-19"
228
+
]
229
+
```
230
+
231
+
and use the variable `y` as the *label*.
232
+
233
+
*Note: You may encounter the following warning:*
234
+
235
+
> A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel()
236
+
237
+
*Note: To avoid this warning every time you train your model, you can use `DataFrame[['y']].values.ravel()` instead of `DataFrame[['y']]` when preparing your samples.*
238
+
239
+
3. Train an SVM classifier with a regularization parameter `C = 1`. Examine the following performance metrics: `accuracy`, `f1`, `recall`, and `precision`.
240
+
241
+
4. Check the confusion matrix: despite seemingly reasonable scores, you should notice a significant issue.
242
+
243
+
5. Repeat the previous steps using normalized variables. Are the results different?
244
+
245
+
6. Change the *x* variables. Use only the previous Democratic vote result (2016) and income. The variables in question are `share_2016_republican` and `Median_Household_Income_2019`. Examine the results, particularly the confusion matrix.
246
+
247
+
7.[OPTIONAL] Perform 5-fold cross-validation to determine the ideal *C* parameter.
#2. Création des échantillons d'entraînement et de validation
147
-
xvars = ['Unemployment_rate_2019', 'Median_Household_Income_2019', 'Percent of adults with less than a high school diploma, 2015-19', "Percent of adults with a bachelor's degree or higher, 2015-19"]
A l'issue de la question 3, notre classifieur manque totalement les labels 0, qui sont minoritaires. Parmi les raisons possibles: l'échelle des variables. Le revenu, notamment, a une distribution qui peut écraser celle des autres variables, dans un modèle linéaire. Il faut donc, a minima, standardiser les variables, ce qui est l'objet de la question 4
320
+
321
+
::: {.content-visible when-profile="fr"}
322
+
A l'issue de la question 3, notre classifieur manque totalement les labels 0, qui sont minoritaires. Parmi les raisons possibles : l'échelle des variables. Le revenu, notamment, a une distribution qui peut écraser celle des autres variables, dans un modèle linéaire. Il faut donc, a minima, standardiser les variables, ce qui est l'objet de la question 4.
323
+
:::
324
+
325
+
::: {.content-visible when-profile="en"}
326
+
At the end of question 3, our classifier completely misses the 0 labels, which are in the minority. One possible reason is the scale of the variables. Income, in particular, has a distribution that can dominate the others in a linear model. Therefore, at a minimum, it is necessary to standardize the variables, which is the focus of question 4.
327
+
:::
187
328
188
329
189
330
@@ -201,15 +342,21 @@ disp.plot()
201
342
plt.show()
202
343
```
203
344
204
-
Standardiser les variables n'apporte finalement pas de gain:
345
+
::: {.content-visible when-profile="fr"}
346
+
Standardiser les variables n'apporte finalement pas de gain :
347
+
:::
348
+
349
+
::: {.content-visible when-profile="en"}
350
+
Standardizing the variables ultimately does not bring any improvement:
351
+
:::
205
352
206
353
```{python}
207
354
import sklearn.preprocessing as preprocessing
208
355
209
356
X = df.loc[:, xvars]
210
357
y = df[['y']]
211
-
scaler = preprocessing.StandardScaler().fit(X) #Ici on estime
cm = sklearn.metrics.confusion_matrix(y_test, predictions, labels=clf.classes_)
222
369
disp = sklearn.metrics.ConfusionMatrixDisplay(
223
-
confusion_matrix=cm,
224
-
display_labels=clf.classes_
225
-
)
370
+
confusion_matrix=cm,
371
+
display_labels=clf.classes_
372
+
)
226
373
disp.plot()
227
374
plt.show()
228
375
```
229
376
230
-
Il faut donc aller plus loin : le problème ne vient pas de l'échelle mais du choix des variables. C'est pour cette raison que l'étape de sélection de variable est cruciale et qu'un chapitre y est consacré.
377
+
::: {.content-visible when-profile="fr"}
378
+
Il faut donc aller plus loin : le problème ne vient pas de l'échelle mais du choix des variables. C'est pour cette raison que l'étape de sélection de variables est cruciale et qu'un chapitre y est consacré.
231
379
232
-
A l'issue de la question 6,
233
-
le nouveau classifieur avec devrait avoir les performances suivantes :
380
+
À l'issue de la question 6, le nouveau classifieur devrait avoir les performances suivantes :
381
+
:::
234
382
235
-
```{python}
236
-
#| output: asis
383
+
::: {.content-visible when-profile="en"}
384
+
It is therefore necessary to go further: the problem does not lie in the scale but in the choice of variables. This is why the step of variable selection is crucial and why a chapter is dedicated to it.
237
385
238
-
out = pd.DataFrame.from_dict({"Accuracy": [sc_accuracy], "Recall": [sc_recall],
0 commit comments