인공지능 공부/머신러닝

2021-04-26 머신러닝 완벽가이드 타이타닉 생존자 예측

앨런튜링_ 2021. 4. 26. 17:57
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

titanic_df = pd.read_csv('./titanic_train.csv')
titanic_df.head(3)
PassengerId	Survived	Pclass	Name	Sex	Age	SibSp	Parch	Ticket	Fare	Cabin	Embarked
0	1	0	3	Braund, Mr. Owen Harris	male	22.0	1	0	A/5 21171	7.2500	NaN	S
1	2	1	1	Cumings, Mrs. John Bradley (Florence Briggs Th...	female	38.0	1	0	PC 17599	71.2833	C85	C
2	3	1	3	Heikkinen, Miss. Laina	female	26.0	0	0	STON/O2. 3101282	7.9250	NaN	S
print('\n ### 학습 데이터 정보 ### \n')
print(titanic_df.info())
 ### 학습 데이터 정보 ### 

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   PassengerId  891 non-null    int64  
 1   Survived     891 non-null    int64  
 2   Pclass       891 non-null    int64  
 3   Name         891 non-null    object 
 4   Sex          891 non-null    object 
 5   Age          714 non-null    float64
 6   SibSp        891 non-null    int64  
 7   Parch        891 non-null    int64  
 8   Ticket       891 non-null    object 
 9   Fare         891 non-null    float64
 10  Cabin        204 non-null    object 
 11  Embarked     889 non-null    object 
dtypes: float64(2), int64(5), object(5)
memory usage: 83.7+ KB
None
#age와 cabin,Enbarked에 Null값을 제거하자
#age는 평균나이 나머지는 N값으로 변경합니다. 
titanic_df['Age'].fillna(titanic_df['Age'].mean(),inplace= True)
titanic_df['Cabin'].fillna('N', inplace= True)
titanic_df['Embarked'].fillna('N', inplace = True)
print('데이터 세트 NUll값의 개수',titanic_df.isnull().sum().sum())
데이터 세트 NUll값의 개수 0
#남아있는 문자열 피쳐는 sex, cabin, embarked입니다. 이 피처들의 값 분류를 살펴보자
print('Sex 값 분포:\n', titanic_df['Sex'].value_counts())
print('\n Cabin 값 분포:\n',titanic_df['Cabin'].value_counts())
print('\n Embarked 값 분포:\n',titanic_df['Embarked'].value_counts())
Sex 값 분포:
 male      577
female    314
Name: Sex, dtype: int64

 Cabin 값 분포:
 N              687
B96 B98          4
C23 C25 C27      4
G6               4
E101             3
              ... 
A5               1
B73              1
D10 D12          1
D50              1
A23              1
Name: Cabin, Length: 148, dtype: int64

 Embarked 값 분포:
 S    644
C    168
Q     77
N      2
Name: Embarked, dtype: int64
titanic_df['Cabin'] = titanic_df['Cabin'].str[:1]
print(titanic_df['Cabin'].head(3))
0    N
1    C
2    N
Name: Cabin, dtype: object
#여성과 아이들 그리고 노약자가 제일 먼저 구조 대상이다. 그리고 아마도 부자나 유명인이 다음 구조 대상이었을 것입니다.
#안타깝게도 삼등실에 탄 많은 가난한 이는 타이타닉 호와 운명을 함께 했을 겁니다
#성별에 따른 생존자 수를 비교해 보겠습니다
titanic_df.groupby(['Sex','Survived'])['Survived'].count()
Sex     Survived
female  0            81
        1           233
male    0           468
        1           109
Name: Survived, dtype: int64
#시본패키지 이용해 시각화 한다.
sns.barplot(x='Sex', y='Survived', data=titanic_df)
<AxesSubplot:xlabel='Sex', ylabel='Survived'>

# 부자와 가난한 사람간의생존 확률은 어떨까? 
#객실등급에 따라 다를 것이다. 
#일등실 , 이등실, 마지막 삼등실에따라 생존확률을 살펴보자
sns.barplot(x='Pclass', y='Survived', hue='Sex', data=titanic_df)
<AxesSubplot:xlabel='Pclass', ylabel='Survived'>

#이번에는 나이에따른 생존률을 구해보자 ㅎㅎ 
#Age카테고리리 값을 할당해보자
#입력 age에 따라 구분값을 반환하는 함수를 설정하고 DataFrame의 apply lamda 식에 적용

def get_category(age):
    cat=''
    if age <=-1:cat='Unknown'
    elif age<=5:cat='Baby'
    elif age<=12:cat='Child'
    elif age<=18:cat='Teenager'
    elif age<=25:cat='Student'
    elif age<=35:cat='Young Adult'
    elif age<=60:cat='Adult'
    else :cat = 'Elderly'
        
    return cat
plt.figure(figsize=(10,6))

#X축의 값을 순차적으로 표시하기 위한 설정
group_names = ['Unknown','Baby','Child','Teenager','Student','Young Adult','Adult','Elderly']
<Figure size 720x432 with 0 Axes>
#lambda식 식에 위에서 생성한 get_category()함수를 반환값으로 지정.
#get_category(X)는 입력값으로 'Age'칼럼 값을 받아서 해당하는 cat 반환
titanic_df['Age_cat'] = titanic_df['Age'].apply(lambda x : get_category(x))
sns.barplot(x='Age_cat', y='Survived', hue ='Sex', data=titanic_df, order=group_names)
titanic_df.drop('Age_cat', axis=1,inplace=True)