데이터 과학

타이타닉 생존자 분석 본문

Kaggle 데이터 분석, 딥러닝

타이타닉 생존자 분석

티에스윤 2022. 1. 21. 13:16

https://www.kaggle.com/advaitchavan/titanic-survival-analysis

 

Titanic survival analysis

Explore and run machine learning code with Kaggle Notebooks | Using data from Titanic - Machine Learning from Disaster

www.kaggle.com

캐글 competitions에서 타이타닉 데이터 분석이 진행되고 있는데, 대체적으로 기본적인 데이터 마이닝 기법을 많이 사용하고 있습니다. 

 

위 예시는 간단한 인공지능 알고리즘인 SVM과 결정트리 이론을 배경으로 분석한 내용으로 데이터마이닝 기법을 사용한 예제입니다. 

 

예제 실습하다가 아래와 같은 메시지가 나오면 결측치값을 없애주지 않아서 발생한 에러이니 결측치 값을 없애주고 fit 명령어를 적용하면 에러가 없어집니다. 

 

                       Input contains NaN, infinity or a value too large for dtype('float32').

 

 

 

 

또한, prediction을 이용한 예제가 있어서 링크를 걸어봅니다. 

 

https://www.kaggle.com/piyushmohnot/titanicpredictionnotebook

 

TitanicPredictionNotebook

Explore and run machine learning code with Kaggle Notebooks | Using data from Titanic - Machine Learning from Disaster

www.kaggle.com

 

 

판다스 라이브러리를 이용하는 데이터 분석 방법은 몇 년 전부터 많이들 소개되고 있는데 기본적인 함수들을 사용하는 방법만 알면 쉽게 시각화를 할 수 있습니다. 

과거에는 R 언어로 시각화를 했는데, 지금은 파이썬을 기반으로 판다스를 활용하는 방법이 보편적으로 많이 사용되고 있습니다. 그 이유는 예제도 많고, 아나콘다만 설치하면 쉽게 사용할 수 있기 때문입니다. 

 

 

아래 예제는 판다스 공부를 하기 위해서 한번은 실행해 볼만한 예제입니다.

 

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.graph_objs as go 
import plotly.offline as py
py.init_notebook_mode(connected=True) 

from sklearn.preprocessing import StandardScaler
%matplotlib inline

 

train_data = pd.read_csv("./train.csv")

train_data.info()
train_data.head(10)
train_data.shape
train_data.describe()

trace = go.Pie(labels = train_data["Survived"].value_counts().keys().tolist(),
               values =  train_data["Survived"].value_counts().values.tolist(),
               marker = dict(colors = ['royalblue','lime'],
                             line = dict(color = "white", width =  1.3)
                            ),
               rotation = 90,
               hoverinfo = "label+value+text",
               hole = .5
              )
layout = go.Layout(dict(title = "Customer churn Telco dataset ",
                        plot_bgcolor = "orange",
                        paper_bgcolor = "white",
                       )
                  )
data = [trace]
fig = go.Figure(data = data, layout = layout)
py.iplot(fig)

 

missing_age_values = train_data_tidy[np.isnan(train_data_tidy.Age)]
missing_age_values

 

 

plt.hist(train_data_tidy.Age,bins="fd")
plt.xlabel("Age of the passengers")
plt.ylabel("Count")
plt.show()

 

x = train_data_tidy[(train_data_tidy.Age.isnull()) & (train_data_tidy.Survived==0) & (train_data.Pclass ==3)]

print(f'Percent of  the missing age values who aren`t survived and who are from 3d Pclass : {round(len(x)/len(missing_age_values),2)*100} % .')

 

x_present = train_data_tidy[(train_data_tidy.Age.notnull()) & (train_data_tidy.Survived==0) & (train_data.Pclass ==3)]

x_present

x_present.Age.mean()

 

mean_age_of_not_survived = (train_data_tidy[(train_data_tidy.Age.notna()) & (train_data_tidy.Survived == 0)]).mean()
mean_age_of_not_survived

 

train_data_tidy.Age=train_data_tidy.Age.fillna(mean_age_of_not_survived[3])
train_data.Age.mean()

 

train_data_tidy.Age.mode()

plt.hist(train_data_tidy.Age,bins ="fd")
plt.xlabel("Age of the passengers")
plt.ylabel("Count")
plt.show()

 

plt.hist(train_data_tidy.Pclass)
plt.xlabel("Class")
plt.ylabel("Count")
plt.show()

 

pd.pivot_table(train_data_tidy,  values = "Survived", columns = "Sex", index = "Pclass")

 

third_class_passengers = len(train_data_tidy[train_data_tidy.Pclass == 3]) / len(train_data_tidy.Pclass)*100
print(f'Percent of the passengers in 3d class vs all: {round(third_class_passengers,2)}%.' )

 

plt.hist(train_data_tidy.Sex)
plt.xlabel("Male/Femae")
plt.ylabel("Count")
plt.show()

 

for i, j in enumerate(train_data_tidy.drop(["PassengerId", "Age", "Fare"],axis=1)):
    plt.figure(i)
    sns.countplot(data=train_data, x= j, hue="Survived")

 

아래 원문 참조: 

https://www.kaggle.com/code/hristinaaleksandrova/titanic-data-modeling

 

Titanic data modeling

Explore and run machine learning code with Kaggle Notebooks | Using data from Titanic - Machine Learning from Disaster

www.kaggle.com

 

 

https://www.kaggle.com/code/shilongzhuang/attack-on-titanic-solution-walkthrough-top-8/notebook

 

Attack-on-Titanic Solution Walkthrough (top 8%)

Explore and run machine learning code with Kaggle Notebooks | Using data from Titanic - Machine Learning from Disaster

www.kaggle.com

 

 

 

아래 예제는 Confusion Matrix(오차행렬)을 활용한 예제로 accuracy (정확도), Precision (정밀도), Recall (재현율)등을 나타냅니다. 

 

  • True Negative: You predicted a Negative and its True.
  • True Positive: You predicted a Positive and its True.
  • False Positive: You predicted a Positive but its False.
  • False Negative: You predicted a Negative but its False.

https://tsyoon.tistory.com/36

 

Fashion MNIST

딥러닝을 공부할 때 가장 먼저 만나게 되는 예제가 MNIST 입니다. MNIST는 뉴욕대의 Recunn 교수가 필기체 인식을 위한 알고리즘 개선을 위해 연구하는 분야로 Modified National Institute of Standards and Tech..

tsyoon.tistory.com

 

https://www.kaggle.com/rprkh15/titanic-survival-prediction

 

Titanic Survival Prediction

Explore and run machine learning code with Kaggle Notebooks | Using data from Titanic - Machine Learning from Disaster

www.kaggle.com

https://www.kaggle.com/code/aleksandrmorozov123/machine-learning-excercises/notebook

 

Machine Learning Excercises

Explore and run machine learning code with Kaggle Notebooks | Using data from Titanic - Machine Learning from Disaster

www.kaggle.com

 

위 예제는 SVC와 결정포레스트에 대한 라이브러리를 활용한 예제입니다. 한번쯤 실행해서 데이터 분석의 여러 알고리즘을 경험해 보는 것이 좋을 것 같습니다. 

 

 

Machine Learning Excercises

Explore and run machine learning code with Kaggle Notebooks | Using data from Titanic - Machine Learning from Disaster

www.kaggle.com