class sklearn.tree.DecisionTreeClassifier(criterion=’gini’, max_depth=None,random_state=None)
criterion
min_samples_split
min_samples_leaf
max_depth
random_state
泰坦尼克号沉没是历史上最臭名昭着的沉船之一。1912年4月15日,在她的处女航中,泰坦尼克号在与冰山相撞后沉没,在2224名乘客和机组人员中造成1502人死亡。这场耸人听闻的悲剧震惊了国际社会,并为船舶制定了更好的安全规定。 造成海难失事的原因之一是乘客和机组人员没有足够的救生艇。尽管幸存下沉有一些运气因素,但有些人比其他人更容易生存,例如妇女,儿童和上流社会。 在这个案例中,我们要求您完成对哪些人可能存活的分析。特别是,我们要求您运用机器学习工具来预测哪些乘客幸免于悲剧。
案例:[
我们提取到的数据集中的特征包括票的类别,是否存活,乘坐班次,年龄,登陆home.dest,房间,船和性别等。
数据:[
经过观察数据得到:
1 乘坐班是指乘客班(1,2,3),是社会经济阶层的代表。
2 其中age数据存在缺失。
2.数据基本处理
2.1 确定特征值,目标值
2.3 数据集划分
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、获取数据
titan = pd.read_csv("
2.数据基本处理
2.1 确定特征值,目标值
x = titan[["pclass", "age", "sex"]]
y = titan["survived"]
# 缺失值需要处理,将特征当中有类别的这些特征进行字典特征抽取
x['age'].fillna(x['age'].mean(), inplace=True)
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=22)
特征中出现类别符号,需要进行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"))
决策树API当中,如果没有指定max_depth那么会根据信息熵的条件直到最终结束。这里我们可以指定树的深度来进行限制树的大小
# 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)
决策树的结构是可以直接显示
sklearn.tree.export_graphviz() 该函数能够导出DOT格式
tree.export_graphviz(estimator,out_file='tree.dot’,feature_names=[‘’,’’])
export_graphviz(estimator, out_file="./data/tree.dot", feature_names=['age', 'pclass=1st', 'pclass=2nd', 'pclass=3rd', '女性', '男性'])
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 ;
}
那么这个结构不能看清结构,所以可以在一个网站上显示
将dot文件内容复制到该网站当中显示
优点:
简单的理解和解释,树木可视化。
缺点:
决策树学习者可以创建不能很好地推广数据的过于复杂的树,容易发生过拟合。
改进:
减枝cart算法
注:企业重要决策,由于决策树很好的分析能力,在决策过程应用较多, 可以选择特征
案例流程分析【了解】
1.获取数据
2.数据基本处理
3.特征工程(字典特征抽取)
5.模型评估
决策树可视化【了解】
sklearn.tree.export_graphviz()
决策树优缺点总结【知道】
优点:
缺点:
改进:
前面已经讲到,关于数据类型,我们主要可以把其分为两类,连续型数据和离散型数据。在面对不同数据时,决策树也可以分为两大类型:
不管是回归决策树还是分类决策树,都会存在两个核心问题:
一个回归树对应着输入空间(即特征空间)的一个划分以及在划分单元上的输出值。分类树中,我们采用信息论中的方法,通过计算选择最佳划分点。
而在回归树中,采用的是启发式的方法。假如我们有n个特征,每个特征有 s i ( i ∈ ( 1 , n ) ) s_i(i\in (1,n)) si(i∈(1,n))个取值,那我们遍历所有特征,尝试该特征所有取值,对空间进行划分,直到取到特征 j 的取值 s,使得损失函数最小,这样就得到了一个划分点。描述该过程的公式如下:
假设将输入空间划分为M个单元: R 1 , R 2 , . . . , R m R_1,R_2,...,R_m R1,R2,...,Rm那么每个区域的输出值就是: c m = a v g ( y i ∣ x i ∈ R m ) c_m=avg(y_i|x_i\in R_m) cm=avg(yi∣xi∈Rm)也就是该区域内所有点y值的平均数。
举例:
如下图,假如我们想要对楼内居民的年龄进行回归,将楼划分为3个区域 R 1 , R 2 , R 3 R_1,R_2,R_3 R1,R2,R3(红线),
那么 R 1 R_1 R1的输出就是第一列四个居民年龄的平均值,
R 2 R_2 R2的输出就是第二列四个居民年龄的平均值,
R 3 R_3 R3的输出就是第三、四列八个居民年龄的平均值。
在训练数据集所在的输入空间中,递归的将每个区域划分为两个子区域并决定每个子区域上的输出值,构建二叉决策树:
(1)选择最优切分特征 j j j与切分点 s s s,求解遍历特征 j j j,对固定的切分特征 j j j扫描切分点 s s s,选择使得上式达到最小值的对 ( j , s ) (j,s) (j,s).
为了易于理解,接下来通过一个简单实例加深对回归决策树的理解。
训练数据见下表,目标是得到一棵最小二乘回归树。
x | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
---|---|---|---|---|---|---|---|---|---|---|
y | 5.56 | 5.7 | 5.91 | 6.4 | 6.8 | 7.05 | 8.9 | 8.7 | 9 | 9.05 |
(1)选择最优的切分特征j与最优切分点s:
在本数据集中,只有一个特征,因此最优切分特征自然是x。
确定第二个问题:我们考虑9个切分点 [ 1 . 5 , 2 . 5 , 3 . 5 , 4 . 5 , 5 . 5 , 6 . 5 , 7 . 5 , 8 . 5 , 9 . 5 ] [1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5,9.5] [1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5,9.5]。
a、计算子区域输出值:
例如,取 s=1.5。此时 R 1 = 1 , R 2 = 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 1 0 R1={1},R2={2,3,4,5,6,7,8,9,10} R1=1,R2=2,3,4,5,6,7,8,9,10,这两个区域的输出值分别为:
c 1 = 5 . 5 6 c1=5.56 c1=5.56
c 2 = ( 5 . 7 + 5 . 9 1 + 6 . 4 + 6 . 8 + 7 . 0 5 + 8 . 9 + 8 . 7 + 9 + 9 . 0 5 ) / 9 = 7 . 5 0 c2=(5.7+5.91+6.4+6.8+7.05+8.9+8.7+9+9.05)/9=7.50 c2=(5.7+5.91+6.4+6.8+7.05+8.9+8.7+9+9.05)/9=7.50。
同理,得到其他各切分点的子区域输出值,如下表:
s | 1.5 | 2.5 | 3.5 | 4.5 | 5.5 | 6.5 | 7.5 | 8.5 | 9.5 |
---|---|---|---|---|---|---|---|---|---|
c1 | 5.56 | 5.63 | 5.72 | 5.89 | 6.07 | 6.24 | 6.62 | 6.88 | 7.11 |
c2 | 7.5 | 7.73 | 7.99 | 8.25 | 8.54 | 8.91 | 8.92 | 9.03 | 9.05 |
b、计算损失函数值,找到最优切分点:
把 c 1 , c 2 c1,c2 c1,c2的值代入到同平方损失函数 L o s s ( y , f ( x ) ) = ( f ( x ) − y ) 2 Loss(y,f(x))=(f(x)-y)^2 Loss(y,f(x))=(f(x)−y)2,
当s=1.5时,
同理,计算得到其他各切分点的损失函数值,可获得下表:
s | 1.5 | 2.5 | 3.5 | 4.5 | 5.5 | 6.5 | 7.5 | 8.5 | 9.5 |
---|---|---|---|---|---|---|---|---|---|
m(s) | 15.72 | 12.07 | 8.36 | 5.78 | 3.91 | 1.93 | 8.01 | 11.73 | 15.74 |
显然取 s=6.5时,m(s)最小。因此,第一个划分变量【j=x,s=6.5】
(2)用选定的(j,s)划分区域,并决定输出值;
(3)调用步骤 (1)、(2),继续划分:
对R1继续进行划分:
x | 1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|---|
y | 5.56 | 5.7 | 5.91 | 6.4 | 6.8 | 7.05 |
取切分点[1.5,2.5,3.5,4.5,5.5],则各区域的输出值c如下表:
s | 1.5 | 2.5 | 3.5 | 4.5 | 5.5 |
---|---|---|---|---|---|
c1 | 5.56 | 5.63 | 5.72 | 5.89 | 6.07 |
c2 | 6.37 | 6.54 | 6.75 | 6.93 | 7.05 |
计算损失函数值m(s):
s | 1.5 | 2.5 | 3.5 | 4.5 | 5.5 |
---|---|---|---|---|---|
m(s) | 1.3087 | 0.754 | 0.2771 | 0.4368 | 1.0644 |
s=3.5时,m(s)最小。
(4)生成回归树
假设在生成3个区域之后停止划分,那么最终生成的回归树形式如下:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor
from sklearn import linear_model
# 生成数据
x = np.array(list(range(1, 11))).reshape(-1, 1)
y = np.array([5.56, 5.70, 5.91, 6.40, 6.80, 7.05, 8.90, 8.70, 9.00, 9.05])
# 训练模型
model1 = DecisionTreeRegressor(max_depth=1)
model2 = DecisionTreeRegressor(max_depth=3)
model3 = linear_model.LinearRegression()
model1.fit(x, y)
model2.fit(x, y)
model3.fit(x, y)
# 模型预测
X_test = np.arange(0.0, 10.0, 0.01).reshape(-1, 1) # 生成1000个数,用于预测模型
X_test.shape
y_1 = model1.predict(X_test)
y_2 = model2.predict(X_test)
y_3 = model3.predict(X_test)
# 结果可视化
plt.figure(figsize=(10, 6), dpi=100)
plt.scatter(x, y, label="data")
plt.plot(X_test, y_1,label="max_depth=1")
plt.plot(X_test, y_2, label="max_depth=3")
plt.plot(X_test, y_3, label='liner regression')
plt.xlabel("data")
plt.ylabel("target")
plt.title("Decision Tree Regression")
plt.legend()
plt.show()
结果展示
回归决策树算法总结【指导】
输入:训练数据集D:
流程:在训练数据集所在的输入空间中,递归的将每个区域划分为两个子区域并决定每个子区域上的输出值,构建二叉决策树: