```python import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt import seaborn as sns import scipy from scipy.stats import pearsonr, ttest_ind, chisquare, f_oneway, chi2_contingency print("pandas version:", pd.__version__) print("matplotlib version:", matplotlib.__version__) print("seaborn version:", sns.__version__) print("scipy version", scipy.__version__) ``` pandas version: 2.2.2 matplotlib version: 3.8.4 seaborn version: 0.13.2 scipy version 1.13.1 ### Data ```python df = sns.load_dataset("mpg") df.dropna(inplace=True) df ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>mpg</th> <th>cylinders</th> <th>displacement</th> <th>horsepower</th> <th>weight</th> <th>acceleration</th> <th>model_year</th> <th>origin</th> <th>name</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>18.0</td> <td>8</td> <td>307.0</td> <td>130.0</td> <td>3504</td> <td>12.0</td> <td>70</td> <td>usa</td> <td>chevrolet chevelle malibu</td> </tr> <tr> <th>1</th> <td>15.0</td> <td>8</td> <td>350.0</td> <td>165.0</td> <td>3693</td> <td>11.5</td> <td>70</td> <td>usa</td> <td>buick skylark 320</td> </tr> <tr> <th>2</th> <td>18.0</td> <td>8</td> <td>318.0</td> <td>150.0</td> <td>3436</td> <td>11.0</td> <td>70</td> <td>usa</td> <td>plymouth satellite</td> </tr> <tr> <th>3</th> <td>16.0</td> <td>8</td> <td>304.0</td> <td>150.0</td> <td>3433</td> <td>12.0</td> <td>70</td> <td>usa</td> <td>amc rebel sst</td> </tr> <tr> <th>4</th> <td>17.0</td> <td>8</td> <td>302.0</td> <td>140.0</td> <td>3449</td> <td>10.5</td> <td>70</td> <td>usa</td> <td>ford torino</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>393</th> <td>27.0</td> <td>4</td> <td>140.0</td> <td>86.0</td> <td>2790</td> <td>15.6</td> <td>82</td> <td>usa</td> <td>ford mustang gl</td> </tr> <tr> <th>394</th> <td>44.0</td> <td>4</td> <td>97.0</td> <td>52.0</td> <td>2130</td> <td>24.6</td> <td>82</td> <td>europe</td> <td>vw pickup</td> </tr> <tr> <th>395</th> <td>32.0</td> <td>4</td> <td>135.0</td> <td>84.0</td> <td>2295</td> <td>11.6</td> <td>82</td> <td>usa</td> <td>dodge rampage</td> </tr> <tr> <th>396</th> <td>28.0</td> <td>4</td> <td>120.0</td> <td>79.0</td> <td>2625</td> <td>18.6</td> <td>82</td> <td>usa</td> <td>ford ranger</td> </tr> <tr> <th>397</th> <td>31.0</td> <td>4</td> <td>119.0</td> <td>82.0</td> <td>2720</td> <td>19.4</td> <td>82</td> <td>usa</td> <td>chevy s-10</td> </tr> </tbody> </table> <p>392 rows × 9 columns</p> </div> 1. Analysez l'évolution de la consommation des voitures (mpg) par rapport à la puissance du moteur (horsepower). - Refaites le graphique correspondant - Quelle est la corrélation de Pearson entre ces deux variables ? - Quelle serait la probabilité d'obtenir une telle corrélation ou plus extrême, si en réalité les deux variables étaient totalement décorrélées ? 2. Peut-on affirmer avec un risque d'erreur de 2% que les voitures du Japon, d'Europe, et des États-Unis ont vu leur autonomie moyenne (mpg) augmenter entre la premiere moitiée des années 70s, et la seconde moitiée des années 70s ? 2. Un constructeur automobile américain affirme que les voitures américaines à 4 cylindres ont en moyenne la même accélération que les voitures américaines à 6 cylindres. Testez cette affirmation et concluez avec un niveau de confiance de 98 % (alpha = 0,02). 4. Un collectionneur de voitures vous affirme que parmi les voitures Ford des années 1970-1982, il y avait : - 25 % de 4 cylindres - 25 % de 6 cylindres - 50 % de 8 cylindres Testez son affirmation et concluez avec un niveau de confiance de 95 %. 5. Les voitures à 4 cylindres ont en moyenne la même consommation d'essence au Japon, en Europe et aux États-Unis, dans les années 1970-1982. Testez cette affirmation et concluez avec un niveau de confiance de 98 % (alpha = 0,02). 6. Les voitures européennes et japonaises ont en moyenne le même nombre de chevaux. Testez cette affirmation et concluez avec un niveau de confiance de 98 % (alpha = 0,02). 7. Un spécialiste vous dit que les constructeurs Ford et Dodge produisaient dans les années 70-82 des voitures avec un nombre de cylindres équivalent. Testez cette affirmation et concluez avec un niveau de confiance de 98 % (alpha = 0,02). Pour cette question aidez-vous du code suivant: `filtered_df = df[df['name'].str.contains('ford|dodge', case=False, na=False)]` `filtered_df['brand'] = filtered_df['name'].apply(lambda x: 'ford' if 'ford' in x else 'dodge')` ### 1. Consommation des voitures par rapport à la puissance du moteur ```python sns.scatterplot(data= df, x="mpg", y="horsepower") ``` <Axes: xlabel='mpg', ylabel='horsepower'> ![png](exo_hypothèses_2_MPG_5_1.png) ```python test_pearson = pearsonr(x=df["mpg"], y=df["horsepower"]) test_pearson ``` PearsonRResult(statistic=-0.7784267838977761, pvalue=7.031989029403434e-81) ```python print(f"La probabilité d'obtenir une telle corrélation ou plus extrême, si en réalité les deux variables étaient totalement décorrélées est de {test_pearson.pvalue:.2e}") ``` La probabilité d'obtenir une telle corrélation ou plus extrême, si en réalité les deux variables étaient totalement décorrélées est de 7.03e-81 ### 2. Est-ce que les voitures du Japon, d'Europe, et des États-Unis ont vu leur autonomie moyenne (mpg) augmenter entre la premiere moitiée des années 70s, et la seconde moitiée des années 70s ? ```python sns.boxplot(df, x="model_year", y="mpg") ``` <Axes: xlabel='model_year', ylabel='mpg'> ![png](exo_hypothèses_2_MPG_9_1.png) ```python df_temp = df.copy() df_temp["half"] = df["model_year"].apply(lambda x: x < 75).replace({True: "first", False: "second"}) df_temp = df_temp.query("`model_year` <= 80") ``` ```python sns.boxplot(df_temp, x="half", y='mpg', hue="half") ``` <Axes: xlabel='half', ylabel='mpg'> ![png](exo_hypothèses_2_MPG_11_1.png) Conditions pour un TTest ind : 1. Données normales ou plus de 30 points 2. Observations indépendantes 3. Variances similaires entre les 2 groupes ```python df_temp.groupby("half").size() ``` half first 150 second 184 dtype: int64 ```python df_temp.groupby("half")["mpg"].var() ``` half first 35.998255 second 57.184598 Name: mpg, dtype: float64 Variance un peu différente --> test de Student ou de Welch ? ```python first_half = df_temp.query("`half` == 'first'") second_half = df_temp.query("`half` == 'second'") ``` Test de Student ```python ttest_ind(first_half["mpg"], second_half["mpg"], equal_var=True) ``` TtestResult(statistic=-6.912631779958917, pvalue=2.4451466260288248e-11, df=332.0) Test de Welch ```python ttest_ind(first_half["mpg"], second_half["mpg"], equal_var=False) ``` TtestResult(statistic=-7.075000003257606, pvalue=8.923594936299578e-12, df=331.77103612309065) Conclusion : la p-value est inférieure à alpha. On rejette H0 ! --> les 2 moyennes ne sont pas les mêmes #### Mon code d'origine ```python df_70_74 = df.query("`model_year` >= 70 & `model_year` <= 74") df_75_79 = df.query("`model_year` >= 75 & `model_year` <= 80") ``` ```python df_70_74["mpg"].describe() ``` count 150.000000 mean 19.220000 std 5.999855 min 9.000000 25% 14.000000 50% 18.000000 75% 24.000000 max 35.000000 Name: mpg, dtype: float64 ```python df_75_79["mpg"].describe() ``` count 157.000000 mean 22.865605 std 6.442882 min 13.000000 25% 18.000000 50% 21.500000 75% 27.400000 max 43.100000 Name: mpg, dtype: float64 ```python ttest_ind(df_70_74["mpg"], df_75_79["mpg"]) ``` TtestResult(statistic=-5.124844610385172, pvalue=5.295104451324324e-07, df=305.0) ```python print("H0 : \"Les voitures du Japon, d'Europe, et des États-Unis n'ont pas vu leur autonomie moyenne (mpg) augmenter entre la premiere moitiée des années 70s, et la seconde moitiée des années 70s\"") print() alpha = 0.02 p_value = ttest_ind(df_70_74["mpg"], df_75_79["mpg"]).pvalue if p_value < alpha: print("Nous avons suffisamment d'évidences pour rejeter H0") else: print("Nous n'avons pas suffisamment d'évidences pour rejeter H0") ``` H0 : "Les voitures du Japon, d'Europe, et des États-Unis n'ont pas vu leur autonomie moyenne (mpg) augmenter entre la premiere moitiée des années 70s, et la seconde moitiée des années 70s" Nous avons suffisamment d'évidences pour rejeter H0 ### 3. Comparaison des accélérations entre les voitures américaines à 4 cylindres et à 6 cylindres ```python df.query("`origin` == 'usa' & `model_year` <= 80").groupby("cylinders")["acceleration"].mean() ``` cylinders 4 16.526667 6 16.543939 8 12.896078 Name: acceleration, dtype: float64 ```python df.query("`origin` == 'usa' & `model_year` <= 80").groupby("cylinders")["acceleration"].size() ``` cylinders 4 45 6 66 8 102 Name: acceleration, dtype: int64 --> + de 30 points ```python df.query("`origin` == 'usa' & `model_year` <= 80").groupby("cylinders")["acceleration"].var() ``` cylinders 4 4.725182 6 3.734809 8 4.633252 Name: acceleration, dtype: float64 --> quasi la même variance ```python 'H0: les voitures américaines 4 cylindres ont en moyenne la même accélération que els voitures américaines 6 cylindres' ``` 'H0: les voitures américaines 4 cylindres ont en moyenne la même accélération que els voitures américaines 6 cylindres' ```python df_usa_4cyl = df.query("`origin` == 'usa' & `cylinders` == 4 & `model_year` <=80") df_usa_6cyl = df.query("`origin` == 'usa' & `cylinders` == 6 & `model_year` <=80") ``` ```python ttest_ind(df_usa_4cyl["acceleration"], df_usa_6cyl["acceleration"]) ``` TtestResult(statistic=-0.04394012601152416, pvalue=0.9650325251684159, df=109.0) ```python print("H0 : \"Les voitures américaines à 4 cylindres ont en moyenne la même accélération que les voitures américaines à 6 cylindres\"") print() alpha = 0.02 p_value = ttest_ind(df_usa_4cyl["acceleration"], df_usa_6cyl["acceleration"]).pvalue if p_value < alpha: print("Nous avons suffisamment d'évidences pour rejeter H0") else: print("Nous n'avons pas suffisamment d'évidences pour rejeter H0") ``` H0 : "Les voitures américaines à 4 cylindres ont en moyenne la même accélération que les voitures américaines à 6 cylindres" Nous n'avons pas suffisamment d'évidences pour rejeter H0 ### 4. Comparaison des cylindres des voitures Ford Un collectionneur de voitures vous affirme que parmi les voitures Ford des années 1970-1982, il y avait : - 25 % de 4 cylindres - 25 % de 6 cylindres - 50 % de 8 cylindres Testez son affirmation et concluez avec un niveau de confiance de 95 %. ```python df_ford = df[df['name'].str.contains('ford')] ``` ```python df_ford["cylinders"].value_counts(normalize=True).round(2) ``` cylinders 8 0.42 4 0.33 6 0.25 Name: proportion, dtype: float64 ```python observed_frequencies = df_ford["cylinders"].value_counts(normalize=False, sort=False).round(2).sort_index() observed_frequencies ``` cylinders 4 16 6 12 8 20 Name: count, dtype: int64 ```python expected_frequencies = np.array([0.25, 0.25, 0.5]) ``` ```python # Probabilités en effectifs expected_frequencies = expected_frequencies * len(df_ford) expected_frequencies ``` array([12., 12., 24.]) ```python chisquare(f_obs=observed_frequencies, f_exp=expected_frequencies) ``` Power_divergenceResult(statistic=2.0, pvalue=0.36787944117144245) ```python print("H0 : parmi les voitures Ford des années 1970-1982, il y avait : 25 % de 4 cylindres, 25 % de 6 cylindres et 50 % de 8 cylindres") print() p_value = chisquare(f_obs=observed_frequencies, f_exp=expected_frequencies).pvalue alpha = 0.05 if p_value < alpha: print("Nous avons suffisamment d'évidences pour rejeter H0") else: print("Nous n'avons pas suffisamment d'évidences pour rejeter H0") ``` H0 : parmi les voitures Ford des années 1970-1982, il y avait : 25 % de 4 cylindres, 25 % de 6 cylindres et 50 % de 8 cylindres Nous n'avons pas suffisamment d'évidences pour rejeter H0 ### 5. Consommation des voitures 4 cylindres entre les différents pays ```python df_4cyl = df.query("`cylinders` == 4") df_4cyl.groupby("origin")["mpg"].mean() ``` origin europe 28.106557 japan 31.595652 usa 28.013043 Name: mpg, dtype: float64 --> moyennes assez similaires ```python df_4cyl.groupby("origin")["mpg"].var() ``` origin europe 39.577623 japan 29.547775 usa 20.853798 Name: mpg, dtype: float64 --> variances assez importante --> test de Anova #### Test de ANOVA H0 : Les voitures à 4 cylindres ont en moyenne la même consommation d'essence au Japon, en Europe et aux États-Unis, dans les années 1970-1982 ```python df_4cyl.groupby("origin")["mpg"].apply(list) ``` origin europe [26.0, 25.0, 24.0, 25.0, 26.0, 28.0, 30.0, 30.... japan [24.0, 27.0, 27.0, 25.0, 31.0, 35.0, 24.0, 28.... usa [28.0, 22.0, 23.0, 26.0, 25.0, 20.0, 21.0, 22.... Name: mpg, dtype: object ```python f_oneway(*df_4cyl.groupby("origin")["mpg"].apply(list)) ``` F_onewayResult(statistic=9.538999089626692, pvalue=0.00011134953247209682) ```python print("H0 : Les voitures à 4 cylindres ont en moyenne la même consommation d'essence au Japon, en Europe et aux États-Unis, dans les années 1970-1982") print() p_value = f_oneway(*df_4cyl.groupby("origin")["mpg"].apply(list)).pvalue alpha = 0.02 if p_value < alpha: print("Nous avons suffisamment d'évidences pour rejeter H0") else: print("Nous n'avons pas suffisamment d'évidences pour rejeter H0") ``` H0 : Les voitures à 4 cylindres ont en moyenne la même consommation d'essence au Japon, en Europe et aux États-Unis, dans les années 1970-1982 Nous avons suffisamment d'évidences pour rejeter H0 ### 6. Comparaison de la puissance des voitures européennes et japonaises ```python df.groupby("origin")["horsepower"].describe() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>count</th> <th>mean</th> <th>std</th> <th>min</th> <th>25%</th> <th>50%</th> <th>75%</th> <th>max</th> </tr> <tr> <th>origin</th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th>europe</th> <td>68.0</td> <td>80.558824</td> <td>20.157871</td> <td>46.0</td> <td>69.75</td> <td>76.5</td> <td>90.0</td> <td>133.0</td> </tr> <tr> <th>japan</th> <td>79.0</td> <td>79.835443</td> <td>17.819199</td> <td>52.0</td> <td>67.00</td> <td>75.0</td> <td>95.0</td> <td>132.0</td> </tr> <tr> <th>usa</th> <td>245.0</td> <td>119.048980</td> <td>39.897790</td> <td>52.0</td> <td>88.00</td> <td>105.0</td> <td>150.0</td> <td>230.0</td> </tr> </tbody> </table> </div> > 30 échantilons, variables indépendantes (pas les mêms voitures) et variance similaire --> test de Student ok H0 : Les voitures européennes et japonaises ont en moyenne le même nombre de chevaux ```python df_eur = df.query("`origin` == 'europe'") df_jap = df.query("`origin` == 'japan'") ``` ```python ttest_ind(df_eur["horsepower"], df_jap["horsepower"]) ``` TtestResult(statistic=0.23093695241338838, pvalue=0.8176893173506833, df=145.0) ```python print("H0 : \"Les voitures européennes et japonaises ont en moyenne le même nombre de chevaux\"") print() alpha = 0.02 p_value = ttest_ind(df_eur["horsepower"], df_jap["horsepower"]).pvalue if p_value < alpha: print("Nous avons suffisamment d'évidences pour rejeter H0") else: print("Nous n'avons pas suffisamment d'évidences pour rejeter H0") ``` H0 : "Les voitures européennes et japonaises ont en moyenne le même nombre de chevaux" Nous n'avons pas suffisamment d'évidences pour rejeter H0 ### 7. Comparaison du nombre de cylindres entre les voitures Ford et Dodge H0 : Les constructeurs Ford et Dodge produisaient dans les années 70-82 des voitures avec un nombre de cylindres équivalent ```python filtered_df = df[df['name'].str.contains('ford|dodge', case=False, na=False)] filtered_df['brand'] = filtered_df['name'].apply(lambda x: 'ford' if 'ford' in x else 'dodge') filtered_df ``` C:\Users\steph\AppData\Local\Temp\ipykernel_28332\2109538067.py:3: 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 filtered_df['brand'] = filtered_df['name'].apply(lambda x: 'ford' if 'ford' in x else 'dodge') <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>mpg</th> <th>cylinders</th> <th>displacement</th> <th>horsepower</th> <th>weight</th> <th>acceleration</th> <th>model_year</th> <th>origin</th> <th>name</th> <th>brand</th> </tr> </thead> <tbody> <tr> <th>4</th> <td>17.0</td> <td>8</td> <td>302.0</td> <td>140.0</td> <td>3449</td> <td>10.5</td> <td>70</td> <td>usa</td> <td>ford torino</td> <td>ford</td> </tr> <tr> <th>5</th> <td>15.0</td> <td>8</td> <td>429.0</td> <td>198.0</td> <td>4341</td> <td>10.0</td> <td>70</td> <td>usa</td> <td>ford galaxie 500</td> <td>ford</td> </tr> <tr> <th>10</th> <td>15.0</td> <td>8</td> <td>383.0</td> <td>170.0</td> <td>3563</td> <td>10.0</td> <td>70</td> <td>usa</td> <td>dodge challenger se</td> <td>dodge</td> </tr> <tr> <th>17</th> <td>21.0</td> <td>6</td> <td>200.0</td> <td>85.0</td> <td>2587</td> <td>16.0</td> <td>70</td> <td>usa</td> <td>ford maverick</td> <td>ford</td> </tr> <tr> <th>25</th> <td>10.0</td> <td>8</td> <td>360.0</td> <td>215.0</td> <td>4615</td> <td>14.0</td> <td>70</td> <td>usa</td> <td>ford f250</td> <td>ford</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>389</th> <td>22.0</td> <td>6</td> <td>232.0</td> <td>112.0</td> <td>2835</td> <td>14.7</td> <td>82</td> <td>usa</td> <td>ford granada l</td> <td>ford</td> </tr> <tr> <th>391</th> <td>36.0</td> <td>4</td> <td>135.0</td> <td>84.0</td> <td>2370</td> <td>13.0</td> <td>82</td> <td>usa</td> <td>dodge charger 2.2</td> <td>dodge</td> </tr> <tr> <th>393</th> <td>27.0</td> <td>4</td> <td>140.0</td> <td>86.0</td> <td>2790</td> <td>15.6</td> <td>82</td> <td>usa</td> <td>ford mustang gl</td> <td>ford</td> </tr> <tr> <th>395</th> <td>32.0</td> <td>4</td> <td>135.0</td> <td>84.0</td> <td>2295</td> <td>11.6</td> <td>82</td> <td>usa</td> <td>dodge rampage</td> <td>dodge</td> </tr> <tr> <th>396</th> <td>28.0</td> <td>4</td> <td>120.0</td> <td>79.0</td> <td>2625</td> <td>18.6</td> <td>82</td> <td>usa</td> <td>ford ranger</td> <td>ford</td> </tr> </tbody> </table> <p>76 rows × 10 columns</p> </div> ```python contigency_table = pd.crosstab(filtered_df["cylinders"], filtered_df["brand"]) contigency_table ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th>brand</th> <th>dodge</th> <th>ford</th> </tr> <tr> <th>cylinders</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th>4</th> <td>12</td> <td>16</td> </tr> <tr> <th>6</th> <td>4</td> <td>12</td> </tr> <tr> <th>8</th> <td>12</td> <td>20</td> </tr> </tbody> </table> </div> ```python chi2_contingency(contigency_table) ``` Chi2ContingencyResult(statistic=1.4056122448979593, pvalue=0.49519377793169395, dof=2, expected_freq=array([[10.31578947, 17.68421053], [ 5.89473684, 10.10526316], [11.78947368, 20.21052632]])) ```python pd.DataFrame( chi2_contingency(contigency_table).expected_freq, columns=filtered_df["brand"].sort_values().unique(), index=filtered_df["cylinders"].sort_values().unique() ).round() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>dodge</th> <th>ford</th> </tr> </thead> <tbody> <tr> <th>4</th> <td>10.0</td> <td>18.0</td> </tr> <tr> <th>6</th> <td>6.0</td> <td>10.0</td> </tr> <tr> <th>8</th> <td>12.0</td> <td>20.0</td> </tr> </tbody> </table> </div> ```python print("H0 : \"Les constructeurs Ford et Dodge produisaient dans les années 70-82 des voitures avec un nombre de cylindres équivalent\"") print() alpha = 0.02 p_value = chi2_contingency(contigency_table).pvalue if p_value < alpha: print("Nous avons suffisamment d'évidences pour rejeter H0") else: print("Nous n'avons pas suffisamment d'évidences pour rejeter H0") ``` H0 : "Les constructeurs Ford et Dodge produisaient dans les années 70-82 des voitures avec un nombre de cylindres équivalent" Nous n'avons pas suffisamment d'évidences pour rejeter H0