泰坦尼克号乘客生存预测(XGBoost)

泰坦尼克号乘客生存预测(XGBoost)

1. 案例背景

泰坦尼克号沉没是历史上最臭名昭着的沉船之一。1912年4月15日,在她的处女航中,泰坦尼克号在与冰山相撞后沉没,在2224名乘客和机组人员中造成1502人死亡。这场耸人听闻的悲剧震惊了国际社会,并为船舶制定了更好的安全规定。 造成海难失事的原因之一是乘客和机组人员没有足够的救生艇。尽管幸存下沉有一些运气因素,但有些人比其他人更容易生存,例如妇女,儿童和上流社会。 在这个案例中,我们要求您完成对哪些人可能存活的分析。特别是,我们要求您运用机器学习工具来预测哪些乘客幸免于悲剧

案例https://www.kaggle.com/c/titanic/overview

我们提取到的数据集中的特征包括票的类别是否存活,乘坐班次,年龄,登陆home.dest,房间,船和性别等

这是一个常用的数据,给大家个链接,可以去该链接下载数据集:http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt

在这里插入图片描述
上面数据下载可能需要外网访问,本地访问连接超时。

第二种下载数据集方式:

https://datahub.csail.mit.edu/download/jander/historic/file/titanic.csv

亲测有效

在这里插入图片描述

经过观察数据得到:

  • 1 乘坐班是指乘客班(1,2,3),是社会经济阶层的代表。
  • 2 其中age数据存在缺失。

2. 步骤分析

  • 1.获取数据
  • 2.数据基本处理
    • 2.1 确定特征值,目标值
    • 2.2 缺失值处理
    • 2.3 数据集划分
  • 3.特征工程(字典特征抽取)
  • 4.机器学习(决策树)
  • 5.模型评估

3. 代码实现

  • 导入需要的模块
import pandas as pd
import numpy as np
from sklearn.feature_extraction import DictVectorizer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_graphviz
  • 1.获取数据
# 1、获取数据
titan = pd.read_csv("http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt")

or

titan = pd.read_csv("./data/titanic.csv")

在这里插入图片描述

titan.describe()

在这里插入图片描述

  • 2.数据基本处理

    • 2.1 确定特征值,目标值
x = titan[["pclass", "age", "sex"]]
y = titan["survived"]

在这里插入图片描述

  • 2.2 缺失值处理
# 缺失值需要处理,将特征当中有类别的这些特征进行字典特征抽取
x['age'].fillna(x['age'].mean(), inplace=True)
  • 2.3 数据集划分
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=22)
  • 3.特征工程(字典特征抽取)

特征中出现类别符号,需要进行one-hot编码处理(DictVectorizer)

x.to_dict(orient="records")需要将数组特征转换成字典数据

# 对于x转换成字典数据x.to_dict(orient="records")
# [{"pclass": "1st", "age": 29.00, "sex": "female"}, {}]

transfer = DictVectorizer(sparse=False)

x_train = transfer.fit_transform(x_train.to_dict(orient="records"))
x_test = transfer.fit_transform(x_test.to_dict(orient="records"))

在这里插入图片描述

4.xgboost模型训练和模型评估

# 模型初步训练 
from xgboost import XGBClassifier 
xg = XGBClassifier() 

xg.fit(x_train, y_train) 
xg.score(x_test, y_test)
# 针对max_depth进⾏模型调优 
depth_range = range(10) 
score = [] 
for i in depth_range: 
	xg = XGBClassifier(eta=1, gamma=0, max_depth=i) 
	xg.fit(x_train, y_train) 
	s = xg.score(x_test, y_test) 
	print(s) 
	score.append(s)
# 结果可视化 
import matplotlib.pyplot as plt 
plt.plot(depth_range, score) 
plt.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chaser&upper

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值