1.数据集简介

此数据集一共有891条数据,数据内容如下,每列表示的意义如下:

乘客ID 是否幸存 舱位等级 姓名 性别 年龄 一同上船的兄弟姐妹 父母和小孩数目 船号 船价 船仓号 登录地点
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
3 1 3 Heikkinen, Miss. Laina female 26 0 0 STON/O2. 3101282 7.925   S
4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35 1 0 113803 53.1 C123 S
5 0 3 Allen, Mr. William Henry male 35 0 0 373450 8.05   S

2.缺失值处理:

查看数据后,发现在Age列,有部分值缺失,将缺失值用中位数进行填充

titanic = pandas.read_csv("titanic_train.csv")
print(titanic.head(5))  # 显示前5条信息
# pandas.set_option('display.max_columns', None)  # 显示所有列
# pandas.set_option('display.max_rows', None)  # 显示所有行# 对Age列进行缺失值titanic["Age"].fillna 填充此列中位数titanic["Age"].median()
titanic["Age"] = titanic["Age"].fillna(titanic["Age"].median())
print(titanic.describe())  # 显示统计信息

填充完之后,初步显示模型的统计信息,主要包括数量、均值、标准差、最小值、4分位数、最大值。

      PassengerId    Survived      Pclass         Age       SibSp  \
count   891.000000  891.000000  891.000000  891.000000  891.000000
mean    446.000000    0.383838    2.308642   29.361582    0.523008
std     257.353842    0.486592    0.836071   13.019697    1.102743
min       1.000000    0.000000    1.000000    0.420000    0.000000
25%     223.500000    0.000000    2.000000   22.000000    0.000000
50%     446.000000    0.000000    3.000000   28.000000    0.000000
75%     668.500000    1.000000    3.000000   35.000000    1.000000
max     891.000000    1.000000    3.000000   80.000000    8.000000   Parch        Fare
count  891.000000  891.000000
mean     0.381594   32.204208
std      0.806057   49.693429
min      0.000000    0.000000
25%      0.000000    7.910400
50%      0.000000   14.454200
75%      0.000000   31.000000
max      6.000000  512.329200  

3.字符串数据转化为数值型变量,将男性用0表示,女性用1表示;登录地点S、C、Q分别用0,1,2表示。

print(titanic["Sex"].unique())  # Sex列的属性值有哪些值
titanic.loc[titanic["Sex"] == "male", "Sex"] = 0  # 将字符串映射为数字
titanic.loc[titanic["Sex"] == "female", "Sex"] = 1# print(titanic["Embarked"].unique())
titanic["Embarked"] = titanic["Embarked"].fillna('S')  # fillna()缺失值填充,用S
titanic.loc[titanic["Embarked"] == "S", "Embarked"] = 0  # 数值映射
titanic.loc[titanic["Embarked"] == "C", "Embarked"] = 1
titanic.loc[titanic["Embarked"] == "Q", "Embarked"] = 2

4. 构建模型进行分类

1.线性回归模型

划分数据,构建线性回归模型:

predictors = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"]  # 选用的特征
alg = LinearRegression()  # 线性回归模型
kf = KFold(n_splits=3, shuffle=False, random_state=1)  # K折交叉验证,把数据分成K份predictions = []
for train, test in kf.split(titanic):# print("%s %s" % (train.shape, test.shape))# print("%s %s" % (train, test))  # 训练集、测试集的索引号train_predictors = (titanic[predictors].iloc[train, :])  # 提取训练集中的特征数据train_target = titanic["Survived"].iloc[train]  # 对应的标签alg.fit(train_predictors, train_target)  # 训练test_predictions = alg.predict(titanic[predictors].iloc[test, :])  # 预测predictions.append(test_predictions)  # 保存预测结果

计算准确率:

predictions = np.concatenate(predictions, axis=0)  # 将3次结果拼接起来
predictions[predictions > .5] = 1  # 转为成2分类问题,概率大于0.5就认为是1
predictions[predictions <=.5] = 0
accuracy = sum(predictions == titanic["Survived"]) / len(predictions)
print(accuracy)

预测准确率为:0.7833894500561167

2. 逻辑回归算法

alg = LogisticRegression(solver="liblinear")  # 创建预测模型
scores = cross_val_score(alg, titanic[predictors], titanic["Survived"], cv=3)  # 3折交叉验证训练
print("逻辑回归准确率:", scores.mean())

逻辑回归准确率: 0.7878787878787877

3.随机森林预测

alg = RandomForestClassifier(random_state=1, n_estimators=100, min_samples_split=4, min_samples_leaf=2)  # 100棵树
scores = cross_val_score(alg, titanic[predictors], titanic["Survived"], cv=3)
print("随机森林准确率:", scores.mean())

随机森林准确率: 0.8226711560044894

4.从原始数据中构建新特征

titanic["FamilySize"] = titanic["SibSp"] + titanic["Parch"]  # 计算家庭成员数量 兄弟姐妹数量+携带孩子
titanic["NameLength"] = titanic["Name"].apply(lambda x: len(x))  # 计算名字长度

提取名字里面包含称呼,如小姐,女士,先生等等,构造新特征

# 得到名字中的称呼,返回匹配的值
def get_title(name):title_search = re.search(' ([A-Za-z]+)\.', name)  # 使用正则表达式搜索,大小写字母 + .if title_search:return title_search.group(1)return ""titles = titanic["Name"].apply(get_title)
print(pandas.value_counts(titles))  # 计算每个名称的数量

数据集每个名称的数量:

Mr          517
Miss        182
Mrs         125
Master       40
Dr            7
Rev           6
Major         2
Mlle          2
Col           2
Sir           1
Countess      1
Don           1
Jonkheer      1
Mme           1
Ms            1
Capt          1
Lady          1
Name: Name, dtype: int64

# 将每个标题映射到一个整数。有些标题非常罕见,并且被压缩到与其他标题相同的代码中
title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Dr": 5, "Rev": 6, "Major": 7, "Col": 7, "Mlle": 8,"Mme": 8, "Don": 9, "Lady": 10, "Countess": 10, "Jonkheer": 10, "Sir": 9, "Capt": 7, "Ms": 2}
# 转为为对应的数字
for k, v in title_mapping.items():titles[titles == k] = v
# print(pandas.value_counts(titles))
# 添加一个特征列
titanic["Title"] = titles

5.可视化特征比重:

# 构建新特征
predictors = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked", "FamilySize", "Title", "NameLength"]selector = SelectKBest(f_classif, k=10)  # 分类任务,选择前k个特征
selector.fit(titanic[predictors], titanic["Survived"])
scores = -np.log10(selector.pvalues_)  # 转化特征得分的p_value值plt.bar(range(len(predictors)), scores)  # 条形图,x值,高度值
plt.xticks(range(len(predictors)), predictors, rotation='vertical')  # x轴,x值,名称
plt.show()

6.使用集成算法预测

algorithms = [[GradientBoostingClassifier(random_state=1, n_estimators=25, max_depth=3),["Pclass", "Sex", "Age", "Fare", "Embarked", "FamilySize", "Title"]],[LogisticRegression(solver="liblinear"), ["Pclass", "Sex", "Fare", "FamilySize", "Title", "Age", "Embarked"]]
]  # 两种预测算法以及对应选择的特征kf = KFold(3)
predictions = []
for train, test in kf.split(titanic):train_target = titanic["Survived"].iloc[train]full_test_predictions = []# 对每个折叠中的每个算法进行预测for alg, predictors in algorithms:alg.fit(titanic[predictors].iloc[train, :], train_target)test_predictions = alg.predict_proba(titanic[predictors].iloc[test, :].astype(float))[:, 1]  # 获取预测为1的概率full_test_predictions.append(test_predictions)test_predictions = (full_test_predictions[0] * 1 + full_test_predictions[1] * 1) / 2  # 两种预测概率取平均test_predictions[test_predictions <= .5] = 0test_predictions[test_predictions > .5] = 1predictions.append(test_predictions)predictions = np.concatenate(predictions, axis=0)
accuracy = sum(predictions == titanic["Survived"]) / len(predictions)
print("两种方法平均准确率:", accuracy)

两种方法平均准确率: 0.8215488215488216

Kaggle实战(一):泰坦尼克获救预测相关推荐

  1. Kaggle实战:泰坦尼克幸存者预测 - 上

    (文章同步更新于个人博客@dai98.github.io) 源代码: Github Kaggle 泰坦尼克幸存者预测是Kaggle上数据竞赛的入门级别的比赛,我曾经在一年前作为作业参加过这个比赛,我想 ...

  2. Kaggle实战:泰坦尼克幸存者预测 -下

    (文章同步更新于个人博客@dai98.github.io) 源代码:Github 上一篇文章介绍了如何使用深度学习来预测泰坦尼克号幸存者,这一部分使用多分类器投票来做.由于数据预处理部分比较相似,重复 ...

  3. 集成算法-随机森林与案例实战-泰坦尼克获救预测

    集成算法-随机森林 Ensemble learning 目的:让机器学习效果更好,单个不行,群殴走起 Bagging:训练多个分类器取平均 f ( x ) = 1 / M ∑ m = 1 M f m ...

  4. kaggle竞赛:泰坦尼克幸存者预测

    kaggle竞赛:泰坦尼克幸存者预测--(一) import pandas as pd import numpy as np import matplotlib.pyplot as plt impor ...

  5. kaggle入门之泰坦尼克幸存预测

    kaggle入门之泰坦尼克幸存预测 # 数据集什么的就不介绍了,官网上都有 主要的工作步骤 1.提出和定义问题 2.获取训练和测试数据 3.获取,准备和清洗数据 4.分析,识别,探究数据 5.建模,预 ...

  6. 机器学习实战(五) kaggle练习赛 泰坦尼克获救预测

    这道题的主页:https://www.kaggle.com/c/titanic 目录 一. 读取数据,观察数据分布 二. 数据预处理 1. 填充缺失值 2. 文字到数值的映射 三.模型 1. 用线性回 ...

  7. Kaggle案例之泰坦尼克船员幸存预测(sklearn机器学习库)

    无意间在网易云课堂上找了一个Kaggle案例,泰坦尼克获救船员预测,在此之前我是从没接触过kaggle,毕竟是刚入门的小白,看着视频,算是真正实战了一次,主要是在这个过程中学到了很多东西. 下面视频地 ...

  8. Kaggle案例之泰坦尼克船员幸存预测

    无意间在网易云课堂上找了一个Kaggle案例,泰坦尼克获救船员预测,在此之前我是从没接触过kaggle,毕竟是刚入门的小白,看着视频,算是真正实战了一次,主要是在这个过程中学到了很多东西.  下面视频 ...

  9. kaggle房价预测特征意思_机器学习-kaggle泰坦尼克生存预测(一)-数据清洗与特征构建...

    1.背景: 1.1 关于kaggle: 谷歌旗下的 Kaggle 是一个数据建模和数据分析竞赛平台.该平台是当下最流行的数据科研赛事平台,其组织的赛事受到全球数据科学爱好者追捧. 如果学生能够在该平台 ...

最新文章

  1. Ansible05-部署文件
  2. sublime打开文本时会记忆上次关闭时鼠标停留的位置
  3. Git打标签(Tag)(亲测)
  4. xpath contains_Python 爬虫进阶: Scrapy Shell 和 Xpath 学习心得
  5. LeetCode 793. 阶乘函数后K个零(二分查找)
  6. python三引号解析_[宜配屋]听图阁
  7. 大学计算机学生成绩综合管理系统,大学综合测评成绩管理系统的研究 计算机专业毕业论文.doc...
  8. Java toString()方法的要点
  9. java runnable 异常_Java实现多线程异常捕获Runnable的案例
  10. 智慧水务、智慧泵房、水厂监控、营收管理、DMA漏损、GIS系统、维护管理、档案管理、仓库管理、水质监控、数据中心、指挥调度中心、消防栓、管网、供水、水质、水厂调度、加压泵站、库存调拨、物料申请
  11. webtop搭建简单知识库粗略介绍
  12. sklearn中SVM的可视化
  13. H13-531 华为HCIE云计算笔试题库整理
  14. c# 超时时间已到.在操作完成之前超时时间已过或服务器未响应,超时过期了。在操作完成或服务器没有响应之前经过的超时时间。声明已被终止...
  15. 通达信买入离场信号选股公式,精准买卖点 不加密无未来
  16. java 1.5 jdk_jdk1.5安装及配置
  17. Python临时文件创建:tempfile模块简介
  18. Ubuntu 设置桥接网络
  19. ROS-Control专题:PR2的六个概念【5】
  20. margin-top传递问题

热门文章

  1. 「 生活太重要了,不能太过严肃 」:生命游戏之父、最神奇的数学家John Conway...
  2. 房价这么高,为什么租金却高不起来?
  3. CheckBox选中状态改变
  4. 不可知敏捷:精益敏捷转型成功的关键
  5. 基于Java+Swing实现天气预报系统
  6. 【教3妹学mysql】一条慢sql如何排查优化
  7. Portraiture2023最新版本下载及PS磨皮的方法教程
  8. UI设计规范有哪些?| 萧蕊冰
  9. Airtestpoco学习历程1——设备连接
  10. python爬取pubmed的文献_爬虫获取pubmed中文献的标题和摘要