泰坦尼克号人员预测模型
运用python实现泰坦尼克号的人员预测,机器学习,数据挖掘
前言
以泰坦尼克号数据为对象,结合当时背景,理解数据和认识数据,掌握数据的初步探索,具体包括缺失值的处理、数据间的相关性分析等。掌握属性变换、特征生成、特征选择与主成分分析处理方法,生成适合模型算法来预测人员生还情况
实验过程
字段解读
每个字段的意义如下。
PassengerId :乘客ID
Pclass:乘客等级(1/2/3等舱位)(属性代表船舱等级,1-一等舱,2-二等舱,3-三等舱,从一定程度上反应了这个乘客经济情况和社会地位。)
Name:乘客姓名
Sex:性别
Age:年龄
SibSp:堂兄弟/妹个数
Parch:父母与小孩个数
Ticket:船票信息(字母与数字具体代表什么信息,需要猜测分析判断)
Fare:票价
Cabin:客舱
Embarked:登船港口
Survived:乘客是否获救
使用jupyter-notebook实现的完整过程:
导入所有的第三方库:
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.model_selection import train_test_split
from sklearn.ensemble import VotingClassifier, RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier as KNN
from sklearn import svm
from sklearn import tree
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
from pylab import *
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
数据理解以及数据分析:
# 导入数据
titanic = pd.read_csv(r'D:\Pycharm工程\MYPYTHON2\Titanic\train.csv')
# pd.set_option('display.max_rows', 500) # 展示区域最多不超过500行
# pd.set_option('display.max_columns', 15) #
pd.set_option('display.width', 130) # 展示前面20行
print(titanic.head(20))
# 调用isnull()方法来查看train.csv数据集的缺失程度
pd.isnull(titanic).sum()
# 可以查看每一个数值属性的平均值、方差、最大值、最小值、四分位数等
titanic.describe()
# (1)Age,对于Age属性我们采用平均值来填补空缺值
# (2)Carbine由于它的空缺值太多,我们这里用一个’NO’来填充Carbine的空缺值
# (3)Embarked 我们采取众数来填充
titanic['Age'] = titanic['Age'].fillna(titanic['Age'].median())
titanic['Cabin'] = titanic['Cabin'].fillna('NO')
titanic['Embarked'] = titanic['Embarked'].fillna('S')
pd.isnull(titanic).sum()
# 设置画布的大小
fig = plt.figure(figsize=(15,10))
# # 获救人数分布,1为获救
plt.subplot2grid((1, 3), (0, 0))
titanic.Survived.value_counts().plot(kind='bar') # 柱状图
plt.title("获救情况 (1为获救)") # 标签
plt.ylabel("人数") # y轴
plt.xlabel("Survived") # x轴
# 乘客等级人数分布
plt.subplot2grid((1, 3), (0, 1))
titanic.Pclass.value_counts().plot(kind="bar")
plt.title("乘客等级分布")
plt.ylabel("人数")
plt.xlabel("Pclass")
# 各登船口岸上船人数分布
plt.subplot2grid((1, 3), (0, 2))
titanic.Embarked.value_counts().plot(kind='bar')
plt.title("各登船口岸上船人数")
plt.ylabel("人数")
plt.xlabel("Embarked")
结果分析:
从分布图可以看出,没有获救的的人数比重大、乘客等级分布里面、三等舱的人数最多、登船口岸上船人数最多的是S口岸
# 乘客等级与获救的关系
Survived_0 = titanic.Pclass[titanic.Survived == 0].value_counts()
Survived_1 = titanic.Pclass[titanic.Survived == 1].value_counts()
df = pd.DataFrame({
'获救': Survived_1, '未获救': Su