kaggle竞赛题 泰坦尼克号生存者预测

由于各种不可抗力,笔者在学习完numpy,pandas,和一些sklearn知识后,不得不开始泰坦尼克号生存着预测。

但由于经验不足,掌握的知识不足,所以跟着知乎上一位大佬的一篇泰坦尼克号教学一步一步的写,以下为这几天所编写的数据代码

import numpy as np

import pandas as pd

#读取训练数据集
train=pd.read_csv('D:/Titanic/train.csv')
#读取测试数据集
test=pd.read_csv('D:/Titanic/test.csv')
print('训练数据集:',train.shape)

print('测试数据集:',test.shape)

#合并数据集,以方便对两数据集进行清洗
full=train.append(test,ignore_index=True)

print('合并后的数据集',full.shape)

#查看数据

full.head()

#获取数据类型统计信息

full.describe()

#查看每一列数据的数据类型以及总数,来确定缺失值

full.info()

'''AGE和FARE都存在缺失值,且数据类型都为浮点型,可以使用平均值填充的办法来填充缺失值,其中,fillna表示填充方法,mean表示使用平均值填充'''
#年龄
full['Age']=full['Age'].fillna(full['Age'].mean())

full['Fare']=full['Fare'].fillna(full['Fare'].mean())

#由于客舱号缺失较为严重,查看客舱号数据

full['Cabin'].head

#由于缺失数据过多,无规律可循,直接填充数据为U表示未知(Unknown)

full['Cabin']=full['Cabin'].fillna('U')

'''查看登船航空
    出发地点:s=南安普顿
    途径地点1:c=瑟堡
    途径地点2:q=皇后镇'''

full['Embarked'].head()

#统计各个地点出发的次数
from collections import Counter

print(Counter(full['Embarked']))

#由上可知,Embarked(登船航口)有两个缺失值,由于缺失值少,可用最频繁出现的值来代替:S=南安普顿

full['Embarked']=full['Embarked'].fillna('S')

#使用info确认缺失值是否处理完毕

full.info()

'''将性别映射为数值
男对应为1
女对应为0'''
sex_mapDict={'male':1,
            'female':0}
#map函数:对于series每个数据应用自定义函数计算
full['Sex']=full['Sex'].map(sex_mapDict)

full.head()

#提取登船航口特征值
#查看该类数据类型

full['Embarked'].head()

#存放提取后的特征
embarkedDF=pd.DataFrame()
#使用get_dummies进行one_hot编码,列名前缀为Embarked
embarkedDF=pd.get_dummies(full['Embarked'],prefix='Embarked')

embarkedDF.head()

#添加one-hot编码产生的虚拟变量(dummy variables)到泰坦尼克号数据集full
full=pd.concat([full,embarkedDF],axis=1)
'''因为已使用登船航口进行了one-hot编码产生虚拟变量(dummy variables)
所以这里把登船航口删除'''
full.drop('Embarked',axis=1,inplace=True)

full.head()

#存放提取后的特征
pclassDF=pd.DataFrame()
#使用get_dummies进行one_hot编码,列名前缀为pclass
pclassDF=pd.get_dummies(full['Pclass'],prefix='Pclass')

pclassDF.head()

#添加one-hot编码产生的虚拟变量到泰坦尼克号数据集full
full=pd.concat([full,pclassDF],axis=1)
#删除客舱等级这一列
full.drop('Pclass',axis=1,inplace=True)

full.head()

#从姓名中提取特征值

full['Name'].head()

#split()通过制定分隔符对字符串进行切片
def getTitle(name):
    str1=name.split(',')[1]
    str2=str1.split('.')[0]
    str3=str2.strip()
    return str3
#存放提取后的特征
titleDF=pd.DataFrame()
#map函数:对series每个数据应用自定义函数运算
titleDF['Title']=full['Name'].map(getTitle)

titleDF.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',
    'Mile':'Miss',
    'Mr':'Mr',
    'Mrs':'Mrs',
    'Miss':'Miss',
    'Master':'Master',
    'Lady':'Royalte',
}
#map函数:对series每一个数据应用自定义函数运算
titleDF=pd.get_dummies(titleDF['Title'])

titleDF.head()

full=pd.concat([full,titleDF],axis=1)
full.drop('Name',axis=1,inplace=True)

full.head()

full['Cabin'].head()

cabinDF=pd.DataFrame()
full['Cabin']=full['Cabin'].map(lambda c:c[0])
cabinDF=pd.get_dummies(full['Cabin'],prefix='Cabin')

cabinDF.head()

full=pd.concat([full,cabinDF],axis=1)
full.drop('Cabin',axis=1,inplace=True)

full.head()

#存放家庭信息
familyDF=pd.DataFrame()
familyDF['Familysize']=full['SibSp']+full['Parch']+1
familyDF['Family_Single']=familyDF['Familysize'].map(lambda s:1 if s==1 else 0)
familyDF['Family_Small']=familyDF['Familysize'].map(lambda s:1 if 2<=s<=4 else 0)
familyDF['Family_Large']=familyDF['Familysize'].map(lambda s:1 if s>=5 else 0)

familyDF.head()

full=pd.concat([full,familyDF],axis=1)

full.head()

ageDF=pd.DataFrame()
ageDF['Child']=full['Age'].map(lambda a:1 if 0<a<=6 else 0)
ageDF['Teenager']=full['Age'].map(lambda a:1 if 6<a<18 else 0)
ageDF['Youth']=full['Age'].map(lambda a:1 if 18<=a<=40 else 0)
ageDF['Middle_age']=full['Age'].map(lambda a:1 if 40<a<=60 else 0)
ageDF['Older']=full['Age'].map(lambda a:1 if 60<a else 0)

ageDF.head()

full=pd.concat([full,ageDF],axis=1)
full.drop('Age',axis=1,inplace=True)

full.head()

full.shape

#相关矩阵
corrDF=full.corr()

corrDF

corrDF['Survived'].sort_values(ascending=False)

#特征选择
full_X=pd.concat([
    titleDF,
    pclassDF,
    familyDF,
    full['Fare'],
    full['Sex'],
    cabinDF,
    embarkedDF
],axis=1)

full_X.head()

#模型构建

#原始数据共891行
sourceRow=891
source_X=full_X.loc[0:sourceRow-1,:]
source_y=full.loc[0:sourceRow-1,'Survived']
pred_X=full_X.loc[sourceRow:,:]

print('原始数据集有多少行:',source_X.shape[0])

print('预测数据集有多少行:',pred_X.shape[0])

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=0.8)
print('原始数据集特征',source_X.shape,
     '训练数据集特征',train_X.shape,
     '测试数据集特征',test_X.shape)
print('原始数据集特征',source_y.shape,
     '训练数据集特征',train_y.shape,

     '测试数据集特征',test_y.shape)

#查看原始数据集标签

source_y.head()

#1.导入算法

from sklearn.linear_model import LogisticRegression

#2.创建模型:逻辑回归

model=LogisticRegression()

#3.训练模型

model.fit(train_X,train_y)

#分类问题,source得到的是模型正确率

model.score(test_X,test_y)

#使用机器学习模型,对预测数据集中的生存情况进行预测
pred_y=model.predict(pred_X)
pred_y=pred_y.astype(int)
passenger_id=full.loc[sourceRow:,'PassengerId']
predDF=pd.DataFrame({'PassengerId':passenger_id,'Survived':pred_y})
predDF.shape

predDF.head()

#保存结果

predDF.to_csv('D:/Titanic/titanic_pred.csv',index=False)




结果如下图

kaggle竞赛题 泰坦尼克号生存者预测



最后,附上使用教程的链接

https://zhuanlan.zhihu.com/p/35120173









真难!!!!