本文已参与「新人创作礼」活动,一起开启掘金创作之路。
实验三、数据挖掘之决策树
一、实验目的
1. 熟悉掌握决策树的原理,
2. 熟练掌握决策树的生成方法与过程
二、实验工具
1. Anaconda
2. sklearn
3. pydotplus
三、实验简介
决策树是一个非参数的监督式学习方法,主要用于分类和回归。算法的目标是通过推断数据特征,学习决策规则从而创建一个预测目标变量的模型。
四、实验内容
1. 自己创建至少2个向量,每个向量至少1个属性和1个类标号,根据向量生成决策树,并利用该决策树进行预测。
from sklearn import tree
X = [[10, 20], [15, 17],[23,21],[50,20],[20,34]]
Y = [0, 1,0,1,1]
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X, Y)
clf.predict([[22., 22.]])
clf.predict_proba([[22., 22.]]) #计算属于每个类的概率
要求根据要求随机生成数据,并构建决策树,并举例预测。
代码
from sklearn import tree
import random
X=[[10,11],[20,21],[11,20],[22,24]]
Y=[0,0,1,1]
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X,Y)
print(clf.predict([[22,32]]))
print(clf.predict_proba([[22,32]]))
test=tree.export_graphviz(clf,out_file=None)
graph=pydotplus.graph_from_dot_data(test)
graph.write_pdf("test1.pdf")
运行结果
2. 对鸢尾花数据构建决策树,
(1) 调用数据的方法如下:
from sklearn.datasets import load_iris
iris = load_iris()# 从sklearn 数据集中获取鸢尾花数据。
(2) 利用sklearn中的决策树方法对鸢尾花数据建立决策树 (3) 为了能够直观看到建好的决策树,安装 pydotplus, 方法如下:
pip install pydotplus
pydotplus使用方法
import pydotplus #引入pydotplus
dot_data = tree.export_graphviz(clf, out_file=None)
graph = pydotplus.graph_from_dot_data(dot_data)
graph.write_pdf("iris.pdf")#将图写成pdf文件
完整代码
from sklearn.datasets import load_iris
import pydotplus
from sklearn import tree
#获取鸢尾花的数据
iris = load_iris()
mode=tree.DecisionTreeClassifier()
clf = mode.fit(iris.data,iris.target)
dot_data=tree.export_graphviz(clf,out_file=None)
graph=pydotplus.graph_from_dot_data(dot_data)
graph.write_pdf("iris.pdf")
运行结果
3. 不使用sklearn中的决策树方法,根据以下数据集自己编写决策树构建程序(建议用python语言)。
| Tid | Refund | Marital Status | Taxable Income | Cheat |
|---|---|---|---|---|
| 1 | yes | single | 125k | no |
| 2 | no | married | 100k | no |
| 3 | no | single | 70k | no |
| 4 | yes | married | 120k | no |
| 5 | no | divorced | 95k | yes |
| 6 | no | married | 60k | no |
| 7 | yes | divorced | 220k | no |
| 8 | no | single | 85k | yes |
| 9 | no | married | 75k | no |
| 10 | no | single | 90k | yes |
首先利用sklearn中的决策树的代码实现
代码
from sklearn import tree
# X
#Refund yes = 1 no=0,
#Marital Status single = 0 married = 1 divorce = 2,
#Taxable Income <80k = 0 >=80 = 1
#Cheat yes = 1 no = 0
X = [
[1, 0, 1],
[0, 1, 1],
[0, 0, 0],
[1, 1, 1],
[0, 2, 1],
[0, 1, 0],
[1, 2, 1],
[0, 0, 1],
[0, 1, 0],
[0, 0, 1]
]
Y = [0, 0, 0, 0, 1, 0, 0, 1, 0, 1]
mode = tree.DecisionTreeClassifier()
clf = mode.fit(X, Y)
dot_data = tree.export_graphviz(clf, out_file=None)
graph = pydotplus.graph_from_dot_data(dot_data)
graph.write_pdf("lzk.pdf")#将图写成pdf文件
运行结果
五、实验总结(写出本次实验的收获,遇到的问题等)
通过本次实验,学会了sklearn中的决策树的使用,在使用之前
要导入包sklearn中的tree,同时学会了使用
tree.DecisionTreeClassifier()方法
tree.DecisionTreeClassifier().fit()方法
tree.export_graphviz()方法,
pydotplus.graph_from_dot_data()方法等等。
利用鸢尾花数据生成了决策树,并导出为pdf文件
对决策树算法有了一些初步了解,为以后深入研究
打下基础。