简介

Titanic是Kaggle竞赛的一道入门题,参赛者需要根据旅客的阶级、性别、年龄、船舱种类等信息预测其是否能在海难中生还,详细信息可以参看https://www.kaggle.com/,本文的分析代码也取自 kaggle 中该竞赛的 kernal。

数据介绍

给出的数据格式如下:

PassengerId,Survived,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked

1,0,3,"Braund, Mr. Owen Harris",male,22,1,0,A/5 21171,7.25,,S

2,1,1,"Cumings, Mrs. John Bradley (Florence Briggs Thayer)",female,38,1,0,PC 17599,71.2833,C85,C

数据项的含义如下:

PassengerId:乘客ID

Survived:是否生还,0表示遇难,1表示生还

Pclass:阶级,1表示最高阶级,3最低

Name:姓名

Sex:性别

Age:年龄

SibSp:同乘船的兄弟姐妹的数量

Parch:是否有配偶同乘,1表示是

Ticket:船票编号

Fare:恐惧指数

Cabin:船舱号

Embarked:登船港口

问题分析

这是一个比较典型的基于特征的分类问题,根据一般的数据处理流程可以将问题的求解分解成为以下步骤:

数据预处理

读取数据,在本文代码中使用了 python 的 pandas 包管理数据结构

特征向量化,在本文代码中将性别和登船港口特征转成向量化表示

处理残缺数据,在本文代码中将残缺年龄用平均年龄表示,残缺的登船港口用频繁项表示

扔掉多余项,姓名、ID、舱号、票号在本问题中被认为是对分类没有帮助的信息,扔掉了这些特征项

数据训练

在本文代码中使用了 sklearn 中的随机森林进行分类,随机森林每次随机选取若干特征和数据项生成决策树,最后采用投票的方式来生成预测结果,本文代码中将第一列作为分类项,后n列作为特征项,随机生成100棵决策树对数据进行训练

预测并生成结果

代码实现

import pandas as pd

import numpy as np

import csv as csv

from sklearn.ensemble import RandomForestClassifier

# Data cleanup

# TRAIN DATA

train_df = pd.read_csv('train.csv', header=0) # Load the train file into a dataframe

# I need to convert all strings to integer classifiers.

# I need to fill in the missing values of the data and make it complete.

# female = 0, Male = 1

train_df['Gender'] = train_df['Sex'].map( {'female': 0, 'male': 1} ).astype(int)

# Embarked from 'C', 'Q', 'S'

# Note this is not ideal: in translating categories to numbers, Port "2" is not 2 times greater than Port "1", etc.

# All missing Embarked -> just make them embark from most common place

if len(train_df.Embarked[ train_df.Embarked.isnull() ]) > 0:

train_df.Embarked[ train_df.Embarked.isnull() ] = train_df.Embarked.dropna().mode().values

Ports = list(enumerate(np.unique(train_df['Embarked']))) # determine all values of Embarked,

Ports_dict = { name : i for i, name in Ports } # set up a dictionary in the form Ports : index

train_df.Embarked = train_df.Embarked.map( lambda x: Ports_dict[x]).astype(int) # Convert all Embark strings to int

# All the ages with no data -> make the median of all Ages

median_age = train_df['Age'].dropna().median()

if len(train_df.Age[ train_df.Age.isnull() ]) > 0:

train_df.loc[ (train_df.Age.isnull()), 'Age'] = median_age

# Remove the Name column, Cabin, Ticket, and Sex (since I copied and filled it to Gender)

train_df = train_df.drop(['Name', 'Sex', 'Ticket', 'Cabin', 'PassengerId'], axis=1)

# TEST DATA

test_df = pd.read_csv('test.csv', header=0) # Load the test file into a dataframe

# I need to do the same with the test data now, so that the columns are the same as the training data

# I need to convert all strings to integer classifiers:

# female = 0, Male = 1

test_df['Gender'] = test_df['Sex'].map( {'female': 0, 'male': 1} ).astype(int)

# Embarked from 'C', 'Q', 'S'

# All missing Embarked -> just make them embark from most common place

if len(test_df.Embarked[ test_df.Embarked.isnull() ]) > 0:

test_df.Embarked[ test_df.Embarked.isnull() ] = test_df.Embarked.dropna().mode().values

# Again convert all Embarked strings to int

test_df.Embarked = test_df.Embarked.map( lambda x: Ports_dict[x]).astype(int)

# All the ages with no data -> make the median of all Ages

median_age = test_df['Age'].dropna().median()

if len(test_df.Age[ test_df.Age.isnull() ]) > 0:

test_df.loc[ (test_df.Age.isnull()), 'Age'] = median_age

# All the missing Fares -> assume median of their respective class

if len(test_df.Fare[ test_df.Fare.isnull() ]) > 0:

median_fare = np.zeros(3)

for f in range(0,3): # loop 0 to 2

median_fare[f] = test_df[ test_df.Pclass == f+1 ]['Fare'].dropna().median()

for f in range(0,3): # loop 0 to 2

test_df.loc[ (test_df.Fare.isnull()) & (test_df.Pclass == f+1 ), 'Fare'] = median_fare[f]

# Collect the test data's PassengerIds before dropping it

ids = test_df['PassengerId'].values

# Remove the Name column, Cabin, Ticket, and Sex (since I copied and filled it to Gender)

test_df = test_df.drop(['Name', 'Sex', 'Ticket', 'Cabin', 'PassengerId'], axis=1)

# The data is now ready to go. So lets fit to the train, then predict to the test!

# Convert back to a numpy array

train_data = train_df.values

test_data = test_df.values

print 'Training...'

forest = RandomForestClassifier(n_estimators=100)

forest = forest.fit( train_data[0::,1::], train_data[0::,0] )

print 'Predicting...'

output = forest.predict(test_data).astype(int)

predictions_file = open("myfirstforest.csv", "wb")

open_file_object = csv.writer(predictions_file)

open_file_object.writerow(["PassengerId","Survived"])

open_file_object.writerows(zip(ids, output))

predictions_file.close()

print 'Done.'

后续思考

这是一个比较简单流程也较为完整的解决方案,但是也存在一些问题,比如

没有对测试结果的准确率和召回率进行评估

模型的参数选择是否可以进一步调整取得更好的效果?

如果采用一些集成学习的办法效果会不会进一步提升?

python泰坦尼克号数据预测_使用python预测泰坦尼克号生还相关推荐

  1. python大数据论坛_干货 | Python+大数据计算平台,PyODPS架构手把手教你搭建

    数据分析和机器学习 大数据基本都是建立在Hadoop系统的生态上的,其实一个Java的环境.很多人喜欢用Python和R来进行数据分析,但是这往往对应一些小数据的问题,或者本地数据处理的问题.如何将二 ...

  2. python大数据免费_用python做大数据

    不学Python迟早会被淘汰?Python真有这么好的前景? 最近几年Python编程语言在国内引起不小的轰动,有超越Java之势,本来在美国这个编程语言就是最火的,应用的非常非常的广泛,而Pytho ...

  3. python爬虫数据可视化_适用于Python入门者的爬虫和数据可视化案例

    本篇文章适用于Python小白的教程篇,如果有哪里不足欢迎指出来,希望对你帮助. 本篇文章用到的模块: requests,re,os,jieba,glob,json,lxml,pyecharts,he ...

  4. python串口数据绘图_使用Python串口实时显示数据并绘图的例子

    使用pyserial进行串口传输 一.安装pyserial以及基本用法 在cmd下输入命令pip install pyserial 注:升级pip后会出现 "'E:\Anaconda3\Sc ...

  5. python两行数据相加_小白python入门基础——Python安装教程与特色介绍

    简介 Python语言是少有的一种可以称得上即简单又功能强大的编程语言.你将惊喜地发现Python语言是多么地简单,它注重的是如何解决问题而不是编程语言的语法和结构. Python的官方介绍是: Py ...

  6. python交互式数据可视化_基于Python实现交互式数据可视化的工具,你用过几种?...

    作者:Alark Joshi 翻译:陈雨琳 来源:数据派THU(ID:DatapiTHU) 我教授了一门关于数据可视化的数据科学硕士课程.我们的数据科学硕士项目是一个为期15个月的强化项目,这个项目已 ...

  7. python证券交易数据接口_实战 | Python获取股票交易数据

    项目介绍 看到标题大家的第一反应估计是怎么用爬虫来获取股票交易数据,要获取股票交易数据确实是需要用爬虫没错,不过还有比使用爬虫更加方便的方式.今天要给大家介绍的是一个专门用来获取国内股票交易数据的开源 ...

  8. python简历数据提取_提取python简介

    书籍:掌握Python的网络和安全 Mastering Python for Networking and Security - 2018.pdf 简介 掌握Python的网络和安全 掌握Python ...

  9. python进行数据查询_使用Python实现NBA球员数据查询小程序功能

    本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理. 以下文章来源于早起Python ,作者投稿君 一.前言 有时将代码转成带有界面的程序,会极大地方便 ...

  10. python收集数据程序_用Python挖掘Twitter数据:数据采集

    原标题:用Python挖掘Twitter数据:数据采集 作者:Marco Bonzanini 翻译:数盟 这是7部系列中的第1部分,注重挖掘Twitter数据以用于各种案例.这是第一篇文章,专注于数据 ...

最新文章

  1. 固态器件理论(5)PN结
  2. Hackerrank - The Grid Search
  3. npm run dev 和 npx webpack-dev-server
  4. 基于OMAPL138的字符驱动_GPIO驱动AD9833(三)之中断申请IRQ
  5. Manjaro下显卡相关的命令搜集
  6. c# 从一组数中随机抽取一定个数_C#产生指定范围随机数的几种方法-亮术网
  7. 交叉编译iproute2
  8. 斯坦福大学深度学习公开课cs231n学习笔记(3)最优化方法:梯度下降
  9. 实现安卓中TextView,EditText中数字的数码管字体显示
  10. 如何快速辨识四位数字贴片电阻阻值
  11. Insyde uefi 隐藏设置_vivo手机怎么隐藏应用 vivo手机怎样把软件隐藏起来?
  12. Python中的角度转换功能
  13. 致我们的青春,一个敬礼。
  14. Android 节操视频播放器jiecaovideoplayer使用
  15. 误传了数千年的几个名句
  16. 【OI做题记录】【BZOJ】【Usaco2008 Mar】土地购买
  17. deepstream系列gst-shark工具分析插件效率
  18. 7-7 到底是不是太胖了(10 分)
  19. 毫米波雷达传感技术方案,爱希ISEE人体感应器,智能感应人体存在控制应用
  20. 洛谷 P5266 【深基17.例6】学籍管理

热门文章

  1. python经典一百道习题(转自奶酪博客)
  2. JSP 简介(转载)
  3. Delphi中动态调用DLL的方法
  4. 《Cracking the Coding Interview》——第11章:排序和搜索——题目7
  5. android:在ViewPager中使用Button
  6. jQuery的radio,checkbox,select操作
  7. 关于DataAccess Application block
  8. C++学习——string
  9. linux的基础知识——全局变量异步I/O
  10. linux基础知识——CPU相关知识