#!/usr/bin/env python # coding: utf-8 # # Titanic이란? # # - https://www.kaggle.com/c/titanic # # - Titanic에 탑승한 승객 정보를 승객의 구출 여부를 결정 # # # - Data는 Training set과 Test set을 제공 # - Train set으로 모델을 만든 후 Test set에 적용 # - 결과제출은 [ID, 생존예측] 형태로 제출 # - 제출된 결과를 바탕으로 accuracy 점수로 등수를 산정함 # - 분석가들은 기존 자신들이 시도했던 다양한 분석 방법을 사이트를 통해서 공유하고 있음 # - https://www.kaggle.com/c/titanic/data # # Train set에는 살았는지 죽었는지가 있지만, Test set에는 살았는지 죽었는지에 대한 정보가 없다. # In[1]: import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression # ## 1. Load dataset # ### Load train set & test set # In[2]: train_df = pd.read_csv("./train.csv") test_df = pd.read_csv("./test.csv") # In[3]: train_df.head() # In[4]: test_df.head() # ### Change index to 'PassengerId' # In[5]: train_df.set_index('PassengerId', inplace=True) test_df.set_index('PassengerId', inplace=True) # In[6]: train_df.head() # In[7]: test_df.head() # In[8]: train_index = train_df.index test_index = test_df.index # ### Make train label - y_train # In[9]: y_train_df = train_df.pop("Survived") # In[10]: y_train_df.head() # ## 2. Data preproecessing # ### float format for output values # In[11]: pd.set_option('display.float_format', lambda x: '%.2f' % x) # ### Check null values - isnull() # In[12]: train_df.isnull().sum() / len(train_df) # In[13]: test_df.isnull().sum() / len(test_df) # Cabin column에 너무 많은 결측치가 있기 때문에 먼저 Drop으로 없애버리자! # ### Drop Cabin # In[14]: del train_df["Cabin"] del test_df["Cabin"] # ### Combine train set & test set # # 전처리를 해줄 때는 train set, test set 모두 같은 방식으로 해주어야 한다. # In[15]: all_df = train_df.append(test_df) # In[16]: all_df.head() # In[17]: len(all_df) # ### Check null values again # In[18]: (all_df.isnull().sum() / len(all_df)).plot(kind='bar') plt.show() # Age가 Nan값이 있긴 하지만, 20%정도이기 때문에 그냥 두고 진행해도 될 것 같다. # ### Drop Name, Ticket # In[19]: del all_df["Name"] del all_df["Ticket"] # In[20]: all_df.head() # ### One-Hot Encoding - Sex # In[21]: all_df["Sex"] = all_df["Sex"].replace({"male":0, "female":1}) # In[22]: all_df.head() # ### One-Hot Encoding - Embarked # # Embarked - 어느 항구에서 탑승 했는가? # In[23]: all_df["Embarked"].unique() # In[24]: all_df["Embarked"] = all_df["Embarked"].replace({"S":0,"C":1,"Q":2, np.nan:99}) # In[25]: all_df["Embarked"].unique() # In[26]: all_df.head() # In[27]: pd.get_dummies(all_df["Embarked"], prefix="embarked") # prefix - 접두사 # ### Merge original all_df & one-hot encoding Embarked to check # In[28]: matrix_df = pd.merge(all_df, pd.get_dummies(all_df["Embarked"], prefix="embarked"), left_index=True, right_index=True) # In[29]: matrix_df.head() # ### Check correlation # In[30]: matrix_df.corr() # ### Check Age about Pclass # # Pclass는 그 사람이 탄 자리를 말한다. # In[31]: all_df.groupby("Pclass")["Age"].mean() # - 1등급 탄 사람의 평균 나이는 39.16세 # - 2등급 탄 사람의 평균 나이는 29.51세 # - 3등급 탄 사람의 평균 나이는 24.82세 # # 로 나타났기 때문에 20% 정도 비어져있는 Age column의 Nan값들을 mean값을 통해 채워넣을 수 있다. # ### Add to null values of Age # # 그렇다면 이제 각각의 Pclass 등급에 따라서 Age에 비어있는 값들을 채워넣자! # In[32]: all_df.loc[(all_df["Pclass"] == 1) & (all_df["Age"].isnull()), "Age"] # [row, column] # In[33]: all_df.loc[(all_df["Pclass"] == 1) & (all_df["Age"].isnull()), "Age"] = 39.16 # In[34]: all_df.loc[(all_df["Pclass"] == 2) & all_df["Age"].isnull() , "Age"] = 29.51 # In[35]: all_df.loc[(all_df["Pclass"] == 3) & all_df["Age"].isnull(), "Age"] = 24.82 # ### Check null values again # In[36]: all_df.isnull().sum() # Fare에 대해서 1개의 null값이 발견되었다. Age에서 했던 방법과 똑같이 해서 채워주자. # ### Add to null values of Fare # In[37]: all_df.groupby("Pclass")["Fare"].mean() # In[38]: all_df[all_df["Fare"].isnull()] # In[39]: all_df.loc[all_df["Fare"].isnull(), "Fare"] = 13.30 # ### One-Hot Encoding - Pclass # In[40]: all_df["Pclass"] = all_df["Pclass"].replace({1:"A",2:"B",3:"C"}) # In[41]: all_df = pd.get_dummies(all_df) # In[42]: all_df.head() # ### Remove Embarked from original all_df # In[43]: del all_df["Embarked"] # In[44]: all_df.head() # ### Merge original all_df & one-hot encoding Embarked # In[45]: all_df = pd.merge(all_df, matrix_df[["embarked_0", "embarked_1", "embarked_2", "embarked_99"]], left_index=True, right_index=True) # ### Divide train_df & test_df # # 위에서 만들어준 train_index, test_index를 통해 다시 나눠준다. # In[46]: train_df = all_df[all_df.index.isin(train_index)] test_df = all_df[all_df.index.isin(test_index)] # In[47]: train_df.head() # In[48]: test_df.head() # ## 3. Build Model # ### Put x_data & y_data # In[49]: x_data = train_df.values y_data = y_train_df.values # In[50]: x_data.shape, y_data.shape # In[51]: y_data.shape # ### Load LogisticRegression & Train data # In[52]: reg = LogisticRegression() reg.fit(x_data, y_data) # In[53]: print("score: {:.3f}".format(reg.score(x_data, y_data))) # In[54]: reg.intercept_ # Independent term in the linear model # In[55]: reg.coef_ # Estimated coefficients for the linear regression problem # ### Predict with Test data # In[56]: test_df.index # In[57]: x_test = test_df.values # In[58]: y_test = reg.predict(x_test) # In[59]: y_test # ### Concat Test data & predicted results # In[60]: result = np.concatenate((test_index.values.reshape(-1,1), reg.predict(x_test).reshape(-1,1)), axis=1) # In[61]: result[:5] # In[62]: df_submssion = pd.DataFrame(result, columns=["PassengerId","Survived"]) # In[63]: df_submssion.head() # In[64]: df_submssion.to_csv("submission_result.csv", index=False)