DieTanic_EDA_Part1

매일 공부(ML)·2022년 3월 23일
0

캐글 필사

목록 보기
7/34

EDA

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('fivethirtyeight')
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
data=pd.read_csv('./input/train.csv')
data.head()

data.isnull().sum()#null값 측정(Age, Cabin, Embarked)


생존자는?

#38.4% , 350명 생존
f, ax=plt.subplots(1,2,figsize=(18,8))
data['Survived'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[0],shadow=True)
ax[0].set_title('Survived')
ax[0].set_ylabel('')
sns.countplot('Survived',data=data, ax=ax[1])
ax[1].set_title('Survived')
plt.show()


Features 유형


Categorical

2개 이상의 카테고리

값들은 범주화에 속함

값들을 정렬할 수 없음(Nominal Variables)

예시: Sex, Embarked


Ordinal

Categorical와 비슷한 속성

값들을 정렬할 수 있다

예시: PClass


Continous

각 열의 최소값과 최대값 구하기 가능

예시: Age


Categorical Feature: Sex

data.groupby(['Sex','Survived'])['Survived'].count()

f,ax=plt.subplots(1,2,figsize=(18,8))
data[['Sex','Survived']].groupby(['Sex']).mean().plot.bar(ax=ax[0])
ax[0].set_title('Survived vs Sex')
sns.countplot('Sex', hue='Survived', data=data, ax=ax[1])
ax[1].set_title('Sex:Survived vs Dead')
plt.show()

데이터를 보면, 남성이 여성보다 탑승객은 많으나 생존자는 혀전히 적다는 것을 알 수 있습니다. 이를 통해서 훗날 모델의 특징을 잡을 때 중요한 요소일 것입니다.


Pclass->Ordinal Feature

pd.crosstab(data.Pclass,data.Survived,margins=True).style.background_gradient(cmap='summer_r')


Pclass에 따른 탑승객 수와 생존자 수의 상관관계

f,ax=plt.subplots(1,2,figsize=(18,8))
data['Pclass'].value_counts().plot.bar(color=['#CD7F32','#FFDF00','#D3D3D3'], ax=ax[0])
ax[0].set_title('Number Of Passenger By Pclass')
ax[0].set_ylabel('Count')
sns.countplot('Pclass', hue='Survived', data=data, ax=ax[1])
ax[1].set_title('Pclass:Survived vs Dead')
plt.show()

#성별, Pclass, 생존율의 관계

pd.crosstab([data.Sex,data.Survived],data.Pclass,margins=True).style.background_gradient(cmap='summer_r')

sns.factorplot('Pclass','Survived',hue='Sex', data=data)
plt.show()

Pclass1에 있던 여성 탑승객의 생존률은 95~96%이라는 높은 수치를 보입니다.

즉, Pclass가 생존율에 중요한 영향을 미치는 특징일 것 같습니다.


Continous Feature-Age

print('Oldest Passenger was of:', data['Age'].max(),'Years')
print('Youngest Passenger was of:', data['Age'].min(),'Years')
print('Average Age on the ship:', data['Age'].mean(),'Years')

f,ax=plt.subplots(1,2,figsize=(18,8))
sns.violinplot("Pclass","Age", hue="Survived", data=data,split=True,ax=ax[0])
ax[0].set_title('Pclass and Age vs Survived')
ax[0].set_yticks(range(0,110,10))
sns.violinplot("Sex","Age", hue="Survived", data=data,split=True,ax=ax[1])
ax[1].set_title('Sex and Age vs Survived')
ax[1].set_yticks(range(0,110,10))
plt.show()

10살 보다 어린 아이들의 생존율이 가장 높다.

Pclass1, 20~50대 나이분들의 생존율이 높았고 그 중 여성분의 생존이 가장 높다.

근데, 한 가지 생각해야될 것은 Age의 결측치가 177이나 되기 때문에 데이터의 거짓말이 발생할 수도 있다는 점이다.

그러므로, Name feature(고유값)를 사용해서 이 문제를 타파하자

data['Initial']=0
for i in data:
    data['Initial']=data.Name.str.extract('([A-Za-z]+)\.') #s뽑기
pd.crosstab(data.Initial,data.Sex).T.style.background_gradient(cmap='summer_r')#성별과 함께 이니셜 체크

data['Initial'].replace(['Mlle','Mme','Ms','Dr','Major','Lady','Countess','Jonkheer','Col','Rev','Capt','Sir','Don'],['Miss','Miss','Miss','Mr','Mr','Mrs','Mrs','Other','Other','Other','Mr','Mr','Mr'],in
data.groupby('Initial')['Age'].mean() # 평균 이니셜 체크

#Filling NaN Ages


data.loc[(data.Age.isnull())&(data.Initial=='Mr'),'Age'] = 33
data.loc[(data.Age.isnull())&(data.Initial=='Mrs'),'Age'] = 36
data.loc[(data.Age.isnull())&(data.Initial=='Master'),'Age'] = 5
data.loc[(data.Age.isnull())&(data.Initial=='Miss'),'Age'] = 22
data.loc[(data.Age.isnull())&(data.Initial=='Ohter'),'Age'] = 46
data.Age.isnull().any()

f,ax=plt.subplots(1,2,figsize=(20,10))
data[data['Survived']==0].Age.plot.hist(ax=ax[0],bins=20,edgecolor='black',color='red')
ax[0].set_title('Survived=0')
x1=list(range(0,85,5))
ax[0].set_xticks(x1)
data[data['Survived'] == 1].Age.plot.hist(ax=ax[1], color='green', bins=20, edgecolor='black')
ax[1].set_title('Survived=1')
x2=list(range(0,85,5))
ax[1].set_xticks(x2)
plt.show()

sns.factorplot('Pclass','Survived',col='Initial', data=data)
plt.show()

profile
성장을 도울 아카이빙 블로그

0개의 댓글