無標(biāo)題文章

Introduction

This notebook describes and implements a basic approach to solving the Titanic Survival Prediction problem. The prediction is made using a Random Forest Classifier.

1. Exploring training and test sets

First, load required packages.

In?[1]:

importreimportnumpyasnpimportpandasaspdimportmatplotlib.pyplotaspltimportwarningsfromsklearn.ensembleimportRandomForestClassifierwarnings.filterwarnings("ignore")plt.style.use('ggplot')

Read training and test sets. Both datasets will be used in exploring and predicting.

In?[2]:

train=pd.read_csv("../input/train.csv")test=pd.read_csv("../input/test.csv")

In?[3]:

train.sample(frac=1).head(3)

Out[3]:

PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked

72372402Hodges, Mr. Henry Pricemale50.00025064313.0000NaNS

252613Asplund, Mrs. Carl Oscar (Selma Augusta Emilia...female38.01534707731.3875NaNS

74574601Crosby, Capt. Edward Giffordmale70.011WE/P 573571.0000B22S

In?[4]:

test.sample(frac=1).head(3)

Out[4]:

PassengerIdPclassNameSexAgeSibSpParchTicketFareCabinEmbarked

24711392Drew, Mr. James Vivianmale42.0112822032.500NaNS

29111833Daly, Miss. Margaret Marcella Maggie""female30.0003826506.950NaNQ

58973Svensson, Mr. Johan Cervinmale14.00075389.225NaNS

2. Exploring missing data

Looks like there are missing (NaN) values among both datasets.

In?[5]:

train.info()

RangeIndex: 891 entries, 0 to 890

Data columns (total 12 columns):

PassengerId? ? 891 non-null int64

Survived? ? ? 891 non-null int64

Pclass? ? ? ? 891 non-null int64

Name? ? ? ? ? 891 non-null object

Sex? ? ? ? ? ? 891 non-null object

Age? ? ? ? ? ? 714 non-null float64

SibSp? ? ? ? ? 891 non-null int64

Parch? ? ? ? ? 891 non-null int64

Ticket? ? ? ? 891 non-null object

Fare? ? ? ? ? 891 non-null float64

Cabin? ? ? ? ? 204 non-null object

Embarked? ? ? 889 non-null object

dtypes: float64(2), int64(5), object(5)

memory usage: 83.6+ KB

In?[6]:

test.info()

RangeIndex: 418 entries, 0 to 417

Data columns (total 11 columns):

PassengerId? ? 418 non-null int64

Pclass? ? ? ? 418 non-null int64

Name? ? ? ? ? 418 non-null object

Sex? ? ? ? ? ? 418 non-null object

Age? ? ? ? ? ? 332 non-null float64

SibSp? ? ? ? ? 418 non-null int64

Parch? ? ? ? ? 418 non-null int64

Ticket? ? ? ? 418 non-null object

Fare? ? ? ? ? 417 non-null float64

Cabin? ? ? ? ? 91 non-null object

Embarked? ? ? 418 non-null object

dtypes: float64(2), int64(4), object(5)

memory usage: 36.0+ KB

Non-numeric data

Cabincolumn stores quite a lot of different qualitative values and has a relatively large amount of missing data.

In?[7]:

missing_val_df=pd.DataFrame(index=["Total","Unique Cabin","Missing Cabin"])forname,dfinzip(("Training data","Test data"),(train,test)):total=df.shape[0]unique_cabin=len(df["Cabin"].unique())missing_cabin=df["Cabin"].isnull().sum()missing_val_df[name]=[total,unique_cabin,missing_cabin]missing_val_df

Out[7]:

Training dataTest data

Total891418

Unique Cabin14877

Missing Cabin687327

We shall removeCabincolumns from our dataframes.

Also, we can excludePassengerIdfrom the training set, since IDs are unnecessary for classification.

In?[8]:

train.drop("PassengerId",axis=1,inplace=True)fordfintrain,test:df.drop("Cabin",axis=1,inplace=True)

Fill in missing rows inEmbarkedcolumn withS(Southampton Port), since it's the most frequent.

In?[9]:

non_empty_embarked=train["Embarked"].dropna()unique_values,value_counts=non_empty_embarked.unique(),non_empty_embarked.value_counts()X=range(len(unique_values))colors=["brown","grey","purple"]plt.bar(left=X,height=value_counts,color=colors,tick_label=unique_values)plt.xlabel("Port of Embarkation")plt.ylabel("Amount of embarked")plt.title("Bar plot of embarked in Southampton, Queenstown, Cherbourg")

Out[9]:

Quantitative data

Consider the distributions of passenger ages and fares (excluding NaN values).

In?[10]:

survived=train[train["Survived"]==1]["Age"].dropna()perished=train[train["Survived"]==0]["Age"].dropna()fig,(ax1,ax2)=plt.subplots(nrows=2,ncols=1)fig.set_size_inches(12,6)fig.subplots_adjust(hspace=0.5)ax1.hist(survived,facecolor='green',alpha=0.75)ax1.set(title="Survived",xlabel="Age",ylabel="Amount")ax2.hist(perished,facecolor='brown',alpha=0.75)ax2.set(title="Dead",xlabel="Age",ylabel="Amount")

Out[10]:

[,

,

]

In?[11]:

survived=train[train["Survived"]==1]["Fare"].dropna()perished=train[train["Survived"]==0]["Fare"].dropna()fig,(ax1,ax2)=plt.subplots(nrows=2,ncols=1)fig.set_size_inches(12,8)fig.subplots_adjust(hspace=0.5)ax1.hist(survived,facecolor='darkgreen',alpha=0.75)ax1.set(title="Survived",xlabel="Age",ylabel="Amount")ax2.hist(perished,facecolor='darkred',alpha=0.75)ax2.set(title="Dead",xlabel="Age",ylabel="Amount")

Out[11]:

[,

,

]

We can clean upAgeandFarecolumns filling in all of the missing values withmedianof all values in the training set.

In?[12]:

fordfintrain,test:df["Embarked"].fillna("S",inplace=True)forfeaturein"Age","Fare":df[feature].fillna(train[feature].mean(),inplace=True)

3. Feature engineering

Converting non-numeric columns

All of the non-numeric features exceptEmbarkedaren't particularly informative.

We shall convertEmbarkedandSexcolumns to numeric because we can't feed non-numeric columns into a Machine Learning algorithm.

In?[13]:

fordfintrain,test:forkey,valueinzip(("S","C","Q"),(0,1,2)):df.loc[df["Embarked"]==key,"Embarked"]=valueforkey,valueinzip(("female","male"),(0,1)):df.loc[df["Sex"]==key,"Sex"]=value

Map every unique ticket to numeric ID value.

In?[14]:

fordfintrain,test:ticket_mapping=dict()tickets=list()timer=0for_,sampleindf.iterrows():ifsample["Ticket"]notinticket_mapping:timer+=1ticket_mapping[sample["Ticket"]]=timertickets.append(timer)df["Ticket"]=tickets

Generating new features

SibSpSibSp+ParchParch+11gives the total number of people in a family.

In?[15]:

fordfintrain,test:df["FamilySize"]=df["SibSp"]+df["Parch"]+1

Extract the passengers' titles (Mr., Mrs., Rev., etc.) from their names.

In?[16]:

fordfintrain,test:titles=list()forrowindf["Name"]:surname,title,name=re.split(r"[,.]",row,maxsplit=2)titles.append(title.strip())df["Title"]=titles

In?[17]:

title=train["Title"]unique_values,value_counts=title.unique(),title.value_counts()X=range(len(unique_values))fig,ax=plt.subplots()fig.set_size_inches(18,10)ax.bar(left=X,height=value_counts,width=0.5,tick_label=unique_values)ax.set_xlabel("Title")ax.set_ylabel("Count")ax.set_title("Passenger titles")ax.grid(color='g',linestyle='--',linewidth=0.5)

Looks like some titles are very rare. Let's map them into related titles.

In?[18]:

fordfintrain,test:forkey,valueinzip(("Mr","Mrs","Miss","Master","Dr","Rev"),list(range(6))):df.loc[df["Title"]==key,"Title"]=valuedf.loc[df["Title"]=="Ms","Title"]=1fortitlein"Major","Col","Capt":df.loc[df["Title"]==title,"Title"]=6fortitlein"Mlle","Mme":df.loc[df["Title"]==title,"Title"]=7fortitlein"Don","Sir":df.loc[df["Title"]==title,"Title"]=8fortitlein"Lady","the Countess","Jonkheer":df.loc[df["Title"]==title,"Title"]=9test["Title"][414]=0

Finally, we get

In?[19]:

train.sample(frac=1).head(10)

Out[19]:

SurvivedPclassNameSexAgeSibSpParchTicketFareEmbarkedFamilySizeTitle

28503Stankovic, Mr. Ivan133.000000002558.6625110

77412Hocking, Mrs. Elizabeth (Eliza Needs)054.0000001360923.0000051

51211McGough, Mr. James Robert136.0000000042926.2875010

46803Scanlan, Mr. James129.699118003987.7250210

12903Ekstrom, Mr. Johan145.000000001216.9750010

85813Baclini, Mrs. Solomon (Latifa Qurban)024.0000000365819.2583141

17503Klasen, Mr. Klas Albin118.000000111607.8542030

82813McCormack, Mr. Thomas Joseph129.699118006427.7500210

60503Lindell, Mr. Edvard Bengtsson136.0000001049815.5500020

75803Theobald, Mr. Thomas Leonard134.000000005988.0500010

4. Prediction

Choose the most informative predictors and randomly split the training data.

In?[20]:

fromsklearn.model_selectionimporttrain_test_splitpredictors=["Pclass","Sex","Age","SibSp","Parch","Ticket","Fare","Embarked","FamilySize","Title"]X_train,X_test,y_train,y_test=train_test_split(train[predictors],train["Survived"])

Build a Random Forest model from the training set and evaluate the mean accuracy on the given test set.

In?[21]:

forest=RandomForestClassifier(n_estimators=100,criterion='gini',max_depth=5,min_samples_split=10,min_samples_leaf=5,random_state=0)forest.fit(X_train,y_train)print("Random Forest score:{0:.2}".format(forest.score(X_test,y_test)))

Random Forest score: 0.81

Examine the feature importances.

In?[22]:

plt.bar(range(len(predictors)),forest.feature_importances_)plt.xticks(range(len(predictors)),predictors,rotation='vertical')

Out[22]:

([,

,

,

,

,

,

,

,

,

],

)

Pick the best features and make a submission.

In?[23]:

predictors=["Title","Sex","Fare","Pclass","Age","Ticket"]clf=RandomForestClassifier(n_estimators=100,criterion='gini',max_depth=5,min_samples_split=10,min_samples_leaf=5,random_state=0)clf.fit(train[predictors],train["Survived"])prediction=clf.predict(test[predictors])submission=pd.DataFrame({"PassengerId":test["PassengerId"],"Survived":prediction})submission.to_csv("submission.csv",index=False)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末勾哩,一起剝皮案震驚了整個(gè)濱河市钠绍,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖跷睦,帶你破解...
    沈念sama閱讀 218,858評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異叛复,居然都是意外死亡宠叼,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門芜赌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來仰挣,“玉大人,你說我怎么就攤上這事缠沈”旌” “怎么了?”我有些...
    開封第一講書人閱讀 165,282評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵洲愤,是天一觀的道長颓芭。 經(jīng)常有香客問我,道長柬赐,這世上最難降的妖魔是什么亡问? 我笑而不...
    開封第一講書人閱讀 58,842評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上州藕,老公的妹妹穿的比我還像新娘束世。我一直安慰自己,他們只是感情好床玻,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,857評(píng)論 6 392
  • 文/花漫 我一把揭開白布毁涉。 她就那樣靜靜地躺著,像睡著了一般锈死。 火紅的嫁衣襯著肌膚如雪贫堰。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,679評(píng)論 1 305
  • 那天待牵,我揣著相機(jī)與錄音严嗜,去河邊找鬼。 笑死洲敢,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的茄蚯。 我是一名探鬼主播压彭,決...
    沈念sama閱讀 40,406評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼渗常!你這毒婦竟也來了壮不?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,311評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤皱碘,失蹤者是張志新(化名)和其女友劉穎询一,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體癌椿,經(jīng)...
    沈念sama閱讀 45,767評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡健蕊,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了踢俄。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片缩功。...
    茶點(diǎn)故事閱讀 40,090評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖都办,靈堂內(nèi)的尸體忽然破棺而出嫡锌,到底是詐尸還是另有隱情,我是刑警寧澤琳钉,帶...
    沈念sama閱讀 35,785評(píng)論 5 346
  • 正文 年R本政府宣布势木,位于F島的核電站,受9級(jí)特大地震影響歌懒,放射性物質(zhì)發(fā)生泄漏啦桌。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,420評(píng)論 3 331
  • 文/蒙蒙 一歼培、第九天 我趴在偏房一處隱蔽的房頂上張望震蒋。 院中可真熱鬧茸塞,春花似錦、人聲如沸查剖。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,988評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽笋庄。三九已至效扫,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間直砂,已是汗流浹背菌仁。 一陣腳步聲響...
    開封第一講書人閱讀 33,101評(píng)論 1 271
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留静暂,地道東北人济丘。 一個(gè)月前我還...
    沈念sama閱讀 48,298評(píng)論 3 372
  • 正文 我出身青樓,卻偏偏與公主長得像洽蛀,于是被迫代替她去往敵國和親摹迷。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,033評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • title: Optical Character Recognition (OCR)author: Marina ...
    4a87cc38dcbc閱讀 365評(píng)論 0 0
  • ``` /* * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject ...
    非專業(yè)碼農(nóng)閱讀 336評(píng)論 0 0
  • 轉(zhuǎn)至元數(shù)據(jù)結(jié)尾創(chuàng)建: 董瀟偉郊供,最新修改于: 十二月 23, 2016 轉(zhuǎn)至元數(shù)據(jù)起始第一章:isa和Class一....
    40c0490e5268閱讀 1,719評(píng)論 0 9
  • 《斐多》讀后感 斐多描繪的是蘇格拉底就義當(dāng)日與其友人關(guān)于正義和靈魂不朽進(jìn)行的深刻討論峡碉。 首先蘇格拉底認(rèn)為哲學(xué)家是最...
    馬嘯閱讀 3,381評(píng)論 0 1
  • 最近項(xiàng)目中遇到需要保存上傳失敗的圖片,通過匯總所有上傳失敗圖片提供一個(gè)展示列表選擇性重發(fā)的需求驮审, 所以需要...
    木馬sun閱讀 2,057評(píng)論 0 0