决策树
1.决策树算法
- 决策树算法的基本思想是根据事物特征。算法的基础思想还是抽象、及概念。当我们在定义概念的时候是用属加种差法来定义。一类事物之所以区别另一类事物就是因为事物的特有属性。我们在分类的时候就是要找到这种特有属性。
- 我们平常在思考的时候也会用到这种思想。比如一个售货员判断一个顾客是否会购买商品的时候,他会下意识的根据顾客的外表来判断“是否有钱”这个属性,在根据这个属性来判断是否会购买商品。
- 在计算机中,我们就是要找到这个能够根据属性判断类型的target function(目标函数)这个目标函数也叫做分类模型
首先安装 graphviz,这是计算的核心 package
conda install graphviz
再安装 pydot ,这是 graphviz 的 python 接口
conda install pydot
1.1 ID3算法
1.2 C4.5 算法
1.3 CART算法-(可分类可回归)
其中涉及到安装graphviz的问题:
- 安装graphviz需要安装低版本的2.2.8的安装文件
- 配置window环境变量
- pip install graphviz
课程的决策树算法-决策树算法_cart.py
from matplotlib import pyplot as plt
import numpy as np
from sklearn import tree
import random
from graphviz import Source
#pip install graphviz 安装就可以
if __name__ == '__main__':
np.random.seed(42)
x = np.random.randint(10,size = (100,4))
y = np.random.randint(2,size = 100)
a = np.column_stack((x,y))
clf = tree.DecisionTreeClassifier(criterion='gini',max_depth=3)
clf.fit(x,y)
graph = Source(tree.export_graphviz(clf,out_file=None))
graph.format = 'png'
graph.render('cart_tree',view = True)
自学代码 决策树.py
from matplotlib import pyplot as plt
import numpy as np
from sklearn import tree
from sklearn.datasets import load_iris
if __name__ == '__main__':
#-----------------------------------------------------------
# load_data
print('决策树分析')
data = load_iris()#加载数据iris数据
print('keys:\n',data.keys())
#查看属性名称
print('feature names:\n',data.get('feature_names'))
#查看label名称
print('target:\n',data.get('target_names'))
#获取样本数据
x = data.get('data')
y = data.get('target')
print('获取样本数据x.shape,y.shape:\n',x.shape,y.shape)
print('获取样本数据描述:\n',data.get('DESCR'))
#-----------------------------------------------------------
# visualize the data
f = []
f.append(y==0)
f.append(y==1)
f.append(y==2)
color = ['red','blue','green']
# 绘制四个属性的散点图
#fig, ax = plt.subplots(1,3),其中参数1和3分别代表子图的行数和列数,一共有 1x3 个子图像。函数返回一个figure图像和子图ax的array列表。
fig, axes = plt.subplots(4,4)
for i, ax in enumerate(axes.flat):
row = i // 4
# '%'求模运算,就是求除法中的余数
col = i % 4
# 对角线的图片
if row == col:
ax.text(.1,.5,data.get('feature_names')[row])
ax.set_xticks([])
ax.set_yticks([])
continue
for k in range(3):
ax.scatter(x[f[k],row],x[f[k],col],c=color[k],s=3)
fig.subplots_adjust(hspace = 0.3,wspace = 0.3)
plt.show()
#-----------------------------------------------------------
# 分类预测
# 随机划分训练集和测试集
num = x.shape[0] # 样本总数
# 划分比例,训练集数目:测试集数目
ratio = 7/3
# 测试集样本数目
num_test = int(num/(1+ratio))
# 训练集样本数目
num_train = num - num_test
# 产生样本标号
index = np.arange(num)
# 洗牌
np.random.shuffle(index)
print('样本总数:\n',num,'\n划分比例:\n',ratio,'\n测试集数量:\n',num_test,'\n训练集数量:\n',num_train)
x_test = x[index[:num_test],:]
y_test = y[index[:num_test:]]
x_train = x[index[num_test:],:]
y_train = y[index[num_test:]]
# 构建决策树
clf = tree.DecisionTreeClassifier()#构建对象
clf.fit(x_train,y_train) #决策树拟合
#预测
y_test_pre = clf.predict(x_test)
print(y_test_pre)
# 计算分类器准确率
acc = sum(y_test_pre == y_test) / num_test
print('the accuracy is ,' , acc)
# 问题:数据的结果是存储在两个数组中