TP3 : Analyse multivariée en Python¶

1. Préparation et exploration du jeu de données¶

In [1]:
import os
import pandas as pd
import geopandas as gpd
import numpy as np
import matplotlib.pyplot as plt

Chargement, reprojection et affichage des données

In [2]:
filosofi = gpd.read_file(os.path.join("..", "TP_2_analyse_bivariee", "carreaux_1km_met.shp"), engine="pyogrio")
In [3]:
filosofi = filosofi.to_crs(epsg=2154)
In [4]:
filosofi.head()
Out[4]:
idcar_1km i_est_1km lcog_geo ind men men_pauv men_1ind men_5ind men_prop men_fmp ... ind_6_10 ind_11_17 ind_18_24 ind_25_39 ind_40_54 ind_55_64 ind_65_79 ind_80p ind_inc geometry
0 CRS3035RES1000mN2029000E4252000 1 2A041 3.0 1.4 0.3 0.5 0.1 0.8 0.1 ... 0.2 0.2 0.3 0.2 0.6 0.2 1.0 0.3 0.0 POLYGON ((1218038.251 6048790.697, 1217949.529...
1 CRS3035RES1000mN2029000E4254000 1 2A041 2.0 0.9 0.2 0.3 0.0 0.5 0.0 ... 0.1 0.1 0.2 0.1 0.4 0.1 0.7 0.3 0.0 POLYGON ((1220028.075 6048968.632, 1219939.34 ...
2 CRS3035RES1000mN2030000E4252000 1 2A041 6.0 2.5 0.3 0.3 0.1 1.6 0.5 ... 0.1 0.5 0.3 0.7 1.5 1.4 1.1 0.3 0.0 POLYGON ((1217949.529 6049793.871, 1217860.808...
3 CRS3035RES1000mN2030000E4253000 1 2A041 16.5 6.9 0.7 1.0 0.3 4.3 1.3 ... 0.3 1.3 1.0 2.0 4.0 3.7 3.0 0.7 0.0 POLYGON ((1218944.435 6049882.842, 1218855.707...
4 CRS3035RES1000mN2030000E4254000 1 2A041 5.0 2.4 0.5 0.9 0.1 1.4 0.1 ... 0.2 0.4 0.5 0.4 1.0 0.4 1.6 0.5 0.0 POLYGON ((1219939.34 6049971.805, 1219850.606 ...

5 rows × 32 columns

Filtre pour avoir uniquement le département de l'Ain : on ne garde que les carreaux dont le code officiel géographique commence par le numéro du département, ici '01'.

In [80]:
filosofi_ain = filosofi[filosofi['lcog_geo'].str.startswith('01')]
In [81]:
filosofi_ain.plot(column="ind", cmap="viridis", legend=True, figsize=(20, 20))
Out[81]:
<Axes: >
No description has been provided for this image
In [82]:
filosofi_ain.columns
Out[82]:
Index(['idcar_1km', 'i_est_1km', 'lcog_geo', 'ind', 'men', 'men_pauv',
       'men_1ind', 'men_5ind', 'men_prop', 'men_fmp', 'ind_snv', 'men_surf',
       'men_coll', 'men_mais', 'log_av45', 'log_45_70', 'log_70_90',
       'log_ap90', 'log_inc', 'log_soc', 'ind_0_3', 'ind_4_5', 'ind_6_10',
       'ind_11_17', 'ind_18_24', 'ind_25_39', 'ind_40_54', 'ind_55_64',
       'ind_65_79', 'ind_80p', 'ind_inc', 'geometry'],
      dtype='object')
In [83]:
filosofi_ain["nv_moy"] = filosofi_ain.loc[:, "ind_snv"] / filosofi_ain.loc[:,"ind"]
filosofi_ain["prop_maison"] = filosofi_ain.loc[:,"men_mais"] /filosofi_ain.loc[:,"men"]
filosofi_ain["prop_proprio"] = filosofi_ain.loc[:,"men_prop"] / filosofi_ain.loc[:,"men"]
filosofi_ain["prop_social"] = filosofi_ain.loc[:,"log_soc"] / filosofi_ain.loc[:,"men"]
filosofi_ain["prop>65"] = (filosofi_ain.loc[:,'ind_65_79'] + filosofi_ain.loc[:,'ind_80p']) / filosofi_ain.loc[:,"ind"]
filosofi_ain["prop<18"] = (filosofi_ain.loc[:,"ind_0_3"] + filosofi_ain.loc[:,"ind_4_5"] +filosofi_ain.loc[:,"ind_6_10"] +filosofi_ain.loc[:,"ind_11_17"]) / filosofi_ain.loc[:,"ind"]
c:\Users\mcubaud\AppData\Local\anaconda3\envs\geo2\lib\site-packages\geopandas\geodataframe.py:1969: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  super().__setitem__(key, value)
c:\Users\mcubaud\AppData\Local\anaconda3\envs\geo2\lib\site-packages\geopandas\geodataframe.py:1969: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  super().__setitem__(key, value)
c:\Users\mcubaud\AppData\Local\anaconda3\envs\geo2\lib\site-packages\geopandas\geodataframe.py:1969: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  super().__setitem__(key, value)
c:\Users\mcubaud\AppData\Local\anaconda3\envs\geo2\lib\site-packages\geopandas\geodataframe.py:1969: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  super().__setitem__(key, value)
c:\Users\mcubaud\AppData\Local\anaconda3\envs\geo2\lib\site-packages\geopandas\geodataframe.py:1969: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  super().__setitem__(key, value)
c:\Users\mcubaud\AppData\Local\anaconda3\envs\geo2\lib\site-packages\geopandas\geodataframe.py:1969: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  super().__setitem__(key, value)

Ces messages de warning nous disent en gros que filosofi_ain est encore lié à filosofi, mais qu'on a modifié que filosofi_ain (c'est ce qu'on veut). On peut les désactiver en faisant préalablement filosofi_ain = filosofi_ain.copy(), ce qui enlève le lien entre les deux dataframes.

Cartes de nos nouvelles variables

In [9]:
for col in ["nv_moy", "prop_maison", "prop_proprio", "prop_social", "prop>65", "prop<18"]:
    filosofi_ain.plot(column=col, cmap="viridis", legend=True, figsize=(20, 20)).set_title(col)
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
In [10]:
filosofi_ain.describe()
Out[10]:
i_est_1km ind men men_pauv men_1ind men_5ind men_prop men_fmp ind_snv men_surf ... ind_55_64 ind_65_79 ind_80p ind_inc nv_moy prop_maison prop_proprio prop_social prop>65 prop<18
count 4131.000000 4131.000000 4131.000000 4131.000000 4131.000000 4131.000000 4131.000000 4131.000000 4.131000e+03 4131.000000 ... 4131.000000 4131.000000 4131.000000 4131.000000 4131.000000 4131.000000 4131.000000 4131.000000 4131.000000 4131.000000
mean 0.586541 151.899903 63.776107 6.716848 19.558291 4.700678 40.711837 6.637061 3.988067e+06 6289.672331 ... 18.792012 19.899467 7.161656 0.106972 26302.990294 0.896489 0.799803 0.035064 0.207973 0.212123
std 0.497405 381.084056 173.219623 30.462708 73.146868 13.653213 82.824247 21.375576 9.655433e+06 14498.452872 ... 43.738825 50.904243 22.428329 1.179535 4514.040863 0.164857 0.152949 0.098569 0.089664 0.071992
min 0.000000 1.000000 0.300000 0.000000 0.000000 0.000000 0.000000 0.000000 1.809780e+04 38.300000 ... 0.000000 0.000000 0.000000 0.000000 13403.365108 0.000000 0.000000 0.000000 0.000000 0.000000
25% 0.000000 10.000000 4.000000 0.100000 0.900000 0.100000 3.200000 0.100000 2.512328e+05 490.050000 ... 1.400000 1.400000 0.300000 0.000000 23436.163366 0.866667 0.725000 0.000000 0.144554 0.166667
50% 1.000000 32.000000 13.100000 0.900000 3.100000 0.900000 11.000000 0.900000 8.314889e+05 1552.100000 ... 4.700000 4.800000 1.400000 0.000000 25493.512088 0.961538 0.833246 0.000000 0.200000 0.215789
75% 1.000000 120.500000 48.000000 3.000000 11.200000 3.800000 38.000000 4.000000 3.036242e+06 5303.500000 ... 16.100000 16.400000 5.000000 0.000000 28175.941654 1.000000 0.909228 0.000000 0.261111 0.259111
max 2.000000 5849.500000 3115.000000 694.000000 1847.000000 323.000000 1072.000000 382.000000 1.261332e+08 239404.000000 ... 632.000000 879.100000 417.000000 48.000000 50068.713725 1.000000 1.000000 1.000000 0.700000 0.503759

8 rows × 35 columns

On peut afficher le type des colonnes à l'aide de l'attribut .dtypes. Ici on constate que toutes les variables quantitatives sont au format float64 (Nombre à virgule encodé sur 64 bits), on veut donc garder uniquement les colonnes avec ce dtype

In [25]:
filosofi_ain.dtypes
Out[25]:
idcar_1km         object
i_est_1km          int32
lcog_geo          object
ind              float64
men              float64
men_pauv         float64
men_1ind         float64
men_5ind         float64
men_prop         float64
men_fmp          float64
ind_snv          float64
men_surf         float64
men_coll         float64
men_mais         float64
log_av45         float64
log_45_70        float64
log_70_90        float64
log_ap90         float64
log_inc          float64
log_soc          float64
ind_0_3          float64
ind_4_5          float64
ind_6_10         float64
ind_11_17        float64
ind_18_24        float64
ind_25_39        float64
ind_40_54        float64
ind_55_64        float64
ind_65_79        float64
ind_80p          float64
ind_inc          float64
geometry        geometry
nv_moy           float64
prop_maison      float64
prop_proprio     float64
prop_social      float64
prop>65          float64
prop<18          float64
dtype: object

C'est justement ce que permet la méthode select_dtypes

In [26]:
filosofi_ain_quanti = filosofi_ain.select_dtypes(include=["float64"])
filosofi_ain_quanti.columns
Out[26]:
Index(['ind', 'men', 'men_pauv', 'men_1ind', 'men_5ind', 'men_prop', 'men_fmp',
       'ind_snv', 'men_surf', 'men_coll', 'men_mais', 'log_av45', 'log_45_70',
       'log_70_90', 'log_ap90', 'log_inc', 'log_soc', 'ind_0_3', 'ind_4_5',
       'ind_6_10', 'ind_11_17', 'ind_18_24', 'ind_25_39', 'ind_40_54',
       'ind_55_64', 'ind_65_79', 'ind_80p', 'ind_inc', 'nv_moy', 'prop_maison',
       'prop_proprio', 'prop_social', 'prop>65', 'prop<18'],
      dtype='object')

Affichage de la matrice de corrélation : elle est symétrique et contient des 1 sur la diagonale. En analysant la première ligne, on constate que la plupart des variables sont fortement corrélés au nombre d'habitants du carreau (ind), à l'exception des variables qu'on a créé. Ça semble assez logique car plus il y a d'habitants, plus il y a de ménages, plus il y en a de chaque type..., mais ça ne joue pas forcément sur les proportions, par exemple la proportion de maison est généralement plus élevée là où la population est faible.

In [27]:
filosofi_ain_quanti.corr()
Out[27]:
ind men men_pauv men_1ind men_5ind men_prop men_fmp ind_snv men_surf men_coll ... ind_55_64 ind_65_79 ind_80p ind_inc nv_moy prop_maison prop_proprio prop_social prop>65 prop<18
ind 1.000000 0.990451 0.887223 0.916703 0.943352 0.948417 0.966701 0.969257 0.990942 0.887766 ... 0.980622 0.961918 0.910539 0.468507 -0.004276 -0.552616 -0.383944 0.470020 -0.132603 0.134803
men 0.990451 1.000000 0.907380 0.961585 0.910091 0.933488 0.982126 0.951766 0.988037 0.926927 ... 0.973590 0.966300 0.939830 0.466712 -0.020696 -0.561400 -0.388731 0.454913 -0.104592 0.105550
men_pauv 0.887223 0.907380 1.000000 0.922912 0.895461 0.723121 0.910540 0.795769 0.850175 0.959869 ... 0.847288 0.879490 0.868851 0.598014 -0.072341 -0.522802 -0.369858 0.432671 -0.058906 0.070628
men_1ind 0.916703 0.961585 0.922912 1.000000 0.817151 0.832082 0.957562 0.858142 0.919506 0.969573 ... 0.896437 0.914679 0.939206 0.469821 -0.054107 -0.548676 -0.378354 0.402860 -0.052636 0.054711
men_5ind 0.943352 0.910091 0.895461 0.817151 1.000000 0.835501 0.888067 0.884682 0.901657 0.834880 ... 0.907569 0.899745 0.825624 0.549424 -0.024418 -0.502109 -0.359414 0.473028 -0.143238 0.167734
men_prop 0.948417 0.933488 0.723121 0.832082 0.835501 1.000000 0.883705 0.959748 0.970805 0.747189 ... 0.957191 0.920710 0.856673 0.332050 0.039593 -0.489923 -0.308683 0.391420 -0.136546 0.134341
men_fmp 0.966701 0.982126 0.910540 0.957562 0.888067 0.883705 1.000000 0.917572 0.959515 0.934034 ... 0.941908 0.934116 0.924064 0.486154 -0.041004 -0.566097 -0.409838 0.471441 -0.100826 0.101458
ind_snv 0.969257 0.951766 0.795769 0.858142 0.884682 0.959748 0.917572 1.000000 0.974950 0.825272 ... 0.944360 0.901532 0.835427 0.387680 0.097981 -0.548580 -0.357745 0.428031 -0.155666 0.146025
men_surf 0.990942 0.988037 0.850175 0.919506 0.901657 0.970805 0.959515 0.974950 1.000000 0.866051 ... 0.981706 0.961710 0.916658 0.428867 0.016609 -0.545380 -0.373506 0.448899 -0.125351 0.125839
men_coll 0.887766 0.926927 0.959869 0.969573 0.834880 0.747189 0.934034 0.825272 0.866051 1.000000 ... 0.845350 0.866596 0.884898 0.517155 -0.039722 -0.553331 -0.368527 0.393943 -0.053451 0.050639
men_mais 0.798950 0.752987 0.474926 0.586835 0.700558 0.909984 0.698012 0.816530 0.831289 0.451043 ... 0.833229 0.778632 0.683579 0.203164 0.020432 -0.364938 -0.278326 0.391168 -0.155036 0.162245
log_av45 0.710899 0.761597 0.654290 0.809686 0.575260 0.698485 0.756458 0.655242 0.741804 0.722914 ... 0.706242 0.699358 0.747435 0.271885 -0.099896 -0.412363 -0.293275 0.251450 -0.046216 0.044735
log_45_70 0.761863 0.776182 0.873602 0.788798 0.810122 0.601257 0.783569 0.641721 0.715287 0.832506 ... 0.736847 0.789667 0.810927 0.590162 -0.080886 -0.401537 -0.278134 0.331912 -0.019780 0.039317
log_70_90 0.859317 0.858320 0.803155 0.806823 0.813032 0.812859 0.822046 0.827593 0.852507 0.784215 ... 0.871545 0.886776 0.808894 0.423703 -0.000872 -0.464323 -0.313097 0.426056 -0.061285 0.074798
log_ap90 0.888647 0.869238 0.672569 0.766839 0.773691 0.898142 0.850597 0.935609 0.899323 0.722334 ... 0.853939 0.788962 0.736255 0.279137 0.072848 -0.537803 -0.374305 0.447660 -0.182565 0.160721
log_inc 0.266602 0.267632 0.280179 0.259110 0.239824 0.234822 0.265144 0.276394 0.259625 0.280387 ... 0.251806 0.236081 0.204585 0.260945 0.001426 -0.161595 -0.104989 0.103883 -0.033792 0.033028
log_soc 0.837687 0.845719 0.947268 0.840050 0.875835 0.647266 0.866638 0.726223 0.786265 0.891232 ... 0.804834 0.844314 0.828070 0.589184 -0.098899 -0.494136 -0.381374 0.509629 -0.051394 0.069245
ind_0_3 0.964539 0.944554 0.856648 0.859395 0.923715 0.897289 0.926854 0.953617 0.943569 0.858297 ... 0.916316 0.881826 0.826275 0.459909 0.016428 -0.551566 -0.387120 0.471633 -0.169480 0.177794
ind_4_5 0.963581 0.936534 0.854698 0.840095 0.943173 0.892574 0.921632 0.944962 0.939884 0.837427 ... 0.920967 0.889336 0.823049 0.473481 0.014267 -0.537063 -0.383022 0.479185 -0.170605 0.186308
ind_6_10 0.975106 0.944236 0.855854 0.839893 0.962592 0.910125 0.923300 0.952231 0.952041 0.831382 ... 0.937088 0.908330 0.836999 0.468586 0.010863 -0.536390 -0.383351 0.483927 -0.172593 0.192571
ind_11_17 0.980444 0.953197 0.872933 0.855439 0.971184 0.912825 0.931186 0.945156 0.958942 0.842237 ... 0.952246 0.931520 0.860353 0.491281 -0.004443 -0.529315 -0.375955 0.480561 -0.157542 0.172980
ind_18_24 0.981927 0.980452 0.866314 0.922311 0.911047 0.936504 0.961503 0.948732 0.980559 0.880448 ... 0.966852 0.941327 0.901524 0.447665 -0.005006 -0.534696 -0.372770 0.447692 -0.135482 0.109227
ind_25_39 0.977577 0.971441 0.868857 0.907373 0.908368 0.915592 0.955247 0.965754 0.964660 0.894269 ... 0.934761 0.899771 0.854027 0.436203 0.005480 -0.572035 -0.398268 0.463298 -0.155915 0.146998
ind_40_54 0.993202 0.977105 0.858033 0.890610 0.934520 0.954426 0.949986 0.978798 0.986286 0.861802 ... 0.971400 0.940749 0.878050 0.441311 0.023315 -0.549201 -0.375247 0.462000 -0.157124 0.146603
ind_55_64 0.980622 0.973590 0.847288 0.896437 0.907569 0.957191 0.941908 0.944360 0.981706 0.845350 ... 1.000000 0.971079 0.912947 0.436584 -0.008768 -0.521886 -0.356569 0.450235 -0.116394 0.097326
ind_65_79 0.961918 0.966300 0.879490 0.914679 0.899745 0.920710 0.934116 0.901532 0.961710 0.866596 ... 0.971079 1.000000 0.950628 0.470970 -0.040683 -0.509874 -0.350417 0.439557 -0.041238 0.074369
ind_80p 0.910539 0.939830 0.868851 0.939206 0.825624 0.856673 0.924064 0.835427 0.916658 0.884898 ... 0.912947 0.950628 1.000000 0.471376 -0.076750 -0.501039 -0.350837 0.407748 -0.012511 0.048622
ind_inc 0.468507 0.466712 0.598014 0.469821 0.549424 0.332050 0.486154 0.387680 0.428867 0.517155 ... 0.436584 0.470970 0.471376 1.000000 -0.065075 -0.248670 -0.186739 0.245911 -0.030715 0.039289
nv_moy -0.004276 -0.020696 -0.072341 -0.054107 -0.024418 0.039593 -0.041004 0.097981 0.016609 -0.039722 ... -0.008768 -0.040683 -0.076750 -0.065075 1.000000 -0.037776 0.125018 -0.165002 -0.107370 -0.043340
prop_maison -0.552616 -0.561400 -0.522802 -0.548676 -0.502109 -0.489923 -0.566097 -0.548580 -0.545380 -0.553331 ... -0.521886 -0.509874 -0.501039 -0.248670 -0.037776 1.000000 0.667666 -0.568704 0.134127 -0.097968
prop_proprio -0.383944 -0.388731 -0.369858 -0.378354 -0.359414 -0.308683 -0.409838 -0.357745 -0.373506 -0.368527 ... -0.356569 -0.350417 -0.350837 -0.186739 0.125018 0.667666 1.000000 -0.634247 0.162832 -0.128143
prop_social 0.470020 0.454913 0.432671 0.402860 0.473028 0.391420 0.471441 0.428031 0.448899 0.393943 ... 0.450235 0.439557 0.407748 0.245911 -0.165002 -0.568704 -0.634247 1.000000 -0.154164 0.171881
prop>65 -0.132603 -0.104592 -0.058906 -0.052636 -0.143238 -0.136546 -0.100826 -0.155666 -0.125351 -0.053451 ... -0.116394 -0.041238 -0.012511 -0.030715 -0.107370 0.134127 0.162832 -0.154164 1.000000 -0.593162
prop<18 0.134803 0.105550 0.070628 0.054711 0.167734 0.134341 0.101458 0.146025 0.125839 0.050639 ... 0.097326 0.074369 0.048622 0.039289 -0.043340 -0.097968 -0.128143 0.171881 -0.593162 1.000000

34 rows × 34 columns

On peut visualiser ça plus en détail sous la forme de nuages de points

In [28]:
pd.plotting.scatter_matrix(filosofi_ain_quanti[["ind", "ind_snv", "nv_moy", "prop_maison", "prop_proprio", "prop_social", "prop>65", "prop<18"]], figsize=(15, 15))
Out[28]:
array([[<Axes: xlabel='ind', ylabel='ind'>,
        <Axes: xlabel='ind_snv', ylabel='ind'>,
        <Axes: xlabel='nv_moy', ylabel='ind'>,
        <Axes: xlabel='prop_maison', ylabel='ind'>,
        <Axes: xlabel='prop_proprio', ylabel='ind'>,
        <Axes: xlabel='prop_social', ylabel='ind'>,
        <Axes: xlabel='prop>65', ylabel='ind'>,
        <Axes: xlabel='prop<18', ylabel='ind'>],
       [<Axes: xlabel='ind', ylabel='ind_snv'>,
        <Axes: xlabel='ind_snv', ylabel='ind_snv'>,
        <Axes: xlabel='nv_moy', ylabel='ind_snv'>,
        <Axes: xlabel='prop_maison', ylabel='ind_snv'>,
        <Axes: xlabel='prop_proprio', ylabel='ind_snv'>,
        <Axes: xlabel='prop_social', ylabel='ind_snv'>,
        <Axes: xlabel='prop>65', ylabel='ind_snv'>,
        <Axes: xlabel='prop<18', ylabel='ind_snv'>],
       [<Axes: xlabel='ind', ylabel='nv_moy'>,
        <Axes: xlabel='ind_snv', ylabel='nv_moy'>,
        <Axes: xlabel='nv_moy', ylabel='nv_moy'>,
        <Axes: xlabel='prop_maison', ylabel='nv_moy'>,
        <Axes: xlabel='prop_proprio', ylabel='nv_moy'>,
        <Axes: xlabel='prop_social', ylabel='nv_moy'>,
        <Axes: xlabel='prop>65', ylabel='nv_moy'>,
        <Axes: xlabel='prop<18', ylabel='nv_moy'>],
       [<Axes: xlabel='ind', ylabel='prop_maison'>,
        <Axes: xlabel='ind_snv', ylabel='prop_maison'>,
        <Axes: xlabel='nv_moy', ylabel='prop_maison'>,
        <Axes: xlabel='prop_maison', ylabel='prop_maison'>,
        <Axes: xlabel='prop_proprio', ylabel='prop_maison'>,
        <Axes: xlabel='prop_social', ylabel='prop_maison'>,
        <Axes: xlabel='prop>65', ylabel='prop_maison'>,
        <Axes: xlabel='prop<18', ylabel='prop_maison'>],
       [<Axes: xlabel='ind', ylabel='prop_proprio'>,
        <Axes: xlabel='ind_snv', ylabel='prop_proprio'>,
        <Axes: xlabel='nv_moy', ylabel='prop_proprio'>,
        <Axes: xlabel='prop_maison', ylabel='prop_proprio'>,
        <Axes: xlabel='prop_proprio', ylabel='prop_proprio'>,
        <Axes: xlabel='prop_social', ylabel='prop_proprio'>,
        <Axes: xlabel='prop>65', ylabel='prop_proprio'>,
        <Axes: xlabel='prop<18', ylabel='prop_proprio'>],
       [<Axes: xlabel='ind', ylabel='prop_social'>,
        <Axes: xlabel='ind_snv', ylabel='prop_social'>,
        <Axes: xlabel='nv_moy', ylabel='prop_social'>,
        <Axes: xlabel='prop_maison', ylabel='prop_social'>,
        <Axes: xlabel='prop_proprio', ylabel='prop_social'>,
        <Axes: xlabel='prop_social', ylabel='prop_social'>,
        <Axes: xlabel='prop>65', ylabel='prop_social'>,
        <Axes: xlabel='prop<18', ylabel='prop_social'>],
       [<Axes: xlabel='ind', ylabel='prop>65'>,
        <Axes: xlabel='ind_snv', ylabel='prop>65'>,
        <Axes: xlabel='nv_moy', ylabel='prop>65'>,
        <Axes: xlabel='prop_maison', ylabel='prop>65'>,
        <Axes: xlabel='prop_proprio', ylabel='prop>65'>,
        <Axes: xlabel='prop_social', ylabel='prop>65'>,
        <Axes: xlabel='prop>65', ylabel='prop>65'>,
        <Axes: xlabel='prop<18', ylabel='prop>65'>],
       [<Axes: xlabel='ind', ylabel='prop<18'>,
        <Axes: xlabel='ind_snv', ylabel='prop<18'>,
        <Axes: xlabel='nv_moy', ylabel='prop<18'>,
        <Axes: xlabel='prop_maison', ylabel='prop<18'>,
        <Axes: xlabel='prop_proprio', ylabel='prop<18'>,
        <Axes: xlabel='prop_social', ylabel='prop<18'>,
        <Axes: xlabel='prop>65', ylabel='prop<18'>,
        <Axes: xlabel='prop<18', ylabel='prop<18'>]], dtype=object)
No description has been provided for this image

2. Analyse en composantes principales¶

2.1 Centrer-réduire les variables¶

In [29]:
filosofi_ain_quanti_cr = (filosofi_ain_quanti - filosofi_ain_quanti.mean())/filosofi_ain_quanti.std()
In [30]:
filosofi_ain_quanti_cr
Out[30]:
ind men men_pauv men_1ind men_5ind men_prop men_fmp ind_snv men_surf men_coll ... ind_55_64 ind_65_79 ind_80p ind_inc nv_moy prop_maison prop_proprio prop_social prop>65 prop<18
124712 -0.357926 -0.336429 -0.220494 -0.267384 -0.293021 -0.429969 -0.310497 -0.374021 -0.388033 -0.174056 ... -0.356480 -0.347701 -0.319313 -0.09069 -0.442484 0.186727 0.833416 -0.355730 -0.736494 -1.154160
125197 -0.151935 -0.091653 -0.059642 -0.021304 -0.212454 0.016760 -0.310497 -0.191333 -0.096802 -0.161528 ... 0.185373 -0.056959 -0.132050 -0.09069 -0.781996 0.374608 0.517243 -0.355730 0.195835 -1.616537
125198 -0.361862 -0.321419 -0.194233 -0.216801 -0.344291 -0.420310 -0.310497 -0.375825 -0.378066 -0.177188 ... -0.395347 -0.361453 -0.283644 -0.09069 -0.141333 0.627880 -0.466871 -0.355730 -0.487228 -1.557429
125687 -0.353990 -0.325460 -0.197515 -0.230472 -0.300345 -0.429969 -0.282428 -0.365807 -0.380770 -0.166226 ... -0.388488 -0.331985 -0.297020 -0.09069 0.115922 -0.519714 -0.723204 -0.218633 -0.023311 -0.413514
125688 -0.301508 -0.293131 -0.220494 -0.199028 -0.058644 -0.347867 -0.310497 -0.318274 -0.330840 -0.177188 ... -0.383915 -0.330021 -0.230140 -0.09069 -0.348543 0.627880 0.755690 -0.355730 -0.782194 1.520983
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
172513 -0.395975 -0.365871 -0.220494 -0.266017 -0.344291 -0.486715 -0.310497 -0.410641 -0.430499 -0.177188 ... -0.427355 -0.385026 -0.314854 -0.09069 -0.699283 0.627880 1.308916 -0.355730 2.141632 -0.168389
172917 -0.283139 -0.275235 -0.154840 -0.212699 -0.278372 -0.322512 -0.268393 -0.299409 -0.317322 -0.169358 ... -0.361052 -0.310376 -0.279185 -0.09069 -0.303018 0.251119 0.456117 -0.355730 -1.052107 0.810252
172918 -0.293636 -0.268307 -0.144992 -0.174420 -0.234427 -0.317683 -0.310497 -0.307375 -0.290512 -0.170924 ... -0.271887 -0.302518 -0.118674 -0.09069 -0.176598 0.347378 0.212930 -0.355730 0.189903 -0.064212
172919 -0.380231 -0.350862 -0.207363 -0.250978 -0.322318 -0.461361 -0.310497 -0.394547 -0.408738 -0.175622 ... -0.402206 -0.377168 -0.283644 -0.09069 -0.176596 0.223490 0.219229 -0.355730 0.070409 0.030045
173346 -0.393351 -0.362408 -0.213929 -0.264650 -0.344291 -0.481886 -0.305819 -0.408728 -0.426671 -0.176405 ... -0.422783 -0.379133 -0.314854 -0.09069 -1.216779 0.021295 0.001291 -0.355730 1.583995 -1.557429

4131 rows × 34 columns

2.2 Appliquer l'ACP¶

In [31]:
from sklearn.decomposition import PCA

pca = PCA()# On construit l'objet pca

filosofi_ain_quanti_pca = pca.fit_transform(filosofi_ain_quanti_cr)#fit = on calcule les vecteurs propres et valeurs propres, transform = on reprojette les données initiales
filosofi_ain_quanti_pca
Out[31]:
array([[-1.75971648e+00,  5.71806394e-01,  1.23990573e-01, ...,
         6.84442472e-15,  1.48840236e-14, -2.32539984e-14],
       [-8.34588374e-01,  1.18516092e+00,  5.12849672e-01, ...,
         5.48288160e-14,  5.09108199e-14, -9.98664117e-14],
       [-1.70876281e+00,  6.69546750e-01, -1.94710062e-01, ...,
         1.27090491e-14,  2.43870879e-14, -3.12556521e-14],
       ...,
       [-1.39132829e+00,  3.72750472e-01,  2.17647972e-02, ...,
         7.08582662e-16, -1.60176457e-14,  1.03279459e-14],
       [-1.76898039e+00,  2.80985225e-01, -1.89150446e-01, ...,
         6.73185164e-16,  2.18834882e-17, -3.48088784e-17],
       [-1.87020017e+00,  1.88294505e+00, -3.88960591e-01, ...,
         2.50459755e-15,  8.21053046e-15, -4.66783187e-15]])

On réinjecte les résultats dans un geodataframe pour pouvoir les visualiser géographiquement

In [32]:
filosofi_ain_quanti_pca_gdf = gpd.GeoDataFrame(filosofi_ain_quanti_pca, index=filosofi_ain.index, geometry=filosofi_ain.geometry)
In [37]:
filosofi_ain_quanti_pca_gdf.head()
Out[37]:
0 1 2 3 4 5 6 7 8 9 ... 25 26 27 28 29 30 31 32 33 geometry
124712 -1.759716 0.571806 0.123991 0.241993 -0.115435 0.016896 0.078169 -0.053354 -0.110777 -1.342939 ... 0.031372 0.016798 -0.017953 0.015741 -0.003491 -0.004413 6.844425e-15 1.488402e-14 -2.325400e-14 POLYGON ((904079.829 6504772.073, 903990.645 6...
125197 -0.834588 1.185161 0.512850 -0.698441 -0.493399 0.415175 0.109820 0.339757 0.020895 -1.079360 ... 0.041224 0.107347 0.005588 -0.016110 -0.026520 -0.020428 5.482882e-14 5.091082e-14 -9.986641e-14 POLYGON ((903990.645 6505768.296, 903901.456 6...
125198 -1.708763 0.669547 -0.194710 -0.343224 0.207162 -0.094914 0.123823 0.214447 0.045850 -1.492373 ... -0.001518 0.015702 0.005379 -0.012755 -0.010080 -0.005851 1.270905e-14 2.438709e-14 -3.125565e-14 POLYGON ((904984.561 6505860.102, 904895.373 6...
125687 -1.490418 0.049446 -0.775304 -0.446379 0.487046 -0.306426 0.285436 0.078897 -0.164723 -0.186456 ... -0.015288 0.016585 0.007728 -0.002067 -0.010131 0.000423 1.301792e-15 7.808021e-15 2.142850e-15 POLYGON ((903901.456 6506764.511, 903812.261 6...
125688 -1.467093 -0.734931 0.032521 1.541561 -0.853617 0.067329 0.187881 -0.300022 0.064276 0.386900 ... 0.041846 0.057327 0.031584 0.009786 -0.008080 -0.004203 1.720718e-14 2.271693e-15 -9.935790e-15 POLYGON ((904895.373 6506856.319, 904806.179 6...

5 rows × 35 columns

In [40]:
filosofi_ain_quanti_pca_gdf.plot(column=0, figsize=(20, 20), legend=True).set_title("Première composante principale")
Out[40]:
Text(0.5, 1.0, 'Première composante principale')
No description has been provided for this image
In [41]:
filosofi_ain_quanti_pca_gdf.plot(column=1, figsize=(20, 20), legend=True).set_title("Deuxième composante principale")
Out[41]:
Text(0.5, 1.0, 'Deuxième composante principale')
No description has been provided for this image

Taux de variance expliquée = Taux d'inertie expliquée = "proportion d'information sur chaque axe factoriel"

In [20]:
pca.explained_variance_ratio_
Out[20]:
array([6.92776595e-01, 5.63292209e-02, 4.95862490e-02, 3.84125003e-02,
       3.09796631e-02, 2.71637468e-02, 2.39723350e-02, 1.49761596e-02,
       1.15631761e-02, 1.14727982e-02, 1.03262536e-02, 9.15945068e-03,
       7.99008229e-03, 4.78365360e-03, 2.23055225e-03, 1.81218690e-03,
       1.27059663e-03, 8.80986232e-04, 8.00857763e-04, 7.15372475e-04,
       5.56141449e-04, 4.29755471e-04, 4.00057688e-04, 3.77360155e-04,
       3.18054818e-04, 2.24736692e-04, 1.98602625e-04, 1.42191890e-04,
       9.87084664e-05, 4.63860809e-05, 5.56839508e-06, 6.05813694e-17,
       5.53900437e-17, 0.00000000e+00])

Par exemple, ici le premier axe explique 69% de la variabilité des données, le second 5.6%.

In [21]:
plt.plot(pca.explained_variance_ratio_.cumsum())
Out[21]:
[<matplotlib.lines.Line2D at 0x1d2dd39ee90>]
No description has been provided for this image

Ce graphique permet de lire quel pourcentage d'information on garde si on conserve uniquement les n premières composantes (attention ici il commence à 0 au lieu de 1 !) Par exemple, si on conserve les 7 premières composantes (de 0 à 6), alors on explique plus de 90% de la variabilité. C'est généralement le seuil qu'on prend lorsqu'on veut réduire le nombre de dimensions avant une classification.

In [35]:
pca.explained_variance_ratio_.cumsum()[6]
Out[35]:
0.9192203099244365

On affiche le premier vecteur propre, c'est les coefficients de la combinaison linéaire des variables initiales qui permet de calculer pour chaque individu sa valeur sur la première composante principale.

In [22]:
pca.components_[0]
Out[22]:
array([ 0.20527683,  0.20474353,  0.18780273,  0.19285001,  0.19396549,
        0.19148082,  0.20126484,  0.19721231,  0.20310739,  0.18781264,
        0.15762352,  0.14807078,  0.16144494,  0.17755041,  0.18010094,
        0.05756627,  0.17792925,  0.19790426,  0.19761971,  0.19929527,
        0.200617  ,  0.20161906,  0.20092645,  0.20295477,  0.20069153,
        0.19836677,  0.19015704,  0.10308974, -0.00395434, -0.12119383,
       -0.08755164,  0.10365336, -0.02764079,  0.0284685 ])
In [23]:
filosofi_ain_quanti_cr.columns
Out[23]:
Index(['ind', 'men', 'men_pauv', 'men_1ind', 'men_5ind', 'men_prop', 'men_fmp',
       'ind_snv', 'men_surf', 'men_coll', 'men_mais', 'log_av45', 'log_45_70',
       'log_70_90', 'log_ap90', 'log_inc', 'log_soc', 'ind_0_3', 'ind_4_5',
       'ind_6_10', 'ind_11_17', 'ind_18_24', 'ind_25_39', 'ind_40_54',
       'ind_55_64', 'ind_65_79', 'ind_80p', 'ind_inc', 'nv_moy', 'prop_maison',
       'prop_proprio', 'prop_social', 'prop>65', 'prop<18'],
      dtype='object')

Cercle des corrélations¶

In [ ]:
from matplotlib.patches import Circle
plt.figure(figsize=(20, 20))
ax = plt.subplot()
ax.add_patch(plt.Circle((0, 0), radius = 1, color='black', fill=False))
for i in range(len(filosofi_ain_quanti_cr.columns)):
    plt.plot(
        [0,  pca.components_[0][i] * np.sqrt(pca.explained_variance_[0])],
        [0,  pca.components_[1][i] * np.sqrt(pca.explained_variance_[1])],
        color="black" ) 
    plt.text(
        pca.components_[0][i] * np.sqrt(pca.explained_variance_[0]),
        pca.components_[1][i] * np.sqrt(pca.explained_variance_[1]),
        filosofi_ain_quanti_cr.columns[i]
    )
No description has been provided for this image

Interprétation :

  • Signification des axes :
    1. Le premier axe factoriel est très corrélé avec "ind" et toutes les variables corrélées à "ind", il est moyennement anti-corrélé à "prop_maison", on peut l'interpréter comme signifiant globalement quelle est la population du carreau.
    2. Le second axe factoriel est corrélé avec "prop>56", et corrélé négativement avec prop<18. On peut l'interpréter comme informant sur l'age des habitants du carreau.
  • Variables plus ou moins bien expliquées, par exemple :
    • La variable "ind" est parfaitement expliquée puisqu'elle touche le bord du cercle.
    • La variable "nv_moy" est mal expliquée par ce plan factoriel parce qu'elle est proche du centre : les deux composantes principales sont insuffisantes pour capturer toutes les variations de cette variable
  • Liens entre les variables, par exemple :
    • La somme des niveau de vie "ind_snv" et le nombre de ménage propriétaire "men_prop" sont corrélés car leur angle est faible.
    • La proportion de ménages habitant dans un logement social est anti-corrélé à la proportion de ménages propriétaires.
    • Le nombre de logements datant d'avant 1945 et la proportion d'individus de moins de 18 ans sont non-corrélés.

On affiche le nuage de points des deux premières composantes

In [50]:
ax = filosofi_ain_quanti_pca_gdf.plot(kind="scatter",x=0, y=1, figsize=(12,5))
ax.axis("equal")
Out[50]:
(-5.951702552609344, 78.15709268214522, -7.374180569492368, 25.91272082962299)
No description has been provided for this image

On ne voit pas de groupes se former clairement, probablement que les méthodes de classification ne parviendront pas à séparer les individus de manière très pertinente.

3. Classification non supervisée¶

Classification non supervisée¶

In [51]:
from scipy.cluster.hierarchy import dendrogram, linkage
Z = linkage(filosofi_ain_quanti_pca_gdf.iloc[:,:6], 'ward')#Sur les 7 premières composantes de l'ACP
plt.figure(figsize=(25, 8))
ax=plt.subplot()
dn = dendrogram(Z)


plt.show()
No description has been provided for this image

On voit que deux groupes principaux semblent se former, mais ils ont une taille très différente

In [52]:
from sklearn.cluster import AgglomerativeClustering

cah = AgglomerativeClustering(n_clusters=2, linkage="ward")
cah_class_2 = cah.fit_predict(filosofi_ain_quanti_pca_gdf.iloc[:,:6]).astype(int)
cah_class_2 = gpd.GeoDataFrame(pd.Series(cah_class_2, index=filosofi_ain.index), geometry=filosofi_ain.geometry)
cah_class_2.plot(column=0, figsize=(12,5), legend=True)
Out[52]:
<Axes: >
No description has been provided for this image
In [53]:
filosofi_ain_quanti_pca_gdf.plot(kind="scatter", x=0, y=1, c=cah_class_2[0], figsize=(12,5), cmap="viridis")
Out[53]:
<Axes: xlabel='0', ylabel='1'>
No description has been provided for this image

On voit qu'il a regroupé dans la classe 1 (jaune) les carreaux "plutôt peuplés", et dans la classe 0 les carreaux avec un faible nombre d'habitants

In [54]:
from sklearn.cluster import AgglomerativeClustering

cah = AgglomerativeClustering(n_clusters=5, linkage="ward")
cah_class_5 = cah.fit_predict(filosofi_ain_quanti_pca_gdf.iloc[:,:6]).astype(int)
cah_class_5 = gpd.GeoDataFrame(pd.Series(cah_class_5, index=filosofi_ain.index), geometry=filosofi_ain.geometry)
cah_class_5.plot(column=0, figsize=(12,5), legend=True)
Out[54]:
<Axes: >
No description has been provided for this image
In [55]:
filosofi_ain_quanti_pca_gdf.plot(kind="scatter", x=0, y=1, c=cah_class_5[0], figsize=(12,5), cmap="viridis")
Out[55]:
<Axes: xlabel='0', ylabel='1'>
No description has been provided for this image
In [56]:
from sklearn.cluster import KMeans

k_means = KMeans(n_clusters=2)
k_means_class_2 = k_means.fit_predict(filosofi_ain_quanti_pca_gdf.iloc[:,:6]).astype(int)
k_means_class_2 = gpd.GeoDataFrame(pd.Series(k_means_class_2, index=filosofi_ain.index), geometry=filosofi_ain.geometry)
k_means_class_2.plot(column=0, figsize=(12,5), legend=True)
Out[56]:
<Axes: >
No description has been provided for this image
In [57]:
from sklearn.cluster import KMeans

k_means = KMeans(n_clusters=5)
k_means_class_5 = k_means.fit_predict(filosofi_ain_quanti_pca_gdf.iloc[:,:6]).astype(int)
k_means_class_5 = gpd.GeoDataFrame(pd.Series(k_means_class_5, index=filosofi_ain.index), geometry=filosofi_ain.geometry)
k_means_class_5.plot(column=0, figsize=(12,5), legend=True)
Out[57]:
<Axes: >
No description has been provided for this image
In [59]:
inertie_totale = ((filosofi_ain_quanti_pca_gdf.iloc[:,:6] - filosofi_ain_quanti_pca_gdf.iloc[:,:6].mean(axis=0))**2).sum().sum()
inertie_totale
Out[59]:
125710.72063260536
In [60]:
for i, clustering in enumerate([cah_class_2, k_means_class_2, cah_class_5, k_means_class_5]):
    inertie_inter = 0
    for c in range(max(clustering[0])+1):
        centre_c = filosofi_ain_quanti_pca_gdf.iloc[:,:6].loc[clustering[0]==c].mean()
        inertie_inter += ((filosofi_ain_quanti_pca_gdf.iloc[:,:6].mean(axis=0) - centre_c)**2).sum().sum()
    Q = inertie_inter / inertie_totale
    print("La qualité du clustering", i, "est", Q)
La qualité du clustering 0 est 0.004924511081251997
La qualité du clustering 1 est 0.004497746175006521
La qualité du clustering 2 est 0.03369150016511253
La qualité du clustering 3 est 0.03912168525170991

Classification supervisée¶

In [62]:
ocs_ge = gpd.read_file(
    os.path.join(
        "..",
        "TP_2_analyse_bivariee",
        "OCS-GE_2-0__SHP_LAMB93_D001_2021-01-01",
        "OCS-GE","1_DONNEES_LIVRAISON_2024-07-00057","OCSGE_2-0_SHP_LAMB93_D01-2021",
        "OCCUPATION_SOL.shp")
)

On va réaliser l'intersection entre les deux couches

In [63]:
intersection = ocs_ge.overlay(filosofi_ain,
                              how="intersection",
                              keep_geom_type=True
                              )
In [84]:
intersection["intersected_area"] = intersection.area
grouped = intersection.groupby(by=["idcar_1km", "CODE_US"])
In [85]:
area_per_US = grouped.aggregate({"intersected_area": "sum"})
In [86]:
area_per_US
Out[86]:
intersected_area
idcar_1km CODE_US
CRS3035RES1000mN2510000E3979000 US1.1 199509.974876
US1.2 247506.319747
US3 148022.904047
US4.1.1 8643.642790
US5 26332.931045
... ... ...
CRS3035RES1000mN2613000E3932000 US1.2 72979.564333
US3 6874.732000
US4.1.1 5182.361158
US5 2594.768041
US6.3 94273.165015

25388 rows × 1 columns

In [87]:
def main_us(groupe):
   #On définit une fonction d'aggrégation qu'on va appliquer à chaque groupe de carreaux, et qui va retourner l'usage avec la plus grande surface
   return groupe["CODE_US"].iloc[np.argmax(groupe["intersected_area"])]
In [88]:
usage_majoritaire = area_per_US.reset_index().groupby("idcar_1km").apply(main_us, include_groups=False)
In [109]:
filosofi_ain_quanti_pca_gdf = filosofi_ain_quanti_pca_gdf.set_index(filosofi_ain["idcar_1km"])
filosofi_ain = filosofi_ain.set_index("idcar_1km")
filosofi_ain["Usage majoritaire"] = usage_majoritaire
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File c:\Users\mcubaud\AppData\Local\anaconda3\envs\geo2\lib\site-packages\pandas\core\indexes\base.py:3812, in Index.get_loc(self, key)
   3811 try:
-> 3812     return self._engine.get_loc(casted_key)
   3813 except KeyError as err:

File pandas/_libs/index.pyx:167, in pandas._libs.index.IndexEngine.get_loc()

File pandas/_libs/index.pyx:196, in pandas._libs.index.IndexEngine.get_loc()

File pandas/_libs/hashtable_class_helper.pxi:7088, in pandas._libs.hashtable.PyObjectHashTable.get_item()

File pandas/_libs/hashtable_class_helper.pxi:7096, in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'idcar_1km'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
Cell In[109], line 1
----> 1 filosofi_ain_quanti_pca_gdf = filosofi_ain_quanti_pca_gdf.set_index(filosofi_ain["idcar_1km"])
      2 filosofi_ain = filosofi_ain.set_index("idcar_1km")
      3 filosofi_ain["Usage majoritaire"] = usage_majoritaire

File c:\Users\mcubaud\AppData\Local\anaconda3\envs\geo2\lib\site-packages\geopandas\geodataframe.py:1891, in GeoDataFrame.__getitem__(self, key)
   1885 def __getitem__(self, key):
   1886     """
   1887     If the result is a column containing only 'geometry', return a
   1888     GeoSeries. If it's a DataFrame with any columns of GeometryDtype,
   1889     return a GeoDataFrame.
   1890     """
-> 1891     result = super().__getitem__(key)
   1892     # Custom logic to avoid waiting for pandas GH51895
   1893     # result is not geometry dtype for multi-indexes
   1894     if (
   1895         pd.api.types.is_scalar(key)
   1896         and key == ""
   (...)
   1899         and not is_geometry_type(result)
   1900     ):

File c:\Users\mcubaud\AppData\Local\anaconda3\envs\geo2\lib\site-packages\pandas\core\frame.py:4113, in DataFrame.__getitem__(self, key)
   4111 if self.columns.nlevels > 1:
   4112     return self._getitem_multilevel(key)
-> 4113 indexer = self.columns.get_loc(key)
   4114 if is_integer(indexer):
   4115     indexer = [indexer]

File c:\Users\mcubaud\AppData\Local\anaconda3\envs\geo2\lib\site-packages\pandas\core\indexes\base.py:3819, in Index.get_loc(self, key)
   3814     if isinstance(casted_key, slice) or (
   3815         isinstance(casted_key, abc.Iterable)
   3816         and any(isinstance(x, slice) for x in casted_key)
   3817     ):
   3818         raise InvalidIndexError(key)
-> 3819     raise KeyError(key) from err
   3820 except TypeError:
   3821     # If we have a listlike key, _check_indexing_error will raise
   3822     #  InvalidIndexError. Otherwise we fall through and re-raise
   3823     #  the TypeError.
   3824     self._check_indexing_error(key)

KeyError: 'idcar_1km'
In [110]:
filosofi_ain.plot(column="Usage majoritaire", legend=True).set_title("Usage majoritaire")
Out[110]:
Text(0.5, 1.0, 'Usage majoritaire')
No description has been provided for this image

Quel est le nombre de pays par régime politique ?

In [111]:
filosofi_ain["Usage majoritaire"].value_counts()
Out[111]:
Usage majoritaire
US1.1      2855
US1.2      1048
US5         136
US6.3        40
US3          36
US2          14
US4.1.4       2
Name: count, dtype: int64
In [112]:
for variable in ["ind", "nv_moy", 'prop_maison', 'prop_proprio',
       'prop_social', 'prop>65', 'prop<18']:
    filosofi_ain.boxplot(column=variable, by="Usage majoritaire", figsize=(12,6))
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
In [116]:
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import train_test_split
clf = RandomForestClassifier()#construct the classifier
X_train, X_test, y_train, y_test = train_test_split(
	filosofi_ain_quanti_pca_gdf.iloc[:,:6][~filosofi_ain["Usage majoritaire"].isna()],#On ne prend pas les carreaux pour lesquels "Usage majoritaire" vaut NaN, on pourra justement utiliser le modèle pour essayer de prédire pour ces carreaux
  	filosofi_ain[~filosofi_ain["Usage majoritaire"].isna()]["Usage majoritaire"],
	train_size=0.7)
clf.fit(X_train, y_train)#train the classifier
y_pred = clf.predict(X_test)
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
[[790  50   0   6   7   0]
 [253  66   0   1   2   0]
 [  3   0   0   0   0   0]
 [  5   3   0   0   2   0]
 [  7   0   0   1  30   0]
 [ 12   2   0   0   0   0]]
              precision    recall  f1-score   support

       US1.1       0.74      0.93      0.82       853
       US1.2       0.55      0.20      0.30       322
         US2       0.00      0.00      0.00         3
         US3       0.00      0.00      0.00        10
         US5       0.73      0.79      0.76        38
       US6.3       0.00      0.00      0.00        14

    accuracy                           0.71      1240
   macro avg       0.34      0.32      0.31      1240
weighted avg       0.67      0.71      0.67      1240

c:\Users\mcubaud\AppData\Local\anaconda3\envs\geo2\lib\site-packages\sklearn\metrics\_classification.py:1731: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.
  _warn_prf(average, modifier, f"{metric.capitalize()} is", result.shape[0])
c:\Users\mcubaud\AppData\Local\anaconda3\envs\geo2\lib\site-packages\sklearn\metrics\_classification.py:1731: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.
  _warn_prf(average, modifier, f"{metric.capitalize()} is", result.shape[0])
c:\Users\mcubaud\AppData\Local\anaconda3\envs\geo2\lib\site-packages\sklearn\metrics\_classification.py:1731: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.
  _warn_prf(average, modifier, f"{metric.capitalize()} is", result.shape[0])

Si on regarde l'overall accuracy, le modèle n'est pas trop mauvais car 71% de ses prédictions sont justes. Cependant, en regardant dans le détail, on peut voir que les classes US2, US3 et US6.3 ne sont pas prédites du tout, et que la classe US1.2 a un faible rappel : le modèle ne détecte que 20% des US1.2.

La première cause des mauvaises performances pour ces classes est le nombre assez faible de données d'entraînement ce qui rend l'apprentissage difficile. L'autre cause la plus importante est que les variables qu'on a ne sont pas suffisantes pour bien prédire ces classes.

In [117]:
results = gpd.GeoDataFrame({"y_pred":y_pred,"y_true":y_test},index=X_test.index, geometry=filosofi_ain.loc[X_test.index, "geometry"])
results
Out[117]:
y_pred y_true geometry
idcar_1km
CRS3035RES1000mN2569000E3947000 US5 US1.2 POLYGON ((866998.607 6560590.693, 866909.008 6...
CRS3035RES1000mN2542000E3960000 US1.1 US1.2 POLYGON ((882337.473 6534900.296, 882248.071 6...
CRS3035RES1000mN2582000E3951000 US1.1 US1.1 POLYGON ((869809.75 6573904.535, 869720.079 65...
CRS3035RES1000mN2597000E3944000 US1.1 US1.1 POLYGON ((861504.951 6588193.494, 861415.163 6...
CRS3035RES1000mN2564000E3945000 US1.2 US1.1 POLYGON ((865458.377 6555427.177, 865368.805 6...
... ... ... ...
CRS3035RES1000mN2545000E3942000 US1.1 US1.1 POLYGON ((864176.962 6536229.093, 864087.504 6...
CRS3035RES1000mN2585000E3931000 US1.1 US1.1 POLYGON ((849658.185 6575044.228, 849568.44 65...
CRS3035RES1000mN2543000E3981000 US1.2 US1.2 POLYGON ((903121.754 6537827.56, 903032.389 65...
CRS3035RES1000mN2592000E3954000 US1.1 US1.1 POLYGON ((871895.145 6584138.331, 871805.419 6...
CRS3035RES1000mN2565000E3997000 US3 US5 POLYGON ((917058.611 6561207.553, 916969.161 6...

1240 rows × 3 columns

In [118]:
results.plot(column="y_pred", figsize=(12,6), legend=True).set_title("Usage prédit")
results.plot(column="y_true", figsize=(12,6), legend=True).set_title("Usage réel")
Out[118]:
Text(0.5, 1.0, 'Usage réel')
No description has been provided for this image
No description has been provided for this image

BONUS: probabilités¶

In [119]:
y_proba = clf.predict_proba(X_test)
y_proba
Out[119]:
array([[0.4 , 0.09, 0.  , ..., 0.  , 0.46, 0.02],
       [0.73, 0.15, 0.06, ..., 0.  , 0.01, 0.01],
       [0.47, 0.32, 0.01, ..., 0.  , 0.04, 0.  ],
       ...,
       [0.15, 0.85, 0.  , ..., 0.  , 0.  , 0.  ],
       [0.69, 0.31, 0.  , ..., 0.  , 0.  , 0.  ],
       [0.02, 0.04, 0.01, ..., 0.  , 0.37, 0.03]])

Chaque ligne correspond aux probabilités données par le modèle pour les 7 classes.

In [128]:
noms_colonnes = "proba_" + np.unique(y_train)
noms_colonnes
Out[128]:
array(['proba_US1.1', 'proba_US1.2', 'proba_US2', 'proba_US3',
       'proba_US4.1.4', 'proba_US5', 'proba_US6.3'], dtype=object)
In [132]:
results[noms_colonnes] = y_proba
results
Out[132]:
y_pred y_true geometry proba_US1.1 proba_US1.2 proba_US2 proba_US3 proba_US4.1.4 proba_US5 proba_US6.3
idcar_1km
CRS3035RES1000mN2569000E3947000 US5 US1.2 POLYGON ((866998.607 6560590.693, 866909.008 6... 0.40 0.09 0.00 0.03 0.0 0.46 0.02
CRS3035RES1000mN2542000E3960000 US1.1 US1.2 POLYGON ((882337.473 6534900.296, 882248.071 6... 0.73 0.15 0.06 0.04 0.0 0.01 0.01
CRS3035RES1000mN2582000E3951000 US1.1 US1.1 POLYGON ((869809.75 6573904.535, 869720.079 65... 0.47 0.32 0.01 0.16 0.0 0.04 0.00
CRS3035RES1000mN2597000E3944000 US1.1 US1.1 POLYGON ((861504.951 6588193.494, 861415.163 6... 0.74 0.24 0.01 0.00 0.0 0.00 0.01
CRS3035RES1000mN2564000E3945000 US1.2 US1.1 POLYGON ((865458.377 6555427.177, 865368.805 6... 0.48 0.50 0.00 0.00 0.0 0.00 0.02
... ... ... ... ... ... ... ... ... ... ...
CRS3035RES1000mN2545000E3942000 US1.1 US1.1 POLYGON ((864176.962 6536229.093, 864087.504 6... 0.85 0.14 0.00 0.00 0.0 0.00 0.01
CRS3035RES1000mN2585000E3931000 US1.1 US1.1 POLYGON ((849658.185 6575044.228, 849568.44 65... 0.82 0.18 0.00 0.00 0.0 0.00 0.00
CRS3035RES1000mN2543000E3981000 US1.2 US1.2 POLYGON ((903121.754 6537827.56, 903032.389 65... 0.15 0.85 0.00 0.00 0.0 0.00 0.00
CRS3035RES1000mN2592000E3954000 US1.1 US1.1 POLYGON ((871895.145 6584138.331, 871805.419 6... 0.69 0.31 0.00 0.00 0.0 0.00 0.00
CRS3035RES1000mN2565000E3997000 US3 US5 POLYGON ((917058.611 6561207.553, 916969.161 6... 0.02 0.04 0.01 0.53 0.0 0.37 0.03

1240 rows × 10 columns

In [133]:
for proba in noms_colonnes:
    results.plot(column=proba, figsize=(12,6), legend=True).set_title(proba)
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
In [ ]: