ML - 决策树(decision tree)

2018-10-11  本文已影响44人  leo567

机器学习中分类和预测算法的评估:

什么是决策树/判定树(decision tree)?

判定树是一个类似于流程图的树结构:其中,每个内部结点表示在一个属性上的测试,每个分支代表一个属性输出,而每个树叶结点代表类或类分布。树的最顶层是根结点。
机器学习中分类方法中的一个重要算法

decision tree

熵(entropy)概念:

信息和抽象,如何度量?

1948年,香农提出了 ”信息熵(entropy)“的概念

一条信息的信息量大小和它的不确定性有直接的关系,要搞清楚一件非常非常不确定的事情,或者

是我们一无所知的事情,需要了解大量信息==>信息量的度量就等于不确定性的多少

例子:猜世界杯冠军,假如一无所知,猜多少次?

每个队夺冠的几率不是相等的

比特(bit)来衡量信息的多少

变量的不确定性越大,熵也就越大

3.1 决策树归纳算法 (ID3

1970-1980, J.Ross. Quinlan, ID3算法

选择属性(A为age时)判断结点

信息获取量(Information Gain)
Gain(A) = Info(D) - Infor_A(D)
Gain(A) =按yes/no分的熵 - 按A属性分类的熵

通过A来作为节点分类获取了多少信息




类似
Gain(income) = 0.029
Gain(student) = 0.151
Gain(credit_rating)=0.048
所以,选择age作为第一个根节点



重复。。。

算法:

*其他算法:

C4.5 : Quinlan

Classification and Regression Trees (CART): (L. Breiman, J. Friedman, R. Olshen, C. Stone)

共同点:都是贪心算法,自上而下(Top-down approach)

区别:属性选择度量方法不同: C4.5 (gain ratio), CART(gini index), ID3 (Information Gain)

先剪枝

后剪枝

直观,便于理解,小规模数据集有效

处理连续变量不好(离散化,阈值选择对结果影响大)

类别较多时,错误增加的比较快

可规模性一般

应用

1. Python

2. Python机器学习的库:scikit-learn

2.1: 特性:

简单高效的数据挖掘和机器学习分析

对所有用户开放,根据不同需求高度可重用性

基于Numpy, SciPy和matplotlib

开源,商用级别:获得 BSD许可

2.2 覆盖问题领域:

分类(classification), 回归(regression), 聚类(clustering), 降维(dimensionality reduction)

模型选择(model selection), 预处理(preprocessing)

3. 使用用scikit-learn

安装scikit-learn: pip, easy_install, windows installer

安装必要package:numpy, SciPy和matplotlib, 可使用Anaconda (包含numpy, scipy等科学计算常用package)

4. 例子:


文档: http://scikit-learn.org/stable/modules/tree.html

安装 Graphviz: http://www.graphviz.org/
配置环境变量
转化dot文件至pdf可视化决策树:dot -Tpdf iris.dot -o outpu.pdf

RID,age,income,student,credit_rating,class_buys_computer
1,youth,high,no,fair,no
2,youth,high,no,excellent,no
3,middle_aged,high,no,fair,yes
4,senior,medium,no,fair,yes
5,senior,low,yes,fair,yes
6,senior,low,yes,excellent,no
7,middle_aged,low,yes,excellent,yes
8,youth,medium,no,fair,no
9,youth,low,yes,fair,yes
10,senior,medium,yes,fair,yes
11,youth,medium,yes,excellent,yes
12,middle_aged,medium,no,excellent,yes
13,middle_aged,high,yes,fair,yes
14,senior,medium,no,excellent,no

# _*_ Coding:utf-8 _*_

from sklearn.feature_extraction import DictVectorizer
import csv
from sklearn import tree
from sklearn import preprocessing

# Read in the csv file and put features into list of dict and list of class label
csv_reader = csv.reader(open('AllElectronics.csv', 'rt'))

headers = next(csv_reader)
print("headers: " + str(headers))
# headers: ['RID', 'age', 'income', 'student', 'credit_rating', 'class_buys_computer']

featureList = []
labelList = []

for row in csv_reader:
    labelList.append(row[len(row) - 1])
    rowDict = {}
    for i in range(1, len(row) - 1):
        rowDict[headers[i]] = row[i]
    featureList.append(rowDict)

print(featureList)
# [{'age': 'youth', 'income': 'high', 'student': 'no', 'credit_rating': 'fair'},
#  {'age': 'youth', 'income': 'high', 'student': 'no', 'credit_rating': 'excellent'},
#  {'age': 'middle_aged', 'income': 'high', 'student': 'no', 'credit_rating': 'fair'},
#  {'age': 'senior', 'income': 'medium', 'student': 'no', 'credit_rating': 'fair'},
#  {'age': 'senior', 'income': 'low', 'student': 'yes', 'credit_rating': 'fair'},
#  {'age': 'senior', 'income': 'low', 'student': 'yes', 'credit_rating': 'excellent'},
#  {'age': 'middle_aged', 'income': 'low', 'student': 'yes', 'credit_rating': 'excellent'},
#  {'age': 'youth', 'income': 'medium', 'student': 'no', 'credit_rating': 'fair'},
#  {'age': 'youth', 'income': 'low', 'student': 'yes', 'credit_rating': 'fair'},
#  {'age': 'senior', 'income': 'medium', 'student': 'yes', 'credit_rating': 'fair'},
#  {'age': 'youth', 'income': 'medium', 'student': 'yes', 'credit_rating': 'excellent'},
#  {'age': 'middle_aged', 'income': 'medium', 'student': 'no', 'credit_rating': 'excellent'},
#  {'age': 'middle_aged', 'income': 'high', 'student': 'yes', 'credit_rating': 'fair'},
#  {'age': 'senior', 'income': 'medium', 'student': 'no', 'credit_rating': 'excellent'}]

print(labelList)
# ['no', 'no', 'yes', 'yes', 'yes', 'no', 'yes', 'no', 'yes', 'yes', 'yes', 'yes', 'yes', 'no']

# Vetorize features
vec = DictVectorizer()
dummyX = vec.fit_transform(featureList).toarray()

print(str(dummyX))
# [[0. 0. 1. 0. 1. 1. 0. 0. 1. 0.]
#  [0. 0. 1. 1. 0. 1. 0. 0. 1. 0.]
#  [1. 0. 0. 0. 1. 1. 0. 0. 1. 0.]
#  [0. 1. 0. 0. 1. 0. 0. 1. 1. 0.]
#  [0. 1. 0. 0. 1. 0. 1. 0. 0. 1.]
#  [0. 1. 0. 1. 0. 0. 1. 0. 0. 1.]
#  [1. 0. 0. 1. 0. 0. 1. 0. 0. 1.]
#  [0. 0. 1. 0. 1. 0. 0. 1. 1. 0.]
#  [0. 0. 1. 0. 1. 0. 1. 0. 0. 1.]
#  [0. 1. 0. 0. 1. 0. 0. 1. 0. 1.]
#  [0. 0. 1. 1. 0. 0. 0. 1. 0. 1.]
#  [1. 0. 0. 1. 0. 0. 0. 1. 1. 0.]
#  [1. 0. 0. 0. 1. 1. 0. 0. 0. 1.]
#  [0. 1. 0. 1. 0. 0. 0. 1. 1. 0.]]

print(vec.get_feature_names())
# ['age=middle_aged', 'age=senior', 'age=youth', 'credit_rating=excellent',
#  'credit_rating=fair', 'income=high', 'income=low', 'income=medium', 'student=no', 'student=yes']

# vectorize class labels
lb = preprocessing.LabelBinarizer()
dummyY = lb.fit_transform(labelList)
print(str(dummyY))
# [[0]
#  [0]
#  [1]
#  [1]
#  [1]
#  [0]
#  [1]
#  [0]
#  [1]
#  [1]
#  [1]
#  [1]
#  [1]
#  [0]]


# Using decision tree for classification
clf = tree.DecisionTreeClassifier(criterion='entropy').fit(dummyX, dummyY)
print(str(clf))
# DecisionTreeClassifier(class_weight=None, criterion='entropy', max_depth=None,
#             max_features=None, max_leaf_nodes=None,
#             min_impurity_decrease=0.0, min_impurity_split=None,
#             min_samples_leaf=1, min_samples_split=2,
#             min_weight_fraction_leaf=0.0, presort=False, random_state=None,
#             splitter='best')


# Visualize model
with open("allElectronicInformationGainOri.dot", 'w') as f:
    f = tree.export_graphviz(clf, feature_names=vec.get_feature_names(), out_file=f)


# 预测分类
oneRowX = dummyX[0, :]  # 取X矩阵数组里面的第一行
print("oneRowX:" + str(oneRowX))
# oneRowX:[0. 0. 1. 0. 1. 1. 0. 0. 1. 0.]

newRowX = oneRowX
newRowX[0] = 1
newRowX[2] = 0
print("newRowX:" + str(newRowX))
# newRowX:[1. 0. 0. 0. 1. 1. 0. 0. 1. 0.]

newRowX = newRowX.reshape(1, -1)
print("newRowX:" + str(newRowX))
# newRowX:[[1. 0. 0. 0. 1. 1. 0. 0. 1. 0.]]

predictedY = clf.predict(newRowX)
print("predictedY:" + str(predictedY))
# predictedY:[1]  true

digraph Tree {
node [shape=box] ;
0 [label="age=middle_aged <= 0.5\nentropy = 0.94\nsamples = 14\nvalue = [5, 9]"] ;
1 [label="student=yes <= 0.5\nentropy = 1.0\nsamples = 10\nvalue = [5, 5]"] ;
0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ;
2 [label="age=youth <= 0.5\nentropy = 0.722\nsamples = 5\nvalue = [4, 1]"] ;
1 -> 2 ;
3 [label="credit_rating=fair <= 0.5\nentropy = 1.0\nsamples = 2\nvalue = [1, 1]"] ;
2 -> 3 ;
4 [label="entropy = 0.0\nsamples = 1\nvalue = [1, 0]"] ;
3 -> 4 ;
5 [label="entropy = 0.0\nsamples = 1\nvalue = [0, 1]"] ;
3 -> 5 ;
6 [label="entropy = 0.0\nsamples = 3\nvalue = [3, 0]"] ;
2 -> 6 ;
7 [label="credit_rating=fair <= 0.5\nentropy = 0.722\nsamples = 5\nvalue = [1, 4]"] ;
1 -> 7 ;
8 [label="age=senior <= 0.5\nentropy = 1.0\nsamples = 2\nvalue = [1, 1]"] ;
7 -> 8 ;
9 [label="entropy = 0.0\nsamples = 1\nvalue = [0, 1]"] ;
8 -> 9 ;
10 [label="entropy = 0.0\nsamples = 1\nvalue = [1, 0]"] ;
8 -> 10 ;
11 [label="entropy = 0.0\nsamples = 3\nvalue = [0, 3]"] ;
7 -> 11 ;
12 [label="entropy = 0.0\nsamples = 4\nvalue = [0, 4]"] ;
0 -> 12 [labeldistance=2.5, labelangle=-45, headlabel="False"] ;
}
decision tree
上一篇下一篇

猜你喜欢

热点阅读