分类算法-决策树

决策树:女神使用的约会策略

算法原理:在已知的条件中,选取一个条件作为树根,然后再看是否还需要其他判断条件,如果需要的话,继续构建一个分支来判断第二个条件,以此类推,最终形成的这棵树上,所有的叶子节点都是要输出的类别信息,所有的非叶子节点都是特征信息。
在这里插入图片描述
如何选择一个特征作为根节点?
下一个决策又该选取哪个特征作为节点?
决策树算法使用信息增益的方法来衡量一个特征和特征之间的重要性

几个版本的决策树的比较
在这里插入图片描述
算法优点:非常直观,可解释极强;预测速度比较快;既可以处理离散值也可以处理连续值,还可以处理缺失值;
算法缺点:
容易过拟合;
两种解决办法
在这里插入图片描述

需要处理样本不均衡的问题;样本的变化会引发树结构巨变;
继续优化:
在这里插入图片描述
实例体会

from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier #引入决策树算法包
import numpy as np #支持大量的维度数组与矩阵运算

#引入画图相关的包
from IPython.display import Image
from sklearn import tree
#dot是一个程序化生成流程图的简单语言
import pydotplus
import matplotlib.pyplot as plt

np.random.seed(0)#保证我们每次产生的随机数是一样的
iris = datasets.load_iris()#获取鸢尾花数据集
x = iris.data ##数据部分
y = iris.target ##类别部分

#从150条数据中选140条作为训练集,10条作为测试集。permutation接收一个数作为参数(这里为数据集长度150),产生一个0-149乱序一维数组
indices = np.random.permutation(len(x))#permutation排列,既可以对list,也可以对矩阵
x_train = x[indices[:-10]] #:从第一项到倒数第十个数
x_test = x[indices[-10:]] #-10:取后10组数
y_train = y[indices[:-10]]
y_test = y[indices[-10:]]

#设置树的最大深度为4
clf = DecisionTreeClassifier(max_depth=4)
clf.fit(x_train, y_train.astype('int'))


dot_data = tree.export_graphviz(clf, out_file=None,
                                feature_names = iris.feature_names,
                                class_names = iris.target_names,
                                filled=True, rounded=True,
                                special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data)
Image(graph.create_png())
fig = plt.figure(figsize=(25,20))
_ = tree.plot_tree(
    clf,
    feature_names=iris.feature_names,
    class_names=iris.target_names,
    filled=True
)

# Save picture
fig.savefig("decistion_tree.png")

y_predict = clf.predict(x_test)
score = clf.score(x_test, y_test,sample_weight=None)
print('y_Test')
print(y_test)
print('y_Predict')
print(y_predict)
print('Accuracy: ',score)

请添加图片描述

                         decistion_tree.png

可能会遇到的问题:

  • 问题1:
    Unknown label type: continuous-multioutput. Maybe you are trying to fit a classifier, which expects discrete classes on a regression target with continuous values.
    解决方法
  • 问题2
    pydotplus.graphviz.InvocationException: GraphViz’s executables not found
    解决方法
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值