案例:泰坦尼克号乘客生存预测
学习目标
通过案例进一步掌握决策树算法api的具体使用
1 案例背景
泰坦尼克号沉没是历史上最臭名昭着的沉船之一。1912年4月15日,在她的处女航中,泰坦尼克号在与冰山相撞后沉没,在2224名乘客和机组人员中造成1502人死亡。这场耸人听闻的悲剧震惊了国际社会,并为船舶制定了更好的安全规定。 造成海难失事的原因之一是乘客和机组人员没有足够的救生艇。尽管幸存下沉有一些运气因素,但有些人比其他人更容易生存,例如妇女,儿童和上流社会。 在这个案例中,我们要求您完成对哪些人可能存活的分析。特别是,我们要求您运用机器学习工具来预测哪些乘客幸免于悲剧。
案列
我们提取到的数据集中的特征包括票的类别,是否存活,乘坐班次,年龄,登陆home.dest,房间,船和性别等。
经过观察数据得到:
- 乘坐班是指乘客班(1,2,3),是社会经济阶层的代表。
- 其中age数据存在缺失。
2 步骤分析
1.获取数据
2.数据基本处理
- 2.1 确定特征值,目标值
- 2.2 缺失值处理
- 2.3 缺失值处理- 项目
3.特征工程(字典特征抽取)
4.机器学习(决策树)
5.模型评估
3 代码实现
导入需要的模块
import numpy as np
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
from sklearn.tree import DecisionTreeClassifier,export_graphviz
from sklearn.feature_extraction import DictVectorizer
from sklearn.model_selection import train_test_split
data=pd.read_csv("titanic.txt")
x=data[['pclass','age','sex']]
y=data['survived']
# print(x)
# import sys
# sys.exit()
x['age'].fillna(x['age'].mean(),inplace=True)#inplace = true 在原字段中修改
# print(x)
# x=x.to_dict(orient='records')
# print(x)
train_x,test_x,train_y,test_y=train_test_split(x,y,random_state=22)
transf=DictVectorizer(sparse=False)
x_train=transf.fit_transform(train_x.to_dict(orient='records'))
x_test=transf.fit_transform(test_x.to_dict(orient='records'))
print(x_train)
print(train_y)
print(x_test)
# 决策树
model=DecisionTreeClassifier(criterion='entropy',max_depth=5)
model.fit(x_train,train_y)
scoe=model.score(x_test,test_y)
pre=model.predict(x_test)
print(scoe)
print(pre)
import graphviz
import os
os.environ['PATH'] = os.pathsep + r'C:\Program Files\Graphviz\bin'
dot_data=export_graphviz(model,out_file=None,feature_names=['age', 'pclass=1st', 'pclass=2nd', 'pclass=3rd', '女性', '男性'],filled=True,rounded=True)
# graph = graphviz.Source(dot_data)
# graph.render('决策树可视化1')
# graph.render('DTREE2')
# 将生成的dot_data内容导入到txt文件中
with open('dot_data.txt', 'w') as f1:
f1.write(dot_data)
f1.close()
# 修改字体设置,避免中文乱码!
import re
f_old = open('dot_data.txt', 'r')
f_new = open('dot_data_new.txt', 'w', encoding='utf-8')
for line in f_old:
if 'fontname' in line:
font_re = 'fontname=(.*?)]'
old_font = re.findall(font_re, line)[0]
line = line.replace(old_font, 'SimHei')
f_new.write(line)
f_old.close()
f_new.close()
# 以PNG的图片形式存储生成的可视化文件
os.system('dot -Tpng dot_data_new.txt -o 决策树模型.png')
print('决策树模型.png已经保存在代码所在文件夹!')
# 以PDF的形式存储生成的可视化文件
os.system('dot -Tpdf dot_data_new.txt -o 决策树模型.pdf')
print('决策树模型.pdf已经保存在代码所在文件夹!')
4.机器学习(决策树)
estimator = DecisionTreeClassifier(criterion=“entropy”, max_depth=5)
estimator.fit(x_train, y_train)
5.模型评估
estimator.score(x_test, y_test)
estimator.predict(x_test)
决策树的结构是可以直接显示
4 决策树可视化
4.1 保存树的结构到dot文件
dot文件当中的内容如下
digraph Tree {
node [shape=box] ;
0 [label="petal length (cm) <= 2.45\nentropy = 1.584\nsamples = 112\nvalue = [39, 37, 36]"] ;
1 [label="entropy = 0.0\nsamples = 39\nvalue = [39, 0, 0]"] ;
0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ;
2 [label="petal width (cm) <= 1.75\nentropy = 1.0\nsamples = 73\nvalue = [0, 37, 36]"] ;
0 -> 2 [labeldistance=2.5, labelangle=-45, headlabel="False"] ;
3 [label="petal length (cm) <= 5.05\nentropy = 0.391\nsamples = 39\nvalue = [0, 36, 3]"] ;
2 -> 3 ;
4 [label="sepal length (cm) <= 4.95\nentropy = 0.183\nsamples = 36\nvalue = [0, 35, 1]"] ;
3 -> 4 ;
5 [label="petal length (cm) <= 3.9\nentropy = 1.0\nsamples = 2\nvalue = [0, 1, 1]"] ;
4 -> 5 ;
6 [label="entropy = 0.0\nsamples = 1\nvalue = [0, 1, 0]"] ;
5 -> 6 ;
7 [label="entropy = 0.0\nsamples = 1\nvalue = [0, 0, 1]"] ;
5 -> 7 ;
8 [label="entropy = 0.0\nsamples = 34\nvalue = [0, 34, 0]"] ;
4 -> 8 ;
9 [label="petal width (cm) <= 1.55\nentropy = 0.918\nsamples = 3\nvalue = [0, 1, 2]"] ;
3 -> 9 ;
10 [label="entropy = 0.0\nsamples = 2\nvalue = [0, 0, 2]"] ;
9 -> 10 ;
11 [label="entropy = 0.0\nsamples = 1\nvalue = [0, 1, 0]"] ;
9 -> 11 ;
12 [label="petal length (cm) <= 4.85\nentropy = 0.191\nsamples = 34\nvalue = [0, 1, 33]"] ;
2 -> 12 ;
13 [label="entropy = 0.0\nsamples = 1\nvalue = [0, 1, 0]"] ;
12 -> 13 ;
14 [label="entropy = 0.0\nsamples = 33\nvalue = [0, 0, 33]"] ;
12 -> 14 ;
}
转换结果生成图:
5 决策树总结
优点:
简单的理解和解释,树木可视化。
缺点:
决策树学习者可以创建不能很好地推广数据的过于复杂的树,容易发生过拟合。
改进:
减枝cart算法
随机森林(集成学习的一种)
注:企业重要决策,由于决策树很好的分析能力,在决策过程应用较多, 可以选择特征