Titanic数据分析和建模

TITANIC DATA PREDICTATION

ok, 这是我自己做的titanic建模,主要过程是:
探索数据:
看下数据维度,数据简单统计
数据类型(数值型,对象型)、
是否有空值,多少空值
用matplotlib绘图探索数据
数据预处理:
填充空值数据
转换分类变量
数据标准化,可在建模时转换
feature很多时要降维 PCA SVD
数据建模:

模型评估:
分类:precision/recall ,f1 score, pr tradeoff图
回归: MAE/ MSE/ R平方

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline

import dataset

train = pd.read_csv("E:/figure/titanic/train.csv")
test = pd.read_csv("E:/figure/titanic/test.csv")
train.head()
Paste_Image.png

•Survived: Outcome of survival (0 = No; 1 = Yes)
•Pclass: Socio-economic class (1 = Upper class; 2 = Middle class; 3 = Lower class)
•Name: Name of passenger
•Sex: Sex of the passenger
•Age: Age of the passenger (Some entries contain NaN)
•SibSp: Number of siblings and spouses of the passenger aboard
•Parch: Number of parents and children of the passenger aboard
•Ticket: Ticket number of the passenger
•Fare: Fare paid by the passenger
•Cabin Cabin number of the passenger (Some entries contain NaN)
•Embarked: Port of embarkation of the passenger (C = Cherbourg; Q = Queenstown; S = Southampton)

explore dataset

print(train.shape)
print(test.shape)
(891, 12)
(418, 11)
train.dtypes
PassengerId      int64
Survived         int64
Pclass           int64
Name            object
Sex             object
Age            float64
SibSp            int64
Parch            int64
Ticket          object
Fare           float64
Cabin           object
Embarked        object
dtype: object
test.dtypes
PassengerId      int64
Pclass           int64
Name            object
Sex             object
Age            float64
SibSp            int64
Parch            int64
Ticket          object
Fare           float64
Cabin           object
Embarked        object
dtype: object
train.describe()
Paste_Image.png

merge training set and testing set

full =pd.merge(train,test,how="outer")
full.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1309 entries, 0 to 1308
Data columns (total 12 columns):
PassengerId    1309 non-null float64
Survived       891 non-null float64
Pclass         1309 non-null float64
Name           1309 non-null object
Sex            1309 non-null object
Age            1046 non-null float64
SibSp          1309 non-null float64
Parch          1309 non-null float64
Ticket         1309 non-null object
Fare           1308 non-null float64
Cabin          295 non-null object
Embarked       1307 non-null object
dtypes: float64(7), object(5)
memory usage: 107.4+ KB
#check missing value

full.isnull().sum()
PassengerId       0
Survived        418
Pclass            0
Name              0
Sex               0
Age             263
SibSp             0
Parch             0
Ticket            0
Fare              1
Cabin          1014
Embarked          2
dtype: int64
print(full["Pclass"].value_counts(),"\n",full["Sex"].value_counts(),"\n",full["Embarked"].value_counts())
3    709
1    323
2    277
Name: Pclass, dtype: int64 
 male      843
female    466
Name: Sex, dtype: int64 
 S    914
C    270
Q    123
Name: Embarked, dtype: int64

data preprocessing

#dummy variable
full=pd.get_dummies(full,columns=["Pclass","Embarked","Sex"])
#drop variable
full=full.drop(["Cabin","PassengerId","Name","Ticket"],axis=1)
full.dtypes
Survived      float64
Age           float64
SibSp         float64
Parch         float64
Fare          float64
Pclass_1.0    float64
Pclass_2.0    float64
Pclass_3.0    float64
Embarked_C    float64
Embarked_Q    float64
Embarked_S    float64
Sex_female    float64
Sex_male      float64
dtype: object
#replace "Age" missing value to -999
full["Age"].fillna(-999,inplace =True)
full["Age"]=full["Age"].astype(int)
full["Age"].hist(bins=10,range=(0,100))
<matplotlib.axes._subplots.AxesSubplot at 0x7ba3750>
Paste_Image.png
#replace nan value with mean
full["Fare"].loc[full["Fare"].isnull()]=full["Fare"].mean()
C:\Anaconda3\lib\site-packages\pandas\core\indexing.py:117: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)
full.isnull().sum()
Survived      418
Age             0
SibSp           0
Parch           0
Fare            0
Pclass_1.0      0
Pclass_2.0      0
Pclass_3.0      0
Embarked_C      0
Embarked_Q      0
Embarked_S      0
Sex_female      0
Sex_male        0
dtype: int64
trainset =full.iloc[:891,]
testset=full.iloc[891:,]
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import f1_score
from sklearn.metrics import precision_recall_curve
x_train = trainset.drop("Survived",axis=1)
y_train = trainset["Survived"]
x_test = testset.drop("Survived",axis=1)
#logistic regression
logreg =LogisticRegression()
logreg.fit(x_train,y_train)
y_predlog = logreg.predict(x_test)
logreg.score(x_train,y_train)
0.7991021324354658

print f1 score and plot pr curve(it's on trainset)

f1_score(y_train,logreg.predict(x_train))
0.72248062015503878
prob = logreg.predict_proba(x_train)
precision, recall, thresholds = precision_recall_curve(y_train,prob[:,1])
plt.plot(precision,recall)
plt.xlabel("precision")
plt.ylabel("recall")
<matplotlib.text.Text at 0xbdc1f50>
Paste_Image.png
from sklearn.metrics import classification_report
print(classification_report(y_train,logreg.predict(x_train),target_names=["unsurvived","survived"]))
             precision    recall  f1-score   support

 unsurvived       0.81      0.87      0.84       549
   survived       0.77      0.68      0.72       342

avg / total       0.80      0.80      0.80       891
#SVC
svc =SVC()
svc.fit(x_train,y_train)
y_predsvc = svc.predict(x_test)
svc.score(x_train,y_train)
0.88776655443322106
#rrandom forest
rf = RandomForestClassifier()
rf.fit(x_train,y_train)
y_predrf = rf.predict(x_test)
rf.score(x_train,y_train)
0.97081930415263751

**feature importances

importanted = rf.feature_importances_
print(importanted)
plt.bar(range(x_train.shape[1]),importanted)
plt.xticks(range(x_train.shape[1]),tuple(x_train.columns),rotation=60)
[ 0.23063155  0.04861788  0.04546831  0.28729027  0.02962199  0.01930221
  0.03710312  0.00726902  0.00953395  0.0125742   0.18180419  0.09078331]





([<matplotlib.axis.XTick at 0xd1caed0>,
  <matplotlib.axis.XTick at 0xd1cafb0>,
  <matplotlib.axis.XTick at 0xd1c6210>,
  <matplotlib.axis.XTick at 0xd201630>,
  <matplotlib.axis.XTick at 0xd201bf0>,
  <matplotlib.axis.XTick at 0xd2061d0>,
  <matplotlib.axis.XTick at 0xd206790>,
  <matplotlib.axis.XTick at 0xd206d50>,
  <matplotlib.axis.XTick at 0xd209330>,
  <matplotlib.axis.XTick at 0xd2098f0>,
  <matplotlib.axis.XTick at 0xd209eb0>,
  <matplotlib.axis.XTick at 0xd20f490>],
 <a list of 12 Text xticklabel objects>)
Paste_Image.png

from the pic, you can see "age", "fare"and "sex" are more important variance.
There must be some relation between fare and Pclass, do that later.

#Gaussian NB
nb = GaussianNB()
nb.fit(x_train,y_train)
y_prednb=nb.predict(x_test)
nb.score(x_train,y_train)
0.78114478114478114
#standard 
from sklearn.preprocessing import StandardScaler
std = StandardScaler()
std.fit(x_train)
x_train_std = std.transform(x_train)
x_test_std = std.transform(x_test)
#train on this later
#save prediction as csv
#submission = pd.DataFrame({"PassengerId":test["PassengerId"],"Survived":y_predlog})
#submission.to_csv("titanicpred.csv",index=False)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,393评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,790评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,391评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,703评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,613评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,003评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,507评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,158评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,300评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,256评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,274评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,984评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,569评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,662评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,899评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,268评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,840评论 2 339

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,281评论 0 23
  • 思路 开始的时候,我想的是将图片直接加载到ImageView上,然后通过 scrollTo()方法滑动内容,从而达...
    jacky123阅读 924评论 0 0
  • 文│乔其 导语:自我感觉行文方式有一丢丢“飞机坏品味樱桃文”的味道。与之前喜欢的风格好像不大一样。现在觉得文字就该...
    叫我其其阅读 304评论 0 0
  • 我是一只猫 露出了蜜汁微笑 你也可以叫我 蒙娜丽猫
    牛爸牛牛的爸爸阅读 366评论 0 0
  • 我们都是上帝撒下的一粒种子,有了阳光和雨露的滋润,就会茁壮成长。我们拥有健康的身体,能感受大自然的美丽与神奇...
    小冷小姐阅读 334评论 0 2