L’accès à des bases de données de plus en plus riches permet des modélisations de plus en plus raffinées. Cependant, les modèles parcimonieux sont généralement préférables aux modèles extrêmement riches pour obtenir de bonnes performances sur un nouveau jeu de données (prédictions out-of-sample). Les méthodes de sélection de variables, notamment le LASSO, permettent de sélectionner le signal le plus pertinent dilué au milieu du bruit lorsqu’on a beaucoup d’information à traiter.

Author

Lino Galiana

Published

July 15, 2023

Download nbviewer Onyxia Onyxia
Binder Open In Colab githubdev

Pour illustrer le travail de données nécessaire pour faire de la sélection de variables, nous allons partir du même jeu de données que précédemment, c’est-à-dire les résultats des élections US 2020 présentés dans l’introduction de cette partie : les données de vote aux élections présidentielles américaines croisées à des variables sociodémographiques. Le code est disponible sur Github.

import requests

url = 'https://raw.githubusercontent.com/linogaliana/python-datascientist/master/content/modelisation/get_data.py'
r = requests.get(url, allow_redirects=True)
open('getdata.py', 'wb').write(r.content)

import getdata
votes = getdata.create_votes_dataframes()

Jusqu’à présent, nous avons supposé que les variables utiles à la prévision du vote Républicain étaient connues du modélisateur. Nous n’avons ainsi exploité qu’une partie limitée des variables disponibles dans nos données. Néanmoins, outre le fléau computationnel que représenterait la construction d’un modèle avec un grand nombre de variables, le choix d’un nombre restreint de variables (modèle parcimonieux) limite le risque de sur-apprentissage.

Comment, dès lors, choisir le bon nombre de variables et la meilleure combinaison de ces variables ? Il existe de multiples méthodes, parmi lesquelles :

Principe du LASSO

Principe général

La classe des modèles de feature selection est ainsi très vaste et regroupe un ensemble très diverse de modèles. Nous allons nous focaliser sur le LASSO (Least Absolute Shrinkage and Selection Operator) qui est une extension de la régression linéaire qui vise à sélectionner des modèles sparses. Ce type de modèle est central dans le champ du Compressed sensing (où on emploie plutôt le terme de L1-regularization que de LASSO). Le LASSO est un cas particulier des régressions elastic-net dont un autre cas fameux est la régression ridge. Contrairement à la régression linéaire classique, elles fonctionnent également dans un cadre où \(p>N\), c’est à dire où le nombre de régresseurs est très grand puisque supérieur au nombre d’observations.

Pénalisation

En adoptant le principe d’une fonction objectif pénalisée, le LASSO permet de fixer un certain nombre de coefficients à 0. Les variables dont la norme est non nulle passent ainsi le test de sélection.

Première régression LASSO

Avant de se lancer dans les exercices, on va éliminer quelques colonnes redondantes, celles qui concernent les votes des partis concurrents (forcément très corrélés au vote Républicain…) :

df2 = votes.loc[:,~votes.columns.str.endswith(
  ('_democrat','_green','_other', 'per_point_diff', 'per_dem')
  )]

Nous allons utiliser par la suite les fonctions ou packages suivants :

import numpy as np
from sklearn.svm import LinearSVC
from sklearn.feature_selection import SelectFromModel
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Lasso
import sklearn.metrics
from sklearn.linear_model import LinearRegression
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from sklearn.linear_model import lasso_path
import seaborn as sns

A l’issue de la question 3, les variables sélectionnées sont :

['ALAND',
 'FIPS_y',
 'INTERNATIONAL_MIG_2017',
 'DOMESTIC_MIG_2014',
 'DOMESTIC_MIG_2017',
 'RESIDUAL_2010',
 'RESIDUAL_2019',
 'R_death_2012',
 'R_death_2019',
 'R_NATURAL_INC_2019',
 'R_INTERNATIONAL_MIG_2011',
 'R_DOMESTIC_MIG_2012',
 "Percent of adults with a bachelor's degree or higher, 1990",
 'Percent of adults with a high school diploma only, 2000',
 "Percent of adults with a bachelor's degree or higher, 2000",
 "Percent of adults with a bachelor's degree or higher, 2015-19",
 'Rural_urban_continuum_code_2013',
 'Metro_2013',
 'Unemployment_rate_2002',
 'Unemployment_rate_2003',
 'Unemployment_rate_2012',
 'Rural-urban_Continuum_Code_2003',
 'Rural-urban_Continuum_Code_2013',
 'CI90LB517P_2019',
 'candidatevotes_2016_republican',
 'share_2012_republican',
 'share_2016_republican']

Certaines variables font sens, comme les variables d’éducation par exemple. Notamment, un des meilleurs prédicteurs pour le score des Républicains en 2020 est… le score des Républicains (et mécaniquement des démocrates) en 2016.

Par ailleurs, on sélectionne des variables redondantes. Une phase plus approfondie de nettoyage des données serait en réalité nécessaire.

  ALAND FIPS_y INTERNATIONAL_MIG_2017 DOMESTIC_MIG_2014 DOMESTIC_MIG_2017 RESIDUAL_2010 RESIDUAL_2019 R_death_2012 R_death_2019 R_NATURAL_INC_2019 R_INTERNATIONAL_MIG_2011 R_DOMESTIC_MIG_2012 Percent of adults with a bachelor's degree or higher, 1990 Percent of adults with a high school diploma only, 2000 Percent of adults with a bachelor's degree or higher, 2000 Percent of adults with a bachelor's degree or higher, 2015-19 Rural_urban_continuum_code_2013 Metro_2013 Unemployment_rate_2002 Unemployment_rate_2003 Unemployment_rate_2012 Rural-urban_Continuum_Code_2003 Rural-urban_Continuum_Code_2013 CI90LB517P_2019 candidatevotes_2016_republican share_2012_republican share_2016_republican
ALAND 1.00 -0.01 0.03 0.05 0.06 -0.02 0.12 -0.11 -0.12 0.10 -0.03 0.03 0.06 -0.17 0.04 -0.00 0.08 -0.08 0.06 0.05 0.02 0.08 0.08 0.01 0.11 0.03 -0.04
FIPS_y -0.01 1.00 -0.04 0.01 0.01 -0.00 -0.05 0.01 -0.03 0.01 -0.00 0.11 0.03 0.01 0.03 0.04 0.01 -0.01 -0.01 -0.01 -0.20 0.01 0.01 -0.09 -0.06 0.05 0.05
INTERNATIONAL_MIG_2017 0.03 -0.04 1.00 -0.28 -0.56 -0.15 0.27 -0.19 -0.17 0.15 0.44 0.05 0.27 -0.25 0.26 0.27 -0.22 0.20 0.01 -0.01 0.00 -0.22 -0.22 -0.00 0.66 -0.23 -0.29
DOMESTIC_MIG_2014 0.05 0.01 -0.28 1.00 0.84 -0.05 0.10 -0.02 -0.03 -0.01 -0.10 0.16 0.01 -0.02 0.03 0.04 -0.03 0.04 -0.05 -0.06 -0.05 -0.03 -0.03 -0.11 -0.03 0.13 0.10
DOMESTIC_MIG_2017 0.06 0.01 -0.56 0.84 1.00 0.04 0.02 0.02 0.02 -0.05 -0.19 0.10 -0.05 0.04 -0.03 -0.02 -0.00 0.01 -0.04 -0.05 -0.02 0.00 -0.00 -0.10 -0.21 0.16 0.15
RESIDUAL_2010 -0.02 -0.00 -0.15 -0.05 0.04 1.00 0.09 -0.06 -0.07 0.09 -0.03 0.03 -0.03 -0.02 -0.03 -0.02 0.01 -0.01 0.02 0.02 0.01 0.01 0.01 0.03 -0.15 0.02 0.02
RESIDUAL_2019 0.12 -0.05 0.27 0.10 0.02 0.09 1.00 -0.06 -0.06 0.05 0.08 0.07 0.03 -0.09 0.03 0.02 -0.02 0.03 0.01 -0.00 0.02 -0.02 -0.02 0.01 0.27 0.02 -0.01
R_death_2012 -0.11 0.01 -0.19 -0.02 0.02 -0.06 -0.06 1.00 0.75 -0.62 -0.33 -0.11 -0.49 0.43 -0.50 -0.47 0.46 -0.41 0.14 0.16 0.08 0.45 0.46 0.26 -0.28 0.22 0.38
R_death_2019 -0.12 -0.03 -0.17 -0.03 0.02 -0.07 -0.06 0.75 1.00 -0.81 -0.35 -0.12 -0.49 0.42 -0.50 -0.47 0.28 -0.29 0.30 0.31 0.32 0.28 0.28 0.38 -0.22 0.07 0.23
R_NATURAL_INC_2019 0.10 0.01 0.15 -0.01 -0.05 0.09 0.05 -0.62 -0.81 1.00 0.32 0.11 0.31 -0.35 0.30 0.27 -0.24 0.22 -0.21 -0.22 -0.28 -0.24 -0.24 -0.18 0.18 -0.04 -0.19
R_INTERNATIONAL_MIG_2011 -0.03 -0.00 0.44 -0.10 -0.19 -0.03 0.08 -0.33 -0.35 0.32 1.00 0.08 0.48 -0.39 0.47 0.43 -0.23 0.21 -0.12 -0.13 -0.14 -0.23 -0.23 -0.09 0.31 -0.28 -0.37
R_DOMESTIC_MIG_2012 0.03 0.11 0.05 0.16 0.10 0.03 0.07 -0.11 -0.12 0.11 0.08 1.00 0.20 -0.15 0.22 0.27 -0.13 0.14 -0.16 -0.19 -0.21 -0.13 -0.13 -0.23 0.13 0.08 0.03
Percent of adults with a bachelor's degree or higher, 1990 0.06 0.03 0.27 0.01 -0.05 -0.03 0.03 -0.49 -0.49 0.31 0.48 0.20 1.00 -0.66 0.97 0.91 -0.37 0.35 -0.32 -0.33 -0.27 -0.37 -0.37 -0.36 0.40 -0.34 -0.53
Percent of adults with a high school diploma only, 2000 -0.17 0.01 -0.25 -0.02 0.04 -0.02 -0.09 0.43 0.42 -0.35 -0.39 -0.15 -0.66 1.00 -0.65 -0.58 0.25 -0.25 0.02 0.06 0.02 0.25 0.25 -0.01 -0.32 0.25 0.48
Percent of adults with a bachelor's degree or higher, 2000 0.04 0.03 0.26 0.03 -0.03 -0.03 0.03 -0.50 -0.50 0.30 0.47 0.22 0.97 -0.65 1.00 0.94 -0.37 0.37 -0.36 -0.36 -0.30 -0.38 -0.37 -0.41 0.39 -0.32 -0.51
Percent of adults with a bachelor's degree or higher, 2015-19 -0.00 0.04 0.27 0.04 -0.02 -0.02 0.02 -0.47 -0.47 0.27 0.43 0.27 0.91 -0.58 0.94 1.00 -0.41 0.41 -0.38 -0.38 -0.31 -0.41 -0.41 -0.47 0.40 -0.31 -0.49
Rural_urban_continuum_code_2013 0.08 0.01 -0.22 -0.03 -0.00 0.01 -0.02 0.46 0.28 -0.24 -0.23 -0.13 -0.37 0.25 -0.37 -0.41 1.00 -0.87 0.04 0.05 -0.07 0.93 1.00 0.18 -0.44 0.28 0.38
Metro_2013 -0.08 -0.01 0.20 0.04 0.01 -0.01 0.03 -0.41 -0.29 0.22 0.21 0.14 0.35 -0.25 0.37 0.41 -0.87 1.00 -0.10 -0.12 -0.00 -0.81 -0.87 -0.19 0.41 -0.21 -0.31
Unemployment_rate_2002 0.06 -0.01 0.01 -0.05 -0.04 0.02 0.01 0.14 0.30 -0.21 -0.12 -0.16 -0.32 0.02 -0.36 -0.38 0.04 -0.10 1.00 0.94 0.76 0.04 0.04 0.53 -0.02 -0.24 -0.18
Unemployment_rate_2003 0.05 -0.01 -0.01 -0.06 -0.05 0.02 -0.00 0.16 0.31 -0.22 -0.13 -0.19 -0.33 0.06 -0.36 -0.38 0.05 -0.12 0.94 1.00 0.74 0.05 0.05 0.51 -0.04 -0.24 -0.16
Unemployment_rate_2012 0.02 -0.20 0.00 -0.05 -0.02 0.01 0.02 0.08 0.32 -0.28 -0.14 -0.21 -0.27 0.02 -0.30 -0.31 -0.07 -0.00 0.76 0.74 1.00 -0.07 -0.07 0.55 0.02 -0.32 -0.25
Rural-urban_Continuum_Code_2003 0.08 0.01 -0.22 -0.03 0.00 0.01 -0.02 0.45 0.28 -0.24 -0.23 -0.13 -0.37 0.25 -0.38 -0.41 0.93 -0.81 0.04 0.05 -0.07 1.00 0.93 0.17 -0.45 0.29 0.39
Rural-urban_Continuum_Code_2013 0.08 0.01 -0.22 -0.03 -0.00 0.01 -0.02 0.46 0.28 -0.24 -0.23 -0.13 -0.37 0.25 -0.37 -0.41 1.00 -0.87 0.04 0.05 -0.07 0.93 1.00 0.18 -0.44 0.28 0.38
CI90LB517P_2019 0.01 -0.09 -0.00 -0.11 -0.10 0.03 0.01 0.26 0.38 -0.18 -0.09 -0.23 -0.36 -0.01 -0.41 -0.47 0.18 -0.19 0.53 0.51 0.55 0.17 0.18 1.00 -0.09 -0.17 -0.11
candidatevotes_2016_republican 0.11 -0.06 0.66 -0.03 -0.21 -0.15 0.27 -0.28 -0.22 0.18 0.31 0.13 0.40 -0.32 0.39 0.40 -0.44 0.41 -0.02 -0.04 0.02 -0.45 -0.44 -0.09 1.00 -0.22 -0.32
share_2012_republican 0.03 0.05 -0.23 0.13 0.16 0.02 0.02 0.22 0.07 -0.04 -0.28 0.08 -0.34 0.25 -0.32 -0.31 0.28 -0.21 -0.24 -0.24 -0.32 0.29 0.28 -0.17 -0.22 1.00 0.93
share_2016_republican -0.04 0.05 -0.29 0.10 0.15 0.02 -0.01 0.38 0.23 -0.19 -0.37 0.03 -0.53 0.48 -0.51 -0.49 0.38 -0.31 -0.18 -0.16 -0.25 0.39 0.38 -0.11 -0.32 0.93 1.00
<Figure size 672x480 with 0 Axes>

On voit que plus \(\alpha\) est élevé, moins le modèle sélectionne de variables.

Validation croisée pour sélectionner le modèle

Quel \(\alpha\) faut-il privilégier ? Pour cela, il convient d’effectuer une validation croisée afin de choisir le modèle pour lequel les variables qui passent la phase de sélection permettent de mieux prédire le résultat Républicain :

from sklearn.linear_model import LassoCV

df3 = df2.select_dtypes(include=np.number)
df3.replace([np.inf, -np.inf], np.nan, inplace=True)
df3 = df3.fillna(0)
scaler = StandardScaler()
yindex = df3.columns.get_loc("per_gop")
df3_scale = scaler.fit(df3).transform(df3)
# X_train, X_test , y_train, y_test = train_test_split(np.delete(data, yindex, axis = 1),data[:,yindex], test_size=0.2, random_state=0)

lcv = LassoCV(alphas=my_alphas, fit_intercept=False,random_state=0,cv=5).fit(np.delete(df3_scale, yindex, axis = 1), df3_scale[:,yindex])
alpha optimal : 0.001
/opt/mamba/lib/python3.9/site-packages/sklearn/linear_model/_coordinate_descent.py:628: ConvergenceWarning:

Objective did not converge. You might want to increase the number of iterations, check the scale of the features or consider increasing regularisation. Duality gap: 3.486e+03, tolerance: 6.352e+01

Les variables sélectionnées sont :

['ALAND', 'AWATER', 'votes_gop', 'diff', 'Rural-urban_Continuum Code_2003', 'Rural-urban_Continuum Code_2013', 'Urban_Influence_Code_2013', 'Economic_typology_2015', 'CENSUS_2010_POP', 'N_POP_CHG_2013', 'N_POP_CHG_2016', 'N_POP_CHG_2017', 'N_POP_CHG_2018', 'N_POP_CHG_2019', 'Births_2011', 'Births_2015', 'Deaths_2015', 'Deaths_2017', 'Deaths_2018', 'NATURAL_INC_2012', 'NATURAL_INC_2013', 'NATURAL_INC_2014', 'NATURAL_INC_2016', 'NATURAL_INC_2018', 'INTERNATIONAL_MIG_2010', 'INTERNATIONAL_MIG_2011', 'INTERNATIONAL_MIG_2012', 'INTERNATIONAL_MIG_2013', 'INTERNATIONAL_MIG_2014', 'INTERNATIONAL_MIG_2015', 'INTERNATIONAL_MIG_2016', 'INTERNATIONAL_MIG_2017', 'INTERNATIONAL_MIG_2018', 'INTERNATIONAL_MIG_2019', 'DOMESTIC_MIG_2010', 'DOMESTIC_MIG_2012', 'DOMESTIC_MIG_2013', 'DOMESTIC_MIG_2015', 'DOMESTIC_MIG_2016', 'DOMESTIC_MIG_2018', 'NET_MIG_2011', 'NET_MIG_2014', 'NET_MIG_2018', 'NET_MIG_2019', 'RESIDUAL_2010', 'RESIDUAL_2011', 'RESIDUAL_2012', 'RESIDUAL_2013', 'RESIDUAL_2014', 'RESIDUAL_2015', 'RESIDUAL_2016', 'RESIDUAL_2017', 'RESIDUAL_2018', 'RESIDUAL_2019', 'GQ_ESTIMATES_BASE_2010', 'GQ_ESTIMATES_2013', 'GQ_ESTIMATES_2015', 'GQ_ESTIMATES_2017', 'R_birth_2011', 'R_birth_2013', 'R_birth_2014', 'R_birth_2016', 'R_birth_2017', 'R_birth_2019', 'R_death_2011', 'R_death_2012', 'R_death_2013', 'R_death_2014', 'R_death_2015', 'R_death_2016', 'R_death_2017', 'R_death_2018', 'R_death_2019', 'R_NATURAL_INC_2012', 'R_NATURAL_INC_2015', 'R_NATURAL_INC_2017', 'R_NATURAL_INC_2018', 'R_NATURAL_INC_2019', 'R_INTERNATIONAL_MIG_2011', 'R_INTERNATIONAL_MIG_2012', 'R_INTERNATIONAL_MIG_2013', 'R_INTERNATIONAL_MIG_2014', 'R_INTERNATIONAL_MIG_2015', 'R_INTERNATIONAL_MIG_2016', 'R_INTERNATIONAL_MIG_2017', 'R_INTERNATIONAL_MIG_2018', 'R_INTERNATIONAL_MIG_2019', 'R_DOMESTIC_MIG_2011', 'R_DOMESTIC_MIG_2012', 'R_DOMESTIC_MIG_2013', 'R_DOMESTIC_MIG_2015', 'R_DOMESTIC_MIG_2016', 'R_DOMESTIC_MIG_2018', 'R_NET_MIG_2014', 'R_NET_MIG_2017', 'R_NET_MIG_2019', '2003 Rural-urban Continuum Code', 'Less than a high school diploma, 1970', 'High school diploma only, 1970', 'Some college (1-3 years), 1970', 'Four years of college or higher, 1970', 'Percent of adults with less than a high school diploma, 1970', 'Percent of adults with a high school diploma only, 1970', 'Percent of adults completing some college (1-3 years), 1970', 'Percent of adults completing four years of college or higher, 1970', 'Less than a high school diploma, 1980', 'High school diploma only, 1980', 'Some college (1-3 years), 1980', 'Four years of college or higher, 1980', 'Percent of adults with less than a high school diploma, 1980', 'Percent of adults with a high school diploma only, 1980', 'Percent of adults completing some college (1-3 years), 1980', 'Percent of adults completing four years of college or higher, 1980', 'Less than a high school diploma, 1990', 'Percent of adults with less than a high school diploma, 1990', 'Percent of adults with a high school diploma only, 1990', 'Less than a high school diploma, 2000', 'High school diploma only, 2000', "Some college or associate's degree, 2000", "Bachelor's degree or higher, 2000", 'Percent of adults with less than a high school diploma, 2000', 'Percent of adults with a high school diploma only, 2000', "Percent of adults completing some college or associate's degree, 2000", "Percent of adults with a bachelor's degree or higher, 2000", 'Less than a high school diploma, 2015-19', 'High school diploma only, 2015-19', "Some college or associate's degree, 2015-19", "Bachelor's degree or higher, 2015-19", 'Percent of adults with less than a high school diploma, 2015-19', 'Percent of adults with a high school diploma only, 2015-19', "Percent of adults completing some college or associate's degree, 2015-19", "Percent of adults with a bachelor's degree or higher, 2015-19", 'Metro_2013', 'Unemployed_2000', 'Unemployment_rate_2000', 'Unemployment_rate_2001', 'Unemployed_2002', 'Unemployment_rate_2002', 'Unemployed_2003', 'Unemployment_rate_2003', 'Civilian_labor_force_2004', 'Employed_2004', 'Unemployment_rate_2004', 'Civilian_labor_force_2005', 'Unemployed_2005', 'Unemployment_rate_2005', 'Civilian_labor_force_2006', 'Unemployed_2006', 'Unemployment_rate_2006', 'Unemployed_2007', 'Unemployment_rate_2007', 'Unemployed_2008', 'Unemployment_rate_2008', 'Employed_2009', 'Unemployment_rate_2009', 'Employed_2010', 'Unemployment_rate_2010', 'Civilian_labor_force_2011', 'Employed_2011', 'Unemployed_2011', 'Civilian_labor_force_2012', 'Employed_2012', 'Unemployed_2012', 'Unemployment_rate_2012', 'Unemployed_2013', 'Unemployment_rate_2013', 'Unemployed_2014', 'Unemployment_rate_2014', 'Civilian_labor_force_2015', 'Employed_2015', 'Unemployment_rate_2015', 'Unemployed_2016', 'Unemployment_rate_2016', 'Unemployed_2017', 'Unemployment_rate_2017', 'Unemployed_2018', 'Unemployment_rate_2018', 'Unemployment_rate_2019', 'Med_HH_Income_Percent_of_State_Total_2019', 'Rural-urban_Continuum_Code_2003', 'Urban_Influence_Code_2003', 'Rural-urban_Continuum_Code_2013', 'POVALL_2019', 'CI90LBALL_2019', 'CI90UBALL_2019', 'CI90LBALLP_2019', 'CI90UBALLP_2019', 'POV017_2019', 'CI90LB017_2019', 'CI90UB017_2019', 'CI90LB017P_2019', 'CI90LB517_2019', 'CI90UB517_2019', 'PCTPOV517_2019', 'CI90LB517P_2019', 'CI90LBINC_2019', 'CI90UBINC_2019', 'candidatevotes_2000_republican', 'candidatevotes_2004_republican', 'candidatevotes_2008_republican', 'candidatevotes_2012_republican', 'candidatevotes_2016_republican', 'share_2000_republican', 'share_2008_republican', 'share_2012_republican', 'share_2016_republican']

Cela correspond à un modèle avec 206 variables sélectionnées.

Back to top

Citation

BibTeX citation:
@book{galiana2023,
  author = {Galiana, Lino},
  title = {Python Pour La Data Science},
  date = {2023},
  url = {https://pythonds.linogaliana.fr/},
  doi = {10.5281/zenodo.8229676},
  langid = {en}
}
For attribution, please cite this work as:
Galiana, Lino. 2023. Python Pour La Data Science. https://doi.org/10.5281/zenodo.8229676.