No description has been provided for this image
Lab 1 : Préparation de données
visualisation de données, Imputation des valeurs manquantes.
Importer les bibliothèques:
1. Pandas pour la manipulation et l'analyse des données 2. Numpy pour manipuler des matrices ou tableaux multidimensionnels 3. matplotlib pour tracer et visualiser des données sous forme de graphiques 4. seaborn pour la visualisation
In [110]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings("ignore")
In [111]:
tdata =pd.read_csv('titanic.csv')
In [112]:
tdata
Out[112]:
pclass survived name sex age sibsp parch ticket fare cabin embarked
0 1 1 Allen, Miss. Elisabeth Walton female 29.0000 0 0 24160 211.3375 B5 S
1 1 1 Allison, Master. Hudson Trevor male 0.9167 1 2 113781 151.5500 C22 C26 S
2 1 0 Allison, Miss. Helen Loraine female 2.0000 1 2 113781 151.5500 C22 C26 S
3 1 0 Allison, Mr. Hudson Joshua Creighton male 30.0000 1 2 113781 151.5500 C22 C26 S
4 1 0 Allison, Mrs. Hudson J C (Bessie Waldo Daniels) female 25.0000 1 2 113781 151.5500 C22 C26 S
... ... ... ... ... ... ... ... ... ... ... ...
1304 3 0 Zabour, Miss. Hileni female 14.5000 1 0 2665 14.4542 NaN C
1305 3 0 Zabour, Miss. Thamine female NaN 1 0 2665 14.4542 NaN C
1306 3 0 Zakarian, Mr. Mapriededer male 26.5000 0 0 2656 7.2250 NaN C
1307 3 0 Zakarian, Mr. Ortin male 27.0000 0 0 2670 7.2250 NaN C
1308 3 0 Zimmerman, Mr. Leo male 29.0000 0 0 315082 7.8750 NaN S

1309 rows × 11 columns

In [113]:
tdata.head()
Out[113]:
pclass survived name sex age sibsp parch ticket fare cabin embarked
0 1 1 Allen, Miss. Elisabeth Walton female 29.0000 0 0 24160 211.3375 B5 S
1 1 1 Allison, Master. Hudson Trevor male 0.9167 1 2 113781 151.5500 C22 C26 S
2 1 0 Allison, Miss. Helen Loraine female 2.0000 1 2 113781 151.5500 C22 C26 S
3 1 0 Allison, Mr. Hudson Joshua Creighton male 30.0000 1 2 113781 151.5500 C22 C26 S
4 1 0 Allison, Mrs. Hudson J C (Bessie Waldo Daniels) female 25.0000 1 2 113781 151.5500 C22 C26 S
Importer le jeu de données Titanic:
1. Afficher les 5 premières ligne du jeu de données 2. Afficher les dimension de la DataFrame 3. Vérifier le type de chaque colonne 4. afficher les noms des colonnes de la DataFrame
In [4]:
tdata = pd.read_csv('titanic.csv')
In [5]:
tdata.head()
Out[5]:
pclass survived name sex age sibsp parch ticket fare cabin embarked
0 1 1 Allen, Miss. Elisabeth Walton female 29.0000 0 0 24160 211.3375 B5 S
1 1 1 Allison, Master. Hudson Trevor male 0.9167 1 2 113781 151.5500 C22 C26 S
2 1 0 Allison, Miss. Helen Loraine female 2.0000 1 2 113781 151.5500 C22 C26 S
3 1 0 Allison, Mr. Hudson Joshua Creighton male 30.0000 1 2 113781 151.5500 C22 C26 S
4 1 0 Allison, Mrs. Hudson J C (Bessie Waldo Daniels) female 25.0000 1 2 113781 151.5500 C22 C26 S
In [6]:
tdata.shape
Out[6]:
(1309, 11)
In [7]:
tdata.dtypes
Out[7]:
pclass        int64
survived      int64
name         object
sex          object
age         float64
sibsp         int64
parch         int64
ticket       object
fare        float64
cabin        object
embarked     object
dtype: object
In [8]:
tdata.columns
Out[8]:
Index(['pclass', 'survived', 'name', 'sex', 'age', 'sibsp', 'parch', 'ticket',
       'fare', 'cabin', 'embarked'],
      dtype='object')
In [114]:
tdata.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1309 entries, 0 to 1308
Data columns (total 11 columns):
 #   Column    Non-Null Count  Dtype  
---  ------    --------------  -----  
 0   pclass    1309 non-null   int64  
 1   survived  1309 non-null   int64  
 2   name      1309 non-null   object 
 3   sex       1309 non-null   object 
 4   age       1046 non-null   float64
 5   sibsp     1309 non-null   int64  
 6   parch     1309 non-null   int64  
 7   ticket    1309 non-null   object 
 8   fare      1308 non-null   float64
 9   cabin     295 non-null    object 
 10  embarked  1307 non-null   object 
dtypes: float64(2), int64(4), object(5)
memory usage: 112.6+ KB
In [115]:
tdata.describe()
Out[115]:
pclass survived age sibsp parch fare
count 1309.000000 1309.000000 1046.000000 1309.000000 1309.000000 1308.000000
mean 2.294882 0.381971 29.881135 0.498854 0.385027 33.295479
std 0.837836 0.486055 14.413500 1.041658 0.865560 51.758668
min 1.000000 0.000000 0.166700 0.000000 0.000000 0.000000
25% 2.000000 0.000000 21.000000 0.000000 0.000000 7.895800
50% 3.000000 0.000000 28.000000 0.000000 0.000000 14.454200
75% 3.000000 1.000000 39.000000 1.000000 0.000000 31.275000
max 3.000000 1.000000 80.000000 8.000000 9.000000 512.329200
No description has been provided for this image
Etape 1: Visualisation du jeu de données
Vérifier les colonnes.
  1. vérifier la distribution de la variable cible (les classes sont bien équilibré!?) Survival (0 = No; 1 = Yes)
In [118]:
tdata.survived.value_counts()
Out[118]:
survived
0    809
1    500
Name: count, dtype: int64
In [10]:
plt = tdata.survived.value_counts().plot(kind='bar')
plt.set_xlabel('Survivre ou pas')
plt.set_ylabel('Nombre de passager')
Out[10]:
Text(0, 0.5, 'Nombre de passager')
No description has been provided for this image
In [11]:
tdata.pclass.value_counts().sort_index()
Out[11]:
pclass
1    323
2    277
3    709
Name: count, dtype: int64
In [12]:
plt = tdata.pclass.value_counts().sort_index().plot(kind='bar', title='')
plt.set_xlabel('Pclass')
plt.set_ylabel('Survival Probability')
Out[12]:
Text(0, 0.5, 'Survival Probability')
No description has been provided for this image
In [13]:
survived = tdata[tdata.survived == 1]
notsurvived = tdata[tdata.survived == 0]
In [14]:
plt = survived.pclass.value_counts().sort_index().plot(kind='bar', title='')
plt.set_xlabel('Pclass')
plt.set_ylabel('Survival Probability')
Out[14]:
Text(0, 0.5, 'Survival Probability')
No description has been provided for this image
In [15]:
plt = notsurvived.pclass.value_counts().sort_index().plot(kind='bar', title='')
plt.set_xlabel('Pclass')
plt.set_ylabel('NotSurvival Probability')
Out[15]:
Text(0, 0.5, 'NotSurvival Probability')
No description has been provided for this image
In [119]:
tdata.pclass.value_counts().sort_index()
Out[119]:
pclass
1    323
2    277
3    709
Name: count, dtype: int64
In [120]:
grouped_df = tdata[['pclass', 'survived']].groupby('pclass')

for key, item in grouped_df:
    print(grouped_df.get_group(key), "\n\n")
     pclass  survived
0         1         1
1         1         1
2         1         0
3         1         0
4         1         0
..      ...       ...
318       1         0
319       1         1
320       1         1
321       1         0
322       1         1

[323 rows x 2 columns] 


     pclass  survived
323       2         0
324       2         1
325       2         0
326       2         0
327       2         0
..      ...       ...
595       2         0
596       2         1
597       2         1
598       2         1
599       2         0

[277 rows x 2 columns] 


      pclass  survived
600        3         0
601        3         0
602        3         0
603        3         1
604        3         1
...      ...       ...
1304       3         0
1305       3         0
1306       3         0
1307       3         0
1308       3         0

[709 rows x 2 columns] 


In [121]:
grouped_df.count()
Out[121]:
survived
pclass
1 323
2 277
3 709
In [122]:
grouped_df.sum()
Out[122]:
survived
pclass
1 200
2 119
3 181
In [20]:
grouped_df.mean()
Out[20]:
survived
pclass
1 0.619195
2 0.429603
3 0.255289
In [21]:
tdata[['pclass', 'survived']].groupby('pclass').count()
Out[21]:
survived
pclass
1 323
2 277
3 709
In [22]:
tdata[['pclass', 'survived']].groupby('pclass').sum()
Out[22]:
survived
pclass
1 200
2 119
3 181
In [23]:
tdata[['pclass', 'survived']].groupby('pclass').mean()
Out[23]:
survived
pclass
1 0.619195
2 0.429603
3 0.255289
In [124]:
plt = tdata[['pclass', 'survived']].groupby('pclass').mean().survived.plot(kind='bar')
plt.set_xlabel('Pclass')
plt.set_ylabel('Survival Probability')
Out[124]:
Text(0, 0.5, 'Survival Probability')
No description has been provided for this image

Les passagers de la classe 1 on plus de chance pour survivre plus que 60%

In [25]:
plt = tdata.sex.value_counts().sort_index().plot(kind='bar')
plt.set_xlabel('Sex')
plt.set_ylabel('Passenger count')
Out[25]:
Text(0, 0.5, 'Passenger count')
No description has been provided for this image

La majorité sont des hommes

In [26]:
plt = tdata[['sex', 'survived']].groupby('sex').mean().survived.plot(kind='bar')
plt.set_xlabel('Sex')
plt.set_ylabel('Survival Probability')
Out[26]:
Text(0, 0.5, 'Survival Probability')
No description has been provided for this image

Les femmes ont tendence à survivre plus que les hommes: elles ont eu de la priorité par rapport aux hommes

In [27]:
plt = tdata.sibsp.value_counts().sort_index().plot(kind='bar')
plt.set_xlabel('SibSp')
plt.set_ylabel('Passenger count')
Out[27]:
Text(0, 0.5, 'Passenger count')
No description has been provided for this image
In [28]:
plt = tdata[['sibsp', 'survived']].groupby('sibsp').mean().survived.plot(kind='bar')
plt.set_xlabel('SibSp')
plt.set_ylabel('Survival Probability')
Out[28]:
Text(0, 0.5, 'Survival Probability')
No description has been provided for this image

les passagers qui ont un seule frère/sœur/conjoint ont plus de probabilité à survivre '1' > '2' > '0' > '3' > '4'

Parch - Children/Parents

In [29]:
plt = tdata.parch.value_counts().sort_index().plot(kind='bar')
plt.set_xlabel('Parch')
plt.set_ylabel('Passenger count')
Out[29]:
Text(0, 0.5, 'Passenger count')
No description has been provided for this image
In [30]:
plt = tdata[['parch', 'survived']].groupby('parch').mean().survived.plot(kind='bar')
plt.set_xlabel('Parch')
plt.set_ylabel('Survival Probability')
Out[30]:
Text(0, 0.5, 'Survival Probability')
No description has been provided for this image

Les passagers qui ont 3 enfants/parents ont plus de probabilité à survivre '3' > '1' > '2' > '0' > '5'

No description has been provided for this image
Etape 2: Transformation
Transformation des valeur qualitatives.

Convertir les variables qualitatives en quantitatives

In [127]:
tdata.head()
Out[127]:
pclass survived name sex age sibsp parch ticket fare cabin embarked
0 1 1 Allen, Miss. Elisabeth Walton female 29.0000 0 0 24160 211.3375 B5 S
1 1 1 Allison, Master. Hudson Trevor male 0.9167 1 2 113781 151.5500 C22 C26 S
2 1 0 Allison, Miss. Helen Loraine female 2.0000 1 2 113781 151.5500 C22 C26 S
3 1 0 Allison, Mr. Hudson Joshua Creighton male 30.0000 1 2 113781 151.5500 C22 C26 S
4 1 0 Allison, Mrs. Hudson J C (Bessie Waldo Daniels) female 25.0000 1 2 113781 151.5500 C22 C26 S
In [128]:
tdata['sex'] = tdata['sex'].map({'male':0, 'female':1})
tdata['embarked'] = tdata['embarked'].map({'C':0, 'Q':1, 'S':2})
In [129]:
tdata.head()
Out[129]:
pclass survived name sex age sibsp parch ticket fare cabin embarked
0 1 1 Allen, Miss. Elisabeth Walton 1 29.0000 0 0 24160 211.3375 B5 2.0
1 1 1 Allison, Master. Hudson Trevor 0 0.9167 1 2 113781 151.5500 C22 C26 2.0
2 1 0 Allison, Miss. Helen Loraine 1 2.0000 1 2 113781 151.5500 C22 C26 2.0
3 1 0 Allison, Mr. Hudson Joshua Creighton 0 30.0000 1 2 113781 151.5500 C22 C26 2.0
4 1 0 Allison, Mrs. Hudson J C (Bessie Waldo Daniels) 1 25.0000 1 2 113781 151.5500 C22 C26 2.0
In [130]:
tdata.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1309 entries, 0 to 1308
Data columns (total 11 columns):
 #   Column    Non-Null Count  Dtype  
---  ------    --------------  -----  
 0   pclass    1309 non-null   int64  
 1   survived  1309 non-null   int64  
 2   name      1309 non-null   object 
 3   sex       1309 non-null   int64  
 4   age       1046 non-null   float64
 5   sibsp     1309 non-null   int64  
 6   parch     1309 non-null   int64  
 7   ticket    1309 non-null   object 
 8   fare      1308 non-null   float64
 9   cabin     295 non-null    object 
 10  embarked  1307 non-null   float64
dtypes: float64(3), int64(5), object(3)
memory usage: 112.6+ KB
In [33]:
tdata.name
Out[33]:
0                         Allen, Miss. Elisabeth Walton
1                        Allison, Master. Hudson Trevor
2                          Allison, Miss. Helen Loraine
3                  Allison, Mr. Hudson Joshua Creighton
4       Allison, Mrs. Hudson J C (Bessie Waldo Daniels)
                             ...                       
1304                               Zabour, Miss. Hileni
1305                              Zabour, Miss. Thamine
1306                          Zakarian, Mr. Mapriededer
1307                                Zakarian, Mr. Ortin
1308                                 Zimmerman, Mr. Leo
Name: name, Length: 1309, dtype: object

Garder seulement le titre de chaque passager (les caractères qui précèdent le .)

In [34]:
tdata.name.str.extract('( [A-Za-z]+)\.', expand=False)
Out[34]:
0          Miss
1        Master
2          Miss
3            Mr
4           Mrs
         ...   
1304       Miss
1305       Miss
1306         Mr
1307         Mr
1308         Mr
Name: name, Length: 1309, dtype: object
In [ ]:
 
In [ ]:
 
In [35]:
tdata['title'] = tdata.name.str.extract(' ([A-Za-z]+)\.', expand=False)
In [36]:
tdata.head()
Out[36]:
pclass survived name sex age sibsp parch ticket fare cabin embarked title
0 1 1 Allen, Miss. Elisabeth Walton 1 29.0000 0 0 24160 211.3375 B5 2.0 Miss
1 1 1 Allison, Master. Hudson Trevor 0 0.9167 1 2 113781 151.5500 C22 C26 2.0 Master
2 1 0 Allison, Miss. Helen Loraine 1 2.0000 1 2 113781 151.5500 C22 C26 2.0 Miss
3 1 0 Allison, Mr. Hudson Joshua Creighton 0 30.0000 1 2 113781 151.5500 C22 C26 2.0 Mr
4 1 0 Allison, Mrs. Hudson J C (Bessie Waldo Daniels) 1 25.0000 1 2 113781 151.5500 C22 C26 2.0 Mrs
In [37]:
tdata = tdata.drop(columns='name')
In [38]:
tdata.head()
Out[38]:
pclass survived sex age sibsp parch ticket fare cabin embarked title
0 1 1 1 29.0000 0 0 24160 211.3375 B5 2.0 Miss
1 1 1 0 0.9167 1 2 113781 151.5500 C22 C26 2.0 Master
2 1 0 1 2.0000 1 2 113781 151.5500 C22 C26 2.0 Miss
3 1 0 0 30.0000 1 2 113781 151.5500 C22 C26 2.0 Mr
4 1 0 1 25.0000 1 2 113781 151.5500 C22 C26 2.0 Mrs
In [39]:
tdata.title.value_counts().plot(kind='bar')
Out[39]:
<Axes: xlabel='title'>
No description has been provided for this image
In [40]:
tdata['title'] = tdata['title'].replace(['Dr', 'Rev', 'Col', 'Major', 'Countess', 'Sir', 'Jonkheer', 'Lady', 'Capt', 'Don', 'Dona'], 'Others')
tdata['title'] = tdata['title'].replace('Ms', 'Miss')
tdata['title'] = tdata['title'].replace('Mme', 'Mrs')
tdata['title'] = tdata['title'].replace('Mlle', 'Miss')
In [41]:
plt = tdata.title.value_counts().sort_index().plot(kind='bar')
plt.set_xlabel('Title')
plt.set_ylabel('Passenger count')
Out[41]:
Text(0, 0.5, 'Passenger count')
No description has been provided for this image
In [42]:
plt = tdata[['title', 'survived']].groupby('title').mean().survived.plot(kind='bar')
plt.set_xlabel('Title')
plt.set_ylabel('Survival Probability')
Out[42]:
Text(0, 0.5, 'Survival Probability')
No description has been provided for this image

Convertir en variable quantitative

In [43]:
tdata['title'] = tdata['title'].map({'Master':0, 'Miss':1, 'Mr':2, 'Mrs':3, 'Others':4})
In [44]:
tdata.head()
Out[44]:
pclass survived sex age sibsp parch ticket fare cabin embarked title
0 1 1 1 29.0000 0 0 24160 211.3375 B5 2.0 1
1 1 1 0 0.9167 1 2 113781 151.5500 C22 C26 2.0 0
2 1 0 1 2.0000 1 2 113781 151.5500 C22 C26 2.0 1
3 1 0 0 30.0000 1 2 113781 151.5500 C22 C26 2.0 2
4 1 0 1 25.0000 1 2 113781 151.5500 C22 C26 2.0 3
No description has been provided for this image
Etape 3: Données manquantes
Les techniques d'imputation des valeurs manquantes.
  1. Vérifier que la colonne age contient des valeurs manquantes: On peut calculer le nombre de valeurs manquantes au niveau de chaque attribut: ça nous aide à comparer le nombre de valeurs manquante par rapport à la taille du jeu de données
In [45]:
tdata['age'].isnull()
Out[45]:
0       False
1       False
2       False
3       False
4       False
        ...  
1304    False
1305     True
1306    False
1307    False
1308    False
Name: age, Length: 1309, dtype: bool
In [46]:
tdata['age'].isnull().sum()
Out[46]:
np.int64(263)

On peut définir une boucle pour vérifier les valeurs manquantes au niveau de tout les attributs

In [47]:
tdata.shape
Out[47]:
(1309, 11)
In [48]:
tdata.isnull().sum()
Out[48]:
pclass         0
survived       0
sex            0
age          263
sibsp          0
parch          0
ticket         0
fare           1
cabin       1014
embarked       2
title          0
dtype: int64
In [49]:
column_names = tdata.columns
for column in column_names:
    print(column + ' : ' + str(tdata[column].isnull().sum()))
pclass : 0
survived : 0
sex : 0
age : 263
sibsp : 0
parch : 0
ticket : 0
fare : 1
cabin : 1014
embarked : 2
title : 0
In [50]:
tdata.shape
Out[50]:
(1309, 11)

Définir la stratégie d'imputation:

  1. La colonne cabin contient 1014 valeurs manquante d'un totale de 1309 valeurs: supprimer la colonne
In [51]:
tdata = tdata.drop(columns=['cabin'])
In [52]:
tdata.head()
Out[52]:
pclass survived sex age sibsp parch ticket fare embarked title
0 1 1 1 29.0000 0 0 24160 211.3375 2.0 1
1 1 1 0 0.9167 1 2 113781 151.5500 2.0 0
2 1 0 1 2.0000 1 2 113781 151.5500 2.0 1
3 1 0 0 30.0000 1 2 113781 151.5500 2.0 2
4 1 0 1 25.0000 1 2 113781 151.5500 2.0 3

Remplacer les valeurs manquante de la colonne embarked par la valeur la plus redendante

In [53]:
tdata['embarked'].isnull().sum()
Out[53]:
np.int64(2)
In [54]:
tdata.embarked.value_counts()
Out[54]:
embarked
2.0    914
0.0    270
1.0    123
Name: count, dtype: int64
In [55]:
tdata['embarked'] = tdata['embarked'].fillna(2)
tdata.head()
Out[55]:
pclass survived sex age sibsp parch ticket fare embarked title
0 1 1 1 29.0000 0 0 24160 211.3375 2.0 1
1 1 1 0 0.9167 1 2 113781 151.5500 2.0 0
2 1 0 1 2.0000 1 2 113781 151.5500 2.0 1
3 1 0 0 30.0000 1 2 113781 151.5500 2.0 2
4 1 0 1 25.0000 1 2 113781 151.5500 2.0 3
In [56]:
tdata['embarked'].isnull().sum()
Out[56]:
np.int64(0)

Remplacer les valeurs manquante de la colonne fare par la valeur moyenne

In [57]:
tdata['fare'].isnull().sum()
Out[57]:
np.int64(1)
In [58]:
tdata.fare.mean()
Out[58]:
np.float64(33.29547928134557)
In [59]:
tdata['fare'] = tdata['fare'].fillna(tdata.fare.mean())
tdata.head()
Out[59]:
pclass survived sex age sibsp parch ticket fare embarked title
0 1 1 1 29.0000 0 0 24160 211.3375 2.0 1
1 1 1 0 0.9167 1 2 113781 151.5500 2.0 0
2 1 0 1 2.0000 1 2 113781 151.5500 2.0 1
3 1 0 0 30.0000 1 2 113781 151.5500 2.0 2
4 1 0 1 25.0000 1 2 113781 151.5500 2.0 3
In [60]:
tdata.isnull().sum()
Out[60]:
pclass        0
survived      0
sex           0
age         263
sibsp         0
parch         0
ticket        0
fare          0
embarked      0
title         0
dtype: int64
In [88]:
corr_matrix = tdata[['pclass', 'sex', 'age', 'sibsp', 'parch', 'embarked']].corr()
In [89]:
corr_matrix
Out[89]:
pclass sex age sibsp parch embarked
pclass 1.000000 -0.124617 -0.448252 0.060832 0.018322 0.185479
sex -0.124617 1.000000 -0.057934 0.109609 0.213125 -0.097960
age -0.448252 -0.057934 1.000000 -0.245868 -0.146060 -0.059738
sibsp 0.060832 0.109609 -0.245868 1.000000 0.373587 0.065567
parch 0.018322 0.213125 -0.146060 0.373587 1.000000 0.044772
embarked 0.185479 -0.097960 -0.059738 0.065567 0.044772 1.000000
In [90]:
sns.heatmap(data = corr_matrix,annot=True, linewidths=0.2) 
Out[90]:
<Axes: >
No description has been provided for this image

L'age n'est pas cooréler avec les variables sex et embarked donc nous n'allons pas considérer ces 2 variables.
'Pclass', 'SibSp' et 'Parch' sont négativement coorélées à l'age
on peut remplir les valeurs manquante de l'age par la mediane des valeurs similaire ('Pclass', 'SibSp' 'Parch'), sinon par la valeur mediane de la colonne age

In [62]:
NaN_indexes = tdata['age'][tdata['age'].isnull()].index
In [63]:
NaN_indexes
Out[63]:
Index([  15,   37,   40,   46,   59,   69,   70,   74,   80,  106,
       ...
       1282, 1283, 1284, 1291, 1292, 1293, 1297, 1302, 1303, 1305],
      dtype='int64', length=263)
In [92]:
for i in NaN_indexes:
    pred_age = tdata['age'][((tdata.sibsp == tdata.iloc[i]["sibsp"]) & (tdata.parch == tdata.iloc[i]["parch"]) & (tdata.pclass == tdata.iloc[i]["pclass"]))].median()
    if not np.isnan(pred_age):
        tdata['age'].iloc[i] = pred_age
    else:
        tdata['age'].iloc[i] = tdata['age'].median()
In [93]:
tdata.isnull().sum()
Out[93]:
pclass        0
survived      0
sex           0
age           0
sibsp         0
parch         0
ticket        0
fare          0
embarked      0
title         0
familysize    0
dtype: int64
No description has been provided for this image
Etape 4: Ingénierie des attributs
Génerer des attributs à travers des combinaisons entre les caractéristiques.
In [94]:
tdata['familysize'] = tdata['sibsp'] + tdata['parch'] + 1
In [95]:
tdata.head()
Out[95]:
pclass survived sex age sibsp parch ticket fare embarked title familysize
0 1 1 1 29.0000 0 0 24160 211.3375 2.0 1 1
1 1 1 0 0.9167 1 2 113781 151.5500 2.0 0 4
2 1 0 1 2.0000 1 2 113781 151.5500 2.0 1 4
3 1 0 0 30.0000 1 2 113781 151.5500 2.0 2 4
4 1 0 1 25.0000 1 2 113781 151.5500 2.0 3 4
In [97]:
tdata.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1309 entries, 0 to 1308
Data columns (total 11 columns):
 #   Column      Non-Null Count  Dtype  
---  ------      --------------  -----  
 0   pclass      1309 non-null   int64  
 1   survived    1309 non-null   int64  
 2   sex         1309 non-null   int64  
 3   age         1309 non-null   float64
 4   sibsp       1309 non-null   int64  
 5   parch       1309 non-null   int64  
 6   ticket      1309 non-null   object 
 7   fare        1309 non-null   float64
 8   embarked    1309 non-null   float64
 9   title       1309 non-null   int64  
 10  familysize  1309 non-null   int64  
dtypes: float64(3), int64(7), object(1)
memory usage: 112.6+ KB
In [98]:
tdata = tdata.drop(columns=['ticket'])
corr_matrix = tdata.corr()
In [99]:
sns.heatmap(data = corr_matrix, annot=True, linewidths=0.2)
Out[99]:
<Axes: >
No description has been provided for this image
In [100]:
tdata.to_csv('Titanic11.csv', index=False)
In [102]:
X = tdata[['pclass', 'sex', 'age', 'sibsp', 'parch', 'fare', 'embarked', 'title', 'familysize']]
X
Out[102]:
pclass sex age sibsp parch fare embarked title familysize
0 1 1 29.0000 0 0 211.3375 2.0 1 1
1 1 0 0.9167 1 2 151.5500 2.0 0 4
2 1 1 2.0000 1 2 151.5500 2.0 1 4
3 1 0 30.0000 1 2 151.5500 2.0 2 4
4 1 1 25.0000 1 2 151.5500 2.0 3 4
... ... ... ... ... ... ... ... ... ...
1304 3 1 14.5000 1 0 14.4542 0.0 1 2
1305 3 1 25.0000 1 0 14.4542 0.0 1 2
1306 3 0 26.5000 0 0 7.2250 0.0 2 1
1307 3 0 27.0000 0 0 7.2250 0.0 2 1
1308 3 0 29.0000 0 0 7.8750 2.0 2 1

1309 rows × 9 columns

In [103]:
Y = tdata['survived']
Y
Out[103]:
0       1
1       1
2       0
3       0
4       0
       ..
1304    0
1305    0
1306    0
1307    0
1308    0
Name: survived, Length: 1309, dtype: int64
In [104]:
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,Y,test_size=0.2, random_state=0)
In [105]:
X_train
Out[105]:
pclass sex age sibsp parch fare embarked title familysize
1118 3 0 25.0000 0 0 7.9250 2.0 2 1
44 1 1 41.0000 0 0 134.5000 0.0 1 1
1072 3 0 25.0000 0 0 7.7333 1.0 2 1
1130 3 1 18.0000 0 0 7.7750 2.0 1 1
574 2 0 29.0000 1 0 21.0000 2.0 2 2
... ... ... ... ... ... ... ... ... ...
763 3 1 0.1667 1 2 20.5750 2.0 1 4
835 3 0 25.0000 0 0 8.0500 2.0 2 1
1216 3 1 25.0000 0 0 7.7333 1.0 1 1
559 2 1 20.0000 0 0 36.7500 2.0 1 1
684 3 1 32.0000 1 1 15.5000 1.0 3 3

1047 rows × 9 columns

In [106]:
y_train.shape
Out[106]:
(1047,)
In [107]:
y_test.shape
Out[107]:
(262,)
In [ ]:
 
In [ ]: