標籤:

預測Titanic--kaggle

預測Titanic--kaggle

來自專欄 數據分析實踐之路

背景:python+jupyter+kaggle上的數據集

根據Titanic號生存下的人進行分析預測,哪些人可以存活。

1.提出問題

什麼樣的人在泰坦尼克號中更容易存活?

2.理解數據

2.1 採集數據

從kaggle上下載數據集

2.2導入數據

導入包

import pandas as pd #數據分析import numpy as np #科學計算from pandas import Series, DataFrameimport matplotlib.pyplot as pltfrom pylab import *mpl.rcParams[font.sans-serif] = [SimHei] #中文顯示解決方案plt.rcParams[axes.unicode_minus]=False #負號顯示解決方案

導入數據

#導入數據#訓練集數據train = pd.read_csv("E:\huangan\kaggle-excise\titanic\train.csv")train

2.3查看數據

查看總的信息

描述性統計信息

乘客各個屬性分布

fig = plt.figure() #空白幕布fig.set(alpha=0.2) #圖表顏色參數fig.set_figheight(10) fig.set_figwidth(15)plt.subplot2grid((2,3), (0,0)) #一張大圖裡分裂幾個小圖,二行三列,第一行第一個圖train.Survived.value_counts().plot(kind=bar) #柱狀圖plt.title(u"獲救情況(1為獲救)") #標題, fontproperties=fontplt.ylabel(u"人數")plt.subplot2grid((2,3), (0,1))train.Pclass.value_counts().plot(kind=bar)plt.ylabel(u"人數")plt.title(u"乘客等級分布")plt.subplot2grid((2,3), (0,2))plt.scatter(train.Survived, train.Age)plt.ylabel(u"年齡")plt.grid(b=True, which=major, axis=y)plt.title(u"按年齡看獲救分布(1為獲救)")plt.subplot2grid((2,3), (1,0), colspan=2)train.Age[train.Pclass == 1].plot(kind=kde)train.Age[train.Pclass == 2].plot(kind=kde)train.Age[train.Pclass == 3].plot(kind=kde)plt.xlabel(u"年齡")plt.ylabel(u"密度")plt.title(u"各等級的乘客年齡分布")plt.legend((u"頭等艙", u"2等艙", u"3等艙"), loc=best) #圖例, prop=chineseplt.subplot2grid((2,3),(1,2))train.Embarked.value_counts().plot(kind=bar)plt.title(u"各登船口岸上船人數")plt.ylabel(u"人數") plt.show()

看看各乘客等級的獲救情況

fig = plt.figure()fig.set(alpha=0.2)Survived_0 = train.Pclass[train.Survived == 0].value_counts()Survived_1 = train.Pclass[train.Survived == 1].value_counts()df = pd.DataFrame({u"獲救":Survived_1, u"未獲救":Survived_0})df.plot(kind=bar, stacked=True)plt.title(u各乘客等級的獲救情況)plt.xlabel(u乘客等級)plt.ylabel(u人數)plt.show()

查看性別獲救的情況

fig = plt.figure()fig.set(alpha=0.2)Survived_m = train.Survived[train.Sex == male].value_counts()Survived_f = train.Survived[train.Sex ==female].value_counts()df = pd.DataFrame({u"男性":Survived_m, u"女性":Survived_f})df.plot(kind=bar, stacked=True)plt.title(u按性別查看獲救情況)plt.xlabel(u性別)plt.ylabel(u人數)plt.show()

看看各種艙級別情況下各性別的獲救情況

fig = plt.figure()fig.set(alpha=0.65)fig.set_figwidth(10)plt.title(u根據艙等級和性別的獲救情況)axl = fig.add_subplot(141)train.Survived[train.Sex == female][train.Pclass != 3].value_counts().plot(kind=bar, label="female highclass", color=#FA2479)axl.set_xticklabels([u獲救, u未獲救], rotation=0)plt.legend([u女性/高級艙], loc=best)axl2 = fig.add_subplot(142, sharey=axl)train.Survived[train.Sex == female][train.Pclass == 3].value_counts().plot(kind=bar, label="female, low class", color=pink)axl2.set_xticklabels([u獲救, u未獲救], rotation=0)plt.legend([u女性/低級艙], loc=best)axl3 = fig.add_subplot(143, sharey=axl)train.Survived[train.Sex == female][train.Pclass != 3].value_counts().plot(kind=bar, label="male, high class", color=lightblue)axl3.set_xticklabels([u獲救, u未獲救], rotation=0)plt.legend([u男性/高級艙], loc=best)axl4 = fig.add_subplot(144, sharey=axl)train.Survived[train.Sex == female][train.Pclass == 3].value_counts().plot(kind=bar, label="male, low class", color=steelblue)axl4.set_xticklabels([u獲救, u未獲救], rotation=0)plt.legend([u男性/低級艙], loc=best)plt.show()

各登錄港口的獲救情況

fig = plt.figure()fig.set(alpha=0.2)Survived_0 = train.Embarked[train.Survived == 0].value_counts()Survived_1 = train.Embarked[train.Survived == 1].value_counts()df = pd.DataFrame({u獲救: Survived_1, u未獲救: Survived_0})df.plot(kind=bar, stacked=True)plt.title(u各登錄港口的獲救情況)plt.xlabel(u登錄港口)plt.ylabel(u人數)plt.show()

看看cabin的分布

train.Cabin.value_counts()#初步看一下cabin的survived的獲救情況fig = plt.figure()fig.set(alpha=0.2)Survived_cabin = train.Survived[pd.notnull(train.Cabin)].value_counts()Survived_nocabin = train.Survived[pd.isnull(train.Cabin)].value_counts()df = DataFrame({u有: Survived_cabin, u無: Survived_nocabin}).transpose()df.plot(kind=bar, stacked=True)plt.title(ucabin的survived的獲救情況)plt.xlabel(ucabin有無)plt.ylabel(u人數)plt.show()

3.數據預處理

3.1缺失值處理

船票:採用平均值處理

total[Fare] = total[Fare].fillna(total[Fare].mean())

登船港口(Embarked):按眾數填充

total[Embarked] = total[Embarked].fillna(S)

年齡:缺失較大

#Age填充 from sklearn.ensemble import RandomForestRegressor### 使用 RandomForestClassifier 填補缺失的年齡屬 age_df = total[[Age,Fare, Parch, SibSp, Pclass]] # 乘客分成已知年齡和未知年齡兩部分 known_age = age_df[age_df.Age.notnull()].as_matrix() unknown_age = age_df[age_df.Age.isnull()].as_matrix() # y即目標年齡 y = known_age[:, 0] # X即特徵屬性值 X = known_age[:, 1:] # fit到RandomForestRegressor之中 rfr = RandomForestRegressor(random_state=0, n_estimators=2000, n_jobs=-1) rfr.fit(X, y) # 用得到的模型進行未知年齡結果預測 predictedAges = rfr.predict(unknown_age[:, 1::]) # 用得到的預測結果填補原缺失數據 total.loc[ (total.Age.isnull()), Age ] = predictedAges

船艙號:缺失值較多,填充為U,表示未知(Uknow)

def set_Cabin_type(total): total.loc[ (total.Cabin.notnull()), Cabin ] = "Yes" total.loc[ (total.Cabin.isnull()), Cabin ] = "No" return totaltotal = set_Cabin_type(total)

查看處理後的結果

處理完畢

3.2特徵提取

因為邏輯回歸建模時,需要輸入的特徵都是數值型特徵,我們通常會先對類目型的特徵因子化。

什麼叫做因子化呢?舉個例子:

以Cabin為例,原本一個屬性維度,因為其取值可以是[『yes』,』no』],而將其平展開為』Cabin_yes』,』Cabin_no』兩個屬性

原本Cabin取值為yes的,在此處的」Cabin_yes」下取值為1,在」Cabin_no」下取值為0

原本Cabin取值為no的,在此處的」Cabin_yes」下取值為0,在」Cabin_no」下取值為1

我們使用pandas的」get_dummies」來完成這個工作,並拼接在原來的」data_train」之上,如下所示。

港口屬性

embarkedDf = pd.DataFrame()embarkedDf = pd.get_dummies(total[Embarked], prefix=Embarked)total = pd.concat([total,embarkedDf],axis=1)total.drop(Embarked,axis=1,inplace=True)

性別屬性

sex_dict = {male:1,female:0}total[Sex] = total[Sex].map(sex_dict)

客艙屬性

pclassDf = pd.get_dummies( total[Pclass] , prefix=Pclass )total = pd.concat([total,pclassDf],axis=1)total.drop(Pclass,axis=1,inplace=True)total.head()

名字屬性

title_mapDict = { "Capt": "Officer", "Col": "Officer", "Major": "Officer", "Jonkheer": "Royalty", "Don": "Royalty", "Sir" : "Royalty", "Dr": "Officer", "Rev": "Officer", "the Countess":"Royalty", "Dona": "Royalty", "Mme": "Mrs", "Mlle": "Miss", "Ms": "Mrs", "Mr" : "Mr", "Mrs" : "Mrs", "Miss" : "Miss", "Master" : "Master", "Lady" : "Royalty" }titleDf[Title] = titleDf[Title].map(title_mapDict)titleDf = pd.get_dummies(titleDf[Title])titleDf.head()

3.3特徵選擇

相關係數法:計算各個特徵的相關係數

根據各個特徵與生成情況的相關係數,選擇了頭銜、客艙等級、家庭大小、船票價格、船艙號、登船港口、性別。

4.構建模型

建立訓練數據集和測試數據集

#原始數據集:特徵source_X = total_x.loc[0:sourceRow-1,:]#原始數據集:標籤source_y = total.loc[0:sourceRow-1,Survived] #預測數據集:特徵pred_X = total_x.loc[sourceRow:,:]from sklearn.cross_validation import train_test_split train_X, test_X, train_y, test_y = train_test_split(source_X ,source_y,train_size=.8)

選擇邏輯回歸演算法

#第1步:導入演算法from sklearn.linear_model import LogisticRegression#第2步:創建模型:邏輯回歸(logisic regression)model = LogisticRegression()#第3步:訓練模型model.fit( train_X , train_y )

5.模型評估

訓練集

# 分類問題,score得到的是模型的準確率model.score(train_X , train_y )

測試集

model.score(test_X , test_y )

6.方案實施

使用機器學習模型,對預測數據集中的生存情況進行預測

pred_Y = model.predict(pred_X)pred_Y=pred_Y.astype(int)passenger_id = total.loc[sourceRow:,PassengerId]predDf = pd.DataFrame( { PassengerId: passenger_id , Survived: pred_Y } )predDf.shapepredDf.head()#保存結果predDf.to_csv( titanic_pred1.csv , index = False )


OVER


推薦閱讀:

今日數據行業日報(2017.03.22)
今日數據行業日報(2016.10.28)
大佛:查詢網貸平台數據的簡單方法!
『女性比男性平均提前1.9天預訂機票 可節省2%』今日數據行業日報(2016.08.26)
今日數據行業日報(2017.7.11)

TAG:數據 |