Fork me on GitHub

基于决策树的泰坦尼克号幸存者分析

基于决策树的泰坦尼克号幸存者分析,几个重要的方法

  • 缺失值的处理
  • 将字符型数据转成数值型
  • 特征属性数据和标签属性的分离
  • 决策树的建模
  • 网格搜索的建立

导入模块

1
2
3
4
5
6
7
8
9
10
11
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set() # setting seaborn default for plots

from sklearn.tree import DecisionTreeClassifier # 分类决策树
from sklearn.model_selection import GridSearchCV # 网格搜索
from sklearn.model_selection import train_test_split # 训练集和测试集的划分
from sklearn.model_selection import cross_val_score # 交叉验证模块

导入数据

1
data = pd.read_csv("/Users/peter/data-visualization/train.csv")

查看数据信息

删除缺失值

1
2
# 去掉缺失值过多的列 Cabin (直接删掉),以及和观测判断来说和预测的y没有关系的列(Name, Ticket)
data.drop(["Cabin", "Name", "Ticket"], inplace=True, axis=1)

中值填充

某个字段缺失值不是太多,使用中值填充

1
2
# Age属性用中值填充
data['Age'] = data['Age'].fillna(data['Age'].mean())

如果只是很少部分的缺失值,比如Embarked字段,直接dropna

1
2
data = data.dropna()   # 只要是存在的缺失值都给删掉
data.info()

将属性的值转成数值型

Python不能直接处理字符串数据,需要转成数值型

  • Embark中存在[“S”, “C”, “Q”]3种结果:现将结果转成列表,再从列表中取出对应的索引(数字)
  • Sex字段中存在[“male”, “female”]2种结果:只有两个结果的情形,通过bool值来解决
1
2
3
4
5
6
7
8
9
10
11
12
# 方法1
# 属性的结果存在多个不同的取值
labels = data["Embarked"].unique().tolist() # ["S", "C", "Q"]
# 将Embarked属性中的 ["S", "C", "Q"]转成0,1,2
data['Embarked']= data['Embarked'].apply(lambda x: labels.index(x))


# 方法2
data["Sex"] = (data["Sex"] == "male").astype("int") # 先获取bool值,再将bool值转成0-1

# 方法3:通过loc来实现
# data.loc[:, "Sex"] = (data["Sex"] == "male").astype("int")

特征属性和标签的分离

根据某个属性将数据分成特征数据和标签数据(最后的预测值或者输出值)

1
2
x = data.iloc[:, data.columns != "Survived"]
y = data.iloc[:, data.columns == "Survived"]

随机划分数据后的索引还原

1
2
3
4
5
# 划分训练集和测试集
Xtrain, Xtest, ytrain, ytest = train_test_split(x, y, test_size=0.3)

for i in [Xtrain, Xtest, ytrain, ytest]:
i.index = range(i.shape[0]) # shape属性的第一个元素就是索引的总个数

决策树的建模过程

1
2
3
4
5
6
7
8
9
clf = DecisionTreeClassifier(random_state=25)
clf = clf.fit(Xtrain, ytrain)
score = clf.score(Xtest, ytest)
score

# 交叉验证
clf = DecisionTreeClassifier(random_state=25)
score = cross_val_score(clf, x, y, cv=10).mean() # 10次交叉验证求均值,结果降低
score

学习曲线

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
tr = []  # 两个空列表用来存储训练得到的两个分数
te = []
for i in range(10):
clf = DecisionTreeClassifier(random_state=25 # 实例化模型,设定决策树的最大深度
,max_depth=i+1
,criterion="entropy" # 默认是基尼系数。一般情况下,entropy是欠拟合的情况下才使用
)
clf = clf.fit(Xtrain, ytrain) # fit训练过程
score_tr = clf.score(Xtrain, ytrain) # 训练集score
score_te = cross_val_score(clf, x, y, cv=10).mean() # 测试集分数,取均值
tr.append(score_tr)
te.append(score_te)

print(max(te))
plt.plot(range(1,11), tr, color="red", label="train") # x,y,颜色,label
plt.plot(range(1,11), te, color="blue", label="test")
plt.xticks(range(1,11)) # 横坐标范围固定在1-10
plt.legend() # 图例
plt.show()

网格搜索demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
gini_threholds = np.linspace(0, 0.5, 20)   # gini:0-0.5
#entropy_threholds = np.linspace(0,1,20) entropy:0-1

# 参数
parameter = {
"criterion":("gini", "entropy")
,"splitter":("best", "random")
,"max_depth":[*range(1,10)]
,"min_samples_leaf":[*range(1,50,5)]
,"min_impurity_decrease":gini_threholds
}

# 网格搜索
clf = DecisionTreeClassifier(random_state=25)
GS = GridSearchCV(clf, parameter, cv=10) # 同时满足fit,score,交叉验证3种功能
GS = GS.fit(Xtrain, ytrain)

# 2个重要的属性
GS.best_params_ # 显示属性的最好组合结果
GS.best_score_

本文标题:基于决策树的泰坦尼克号幸存者分析

发布时间:2020年01月10日 - 17:01

原始链接:http://www.renpeter.cn/2020/01/10/%E5%9F%BA%E4%BA%8E%E5%86%B3%E7%AD%96%E6%A0%91%E7%9A%84%E6%B3%B0%E5%9D%A6%E5%B0%BC%E5%85%8B%E5%8F%B7%E5%B9%B8%E5%AD%98%E8%80%85%E5%88%86%E6%9E%90.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Coffee or Tea