투빅스 9&10기 2주차 Naive Bayes - 10기 장유영

by 장유영 posted Aug 01, 2018
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

+ - Up Down Comment Print

Week02 Assignment Naive Bayes 코드입니다.


*R이 아니라 파이썬 코드입니다.


# Setting
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
#------------------------------------------------------
#1 데이터 로드
path = "~/NaiveBayes/"
file = pd.read_csv(path + 'train.csv')
file.info()
file.head()
file.isnull().sum()
# Age에 177개, Cabin에 687개, Embarked에 2개가 있다.
# 데이터프레임 최대로 보기
pd.set_option('display.max_columns', 50)
#------------------------------------------------------
#2 Feature Analysis: 연속형 변수
cmap = sns.cubehelix_palette(dark=0.3, light=1, as_cmap=True)
graph = sns.heatmap(file[['Survived', 'SibSp', 'Parch', 'Age', 'Fare']].corr(), annot=True, fmt="0.2f", cmap=cmap)
graph
plt.show()

1.PNG





















# Fare 변수는 상당한 연관이 있는 것으로 판단된다. Parch와 Sibsp는 서로 높은 상관관계를 지닌다.
# Age에 대해서 탐구해보자.
graph = sns.kdeplot(file["Age"][(file["Survived"] == 0) & (file["Age"].notnull())], color="Red", shade=True)
graph = sns.kdeplot(file["Age"][(file["Survived"] == 1) & (file["Age"].notnull())], ax=graph, color="Blue", shade=True)
graph.set_xlabel("Age")
graph.set_ylabel("Frequency")
graph = graph.legend(["Not Survived","Survived"])
graph
plt.show()
2.PNG




















# Fare에 대해 탐구해보자.
graph = sns.distplot(file["Fare"], color="orange")
graph
plt.show()

3.PNG








 











# 너무 치우쳐져 있기 때문에 log변환을 해주는 게 나아보인다.
file["Fare"] = file["Fare"].map(lambda i: np.log(i) if i > 0 else 0)
#------------------------------------------------------
#3 Feature Analysis: 범주형 변수
# Sex에 대해 탐구해보자.
file[["Sex","Survived"]].groupby('Sex').mean()
# 분명 여자가 더 많이 살아남았다.
# Pclass에 대해 탐구해보자.
file[["Pclass","Survived"]].groupby('Pclass').mean()
# 분명 1등석 생존 확률이 높아 보인다.
# Embarked에 대해 탐구해보자.
file[file['Embarked'].isnull()==True]
# 어쩌면 Pclass나 Fare, Cabin과 관련이 있을지도 모른다.
file['Fare'].groupby(file['Embarked']).mean()
file['Pclass'].groupby(file['Embarked']).describe()
# 이 두가지 사실을 조합해보면 1등석을 탔고 $80의 요금을 낸 이 두명은 C선착상에서 탔을 가능성이 높다.
# 돈이 많은 사람들이지 않았을까
# Embarked NA처리
file['Embarked'].fillna('C', inplace = True)
graph = sns.catplot(x="Embarked", y="Survived", data=file,
height=6, kind="bar", palette="coolwarm")
graph = graph.set_ylabels("survival probability")
graph
plt.show()

4.PNG


























# 확실히 선착상 C에서 탔다면 생존확률이 높아보인다.
#------------------------------------------------------
#4 Feature Engineering
# Sex
file['Sex'] = file['Sex'].map({'male':0, 'female':1})
# Embarked
file['Embarked'] = file['Embarked'].map({'S':0, 'C':1, 'Q':2})
file['Embarked'] = file['Embarked'].astype(int)
# file = pd.get_dummies(file, columns=["Embarked"], prefix="Embarked")
# Name
# 이름에서 Mr, Miss 등 추출
file['Title'] = file['Name'].str.extract(' ([A-Za-z]+)\.', expand = False)
file['Title'].value_counts()
# NA값을 확인해보자
file['Title'].isnull().sum()
# 줄여서 매핑해보자.
file['Title'] = file['Title'].replace(['Dr', 'Rev', 'Major', 'Col', 'Don', 'Jonkheer', 'Capt', 'Countess''Lady', 'Done'], 'etc')
title_mapping = {'Mr':0, 'Miss':1, 'Mrs':1, 'Master':2, 'Mlle':1, 'Ms':1, 'Sir':0, 'Mme':1, 'etc':3}
file['Title'] = file['Title'].map(title_mapping)
file['Title'] = file['Title'].astype(int)


# Age
# Pclass, Parch, SibSp가 비슷한 사람들의 Age를 바탕으로 결측값을 추리해보자
# Index of NA age rows
index = list(file["Age"][file["Age"].isnull()].index)
for i in index:
age_median = file["Age"].median()
age_pred = file["Age"][((file['SibSp']==file.iloc[i]["SibSp"]) & (file['Parch']==file.iloc[i]["Parch"]) &
                       (file['Pclass']==file.iloc[i]["Pclass"]))].median()

if not np.isnan(age_pred):
file['Age'].iloc[i] = age_pred
else:
file['Age'].iloc[i] = age_median


# SibSp, Parch 합치기
file['nb_family'] = file['SibSp'] + file['Parch']
# 효과는 어떨까?
graph = sns.catplot(x="nb_family", y="Survived", data=file, kind='point')
graph = graph.set_ylabels("Survival Probability")
graph
plt.show()
5.PNG




















# 필요 없는 Id, Name, SibSp, Parch, Ticket 칼럼을 삭제한다.
file.drop(['PassengerId', 'Name', 'Ticket', 'SibSp', 'Parch'], axis=1, inplace=True)
# Cabin 처리
# 먼저 Cabin의 앞 글자만 남겨보자
file['Cabin'] = file['Cabin'].str[:1]
file["Cabin"] = file["Cabin"].fillna("N")
file['Cabin'].value_counts()
# 과연 생존확률과 관계가 있을까?
graph = sns.catplot(y="Survived", x="Cabin", data=file,kind="bar",order=['A','B','C','D','E','F','G','T','N'], palette='coolwarm')
graph = graph.set_ylabels("Survival Probability")
graph
plt.show()
6.PNG

























# Cabin 정보가 없었던 사람들의 생존확률은 좀 낮아보이고,
# B, D, E 정보를 갖고 있는 사람들의 생존확률이 높아보인다.
file['Cabin'] = file['Cabin'].map({'A':0, 'B':0.1, 'C':0.2, 'D':0.3, 'E':0.4, 'F':0.5, 'G':0.6, 'T':0.7, 'N':1.0})


# Age Scailing
bins = pd.qcut(file['Age'], 6, precision=2, labels=['A1', 'A2', 'A3', 'A4', 'A5', 'A6'])
file['binned_Age'] = bins
file['binned_Age'] = file['binned_Age'].map({'A1':0.0, 'A2':0.2, 'A3':0.4, 'A4':0.6, 'A5':0.8, 'A6':1.0})
file = file.drop('Age', axis=1)

# 학습 및 결과 확인
y = np.array(file['Survived'])
= file.drop('Survived', axis=1)
# random_state 번호를 담은 리스트를 argument에 삽입하면 리스트의 길이 만큼의 횟수로 데이터 셋을 분리하여
# Train Score와 Test Score의 평균을 반환하는 함수
def calculate_score(state_list):
train_scores = []
test_scores = []

for state in state_list:
X_train, X_test, Y_train, Y_test = train_test_split(x, y, test_size=0.1, random_state=state)

nb = GaussianNB()
nb.fit(X_train, Y_train)

train_score = nb.score(X_train, Y_train)
test_score = nb.score(X_test, Y_test)
train_scores.append(train_score)
test_scores.append(test_score)

print("Mean of train scores: ", np.mean(train_scores))
print("Mean of test scores: ", np.mean(test_scores))

return train_scores, test_scores
train_scores, test_scores = calculate_score(state_list=list(range(0,20)))
Mean of train scores: 0.7828339575530587
Mean of test scores: 0.8016666666666667
# 이 random_state 설정과 test_size 설정에 따르면
# Test Score의 평균은 약 80.17%이다.
# 여러 설정을 비교해서 학습해본 결과 (test_size=0.2, random_state=10개~100개 등)
# 나이브 베이즈 단일 모델은 대략 78~79% 정도 되는 성능을 보이는 것으로 확인되었다.

Articles

5 6 7 8 9 10 11 12 13 14

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소

Designed by sketchbooks.co.kr / sketchbook5 board skin

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5