Classification algorithm - decision trees, random forest

The decision tree classification algorithm

A decision tree is a basic classification method, of course, also be used for regression. We generally only discuss the decision trees for classification. Decision tree model was a tree structure. In the classification problem indicating the instance based on the process of classifying feature, it may be considered a set of if-then rules. In the structure of the decision tree, each path or instances are covered by a rule. Decision tree learning typically includes three steps: feature selection, and generating a decision tree decision tree pruning

Advantages: computational complexity is not high, the output of easy understanding, the intermediate values of the missing insensitive, processing logic can not solve the non-linear regression feature data

Cons: may produce excessive matching problem

Applicable Data Type: numeric and nominal type

Feature Selection

Characterized in that the selected features having selected classification ability of the training data. This can improve the efficiency of decision tree learning, if the use of a feature classification results with the results of random classification is not very different, claimed that this feature is not classed capability. Kyoto throw away such a feature on the experience of learning of the decision tree has little effect. Usually feature selection criterion is the information gain, which is a mathematical concept. An example to understand the process of feature selection.


We want a loan application by the given training data for learning decision trees for loan application to Brunei classification, that is, when a new customer applying for the loan, the decision tree based on the characteristics of the applicant to decide whether to approve the loan application . Feature selection is actually decided to use that feature to divide the feature space. The figure below are in accordance with the age, and whether there is work to get different sub-divided node

The question is to find out which feature selection is better? So Intuitively, if a feature has better classification ability, is that they have the best of each classification under the current conditions, then more should choose this feature. Information gain can be a good representation of the visual criteria. Such a decision tree obtained only two characteristics were determined on:

By decision tree structure information gain generated more pronounced and rapid division category. The following describes the use of the API scikit-learn

Measure and the role of information

我们常说信息有用,那么它的作用如何客观、定量地体现出来呢?信息用途的背后是否有理论基础呢?这个问题一直没有很好的回答,直到1948年,香农在他的论文“通信的数学原理”中提到了“信息熵”的概念,才解决了信息的度量问题,并量化出信息的作用。

一条信息的信息量与其不确定性有着直接的关系,比如我们要搞清一件非常不确定的事,就需要大量的信息。相反如果对某件事了解较多,则不需要太多的信息就能把它搞清楚 。所以从这个角度看,可以认为,信息量就等于不确定的多少。那么如何量化信息量的度量呢?2022年举行世界杯,大家很关系谁是冠军。假如我错过了看比赛,赛后我问朋友 ,“谁是冠军”?他不愿意直接告诉我,让我每猜一次给他一块钱,他告诉我是否猜对了,那么我需要掏多少钱才能知道谁是冠军?我可以把球编上号,从1到32,然后提问:冠 军在1-16号吗?依次询问,只需要五次,就可以知道结果。所以谁是世界杯冠军这条消息只值五块钱。当然香农不是用钱,而是用“比特”这个概念来度量信息量。一个比特是 一位二进制数,在计算机中一个字节是8比特。

那么如果说有一天有64支球队进行决赛阶段的比赛,那么“谁是世界杯冠军”的信息量就是6比特,因为要多猜一次,有的同学就会发现,信息量的比特数和所有可能情况的对数函数log有关,(log32=5,log64=6)

另外一方面你也会发现实际上我们不需要猜五次就能才出冠军,因为像西班牙、巴西、德国、意大利这样的球队夺得冠军的可能性比南非、尼日利亚等球队大得多,因此第一次猜测时不需要把32支球队等分成两个组,而可以把少数几支最有可能的球队分成一组,把其他球队分成一组。然后才冠军球队是否在那几支热门队中。这样,也许三次就猜出结果。因此,当每支球队夺冠的可能性不等时,“谁是世界杯冠军”的信息量比5比特少。香农指出,它的准确信息量应该是:

H = -(p1logp1 + p2logp2 + ... + p32log32)

其中,p1...p32为这三支球队夺冠的概率。H的专业术语称之为信息熵,单位为比特,当这32支球队夺冠的几率相同时,对应的信息熵等于5比特,这个可以通过计算得出。有一个特性就是,5比特是公式的最大值。那么信息熵(经验熵)的具体定义可以为如下:

H(X)=∑​x∈XP(x)logP(x)

信息增益

自古以来,信息和消除不确定性是相联系的。所以决策树的过程其实是在寻找某一个特征对整个分类结果的不确定减少的过程。那么这样就有一个概念叫做信息增益(information gain)。

那么信息增益表示得知特征X的信息而是的类Y的信息的不确定性减少的程度,所以我们对于选择特征进行分类的时候,当然选择信息增益较大的特征,这样具有较强的分类能力。特征A对训练数据集D的信息增益g(D,A),定义为集合D的经验熵H(D)与特征A给定条件下D的经验条件熵H(D|A)之差,即公式为:

g(D,A)=H(D)−H(D∣A)

根据信息增益的准则的特征选择方法是:对于训练数据集D,计算其每个特征的信息增益,并比较它们的阿笑,选择信息增益最大的特征

信息增益的计算


那么条件熵计算如下:

既然我们有了这两个公式,我们可以根据前面的是否通过贷款申请的例子来通过计算得出我们的决策特征顺序。那么我们首先计算总的经验熵为:

计算经验熵

 

class sklearn.tree.DecisionTreeClassifier(criterion='gini', splitter='best', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_split=1e-07, class_weight=None, presort=False)
"""
:param max_depth:int或None,可选(默认=无)树的最大深度。如果没有,那么节点将被扩展,直到所有的叶子都是纯类,或者直到所有的叶子都包含少于min_samples_split样本

:param random_state:random_state是随机数生成器使用的种子
"""

 

首先我们导入类,以及数据集,还有将数据分成训练数据集和测试数据集两部分

from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
estimator = DecisionTreeClassifier(max_leaf_nodes=3, random_state=0)
estimator.fit(X_train, y_train)
method
apply 返回每个样本被预测的叶子的索引

estimator.apply(X)

array([ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 15, 5, 5, 5, 5, 5, 5, 10, 5, 5, 5, 5, 5, 10, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 16, 16,
16, 16, 16, 16, 6, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
8, 16, 16, 16, 16, 16, 16, 14, 16, 16, 11, 16, 16, 16, 8, 8, 16,
16, 16, 14, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16])
decision_path 返回树中的决策路径

dp = estimator.decision_path(X_test)
fit_transform(X,y=None,fit_params)** 输入数据,然后转换

predict(X) 预测输入数据的类型,完整代码

estimator.predict(X_test)
array([2, 1, 0, 2, 0, 2, 0, 1, 1, 1, 2, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0,
0, 1, 0, 0, 1, 1, 0, 2, 1, 0, 1, 2, 1, 0, 2])

print y_test

array([2, 1, 0, 2, 0, 2, 0, 1, 1, 1, 2, 1, 1, 1, 1, 0, 1, 1, 0, 0, 2, 1, 0,
0, 2, 0, 0, 1, 1, 0, 2, 1, 0, 2, 2, 1, 0, 1])
score(X,y,sample_weight=None) 返回给定测试数据的准确精度

estimator.score(X_test,y_test)

0.89473684210526316
决策树本地保存
sklearn.tree.export_graphviz() 该函数能够导出DOT格式

from sklearn.datasets import load_iris
from sklearn import tree
clf = tree.DecisionTreeClassifier()
iris = load_iris()
clf = clf.fit(iris.data, iris.target)
tree.export_graphviz(clf,out_file='tree.dot')
那么有了tree.dot文件之后,我们可以通过命令转换为png或者pdf格式,首先得安装graphviz

ubuntu:sudo apt-get install graphviz
Mac:brew install graphviz
然后我们运行这个命令

$ dot -Tps tree.dot -o tree.ps
$ dot -Tpng tree.dot -o tree.png
或者,如果我们安装了Python模块pydotplus,我们可以直接在Python中生成PDF文件,通过pip install pydotplus,然后运行

import pydotplus
dot_data = tree.export_graphviz(clf, out_file=None)
graph = pydotplus.graph_from_dot_data(dot_data)
graph.write_pdf("iris.pdf")
查看决策树结构图片,这个结果是经过决策树学习的三个步骤之后形成的。当作了解

扩展:所有各种决策树算法是什么,它们之间有什么不同?哪一个在scikit-learn中实现?

ID3 --- 信息增益 最大的准则

C4.5 --- 信息增益比 最大的准则

CART 回归树: 平方误差 最小 分类树: 基尼系数 最小的准则 在sklearn中可以选择划分的原则

决策树优缺点分析
决策树的一些优点是:

简单的理解和解释。树木可视化。

需要很少的数据准备。其他技术通常需要数据归一化,需要创建虚拟变量,并删除空值。但请注意,此模块不支持缺少值。

使用树的成本(即,预测数据)在用于训练树的数据点的数量上是对数的。

决策树的缺点包括:

决策树学习者可以创建不能很好地推广数据的过于复杂的树。这被称为过拟合。修剪(目前不支持)的机制,设置叶节点所需的最小采样数或设置树的最大深度是避免此问题的必要条件。

决策树可能不稳定,因为数据的小变化可能会导致完全不同的树被生成。通过使用合奏中的决策树来减轻这个问题。

集成方法(分类)之随机森林
在机器学习中,随机森林是一个包含多个决策树的分类器,并且其输出的类别是由个别树输出的类别的众数而定。利用相同的训练数搭建多个独立的分类模型,然后通过投票的方式,以少数服从多数的原则作出最终的分类决策。例如, 如果你训练了5个树, 其中有4个树的结果是True, 1个数的结果是False, 那么最终结果会是True.

在前面的决策当中我们提到,一个标准的决策树会根据每维特征对预测结果的影响程度进行排序,进而决定不同的特征从上至下构建分裂节点的顺序,如此以来,所有在随机森林中的决策树都会受这一策略影响而构建的完全一致,从而丧失的多样性。所以在随机森林分类器的构建过程中,每一棵决策树都会放弃这一固定的排序算法,转而随机选取特征。

学习算法
根据下列算法而建造每棵树:

用N来表示训练用例(样本)的个数,M表示特征数目。
输入特征数目m,用于确定决策树上一个节点的决策结果;其中m应远小于M。
从N个训练用例(样本)中以有放回抽样的方式,取样N次,形成一个训练集(即bootstrap取样),并用未抽到的用例(样本)作预测,评估其误差。
对于每一个节点,随机选择m个特征,决策树上每个节点的决定都是基于这些特征确定的。根据这m个特征,计算其最佳的分裂方式。
sklearn.ensemble,集成方法模块
sklearn.ensemble提供了准确性更加好的集成方法,里面包含了主要的RandomForestClassifier(随机森林)方法。

class sklearn.ensemble.RandomForestClassifier(n_estimators=10, criterion=’gini’, max_depth=None, bootstrap=True, oob_score=False, n_jobs=1, random_state=None)
"""
:param n_estimators:integer,optional(default = 10) 森林里的树木数量。

:param criteria:string,可选(default =“gini”)分割特征的测量方法

:param max_depth:integer或None,可选(默认=无)树的最大深度

:param bootstrap:boolean,optional(default = True)是否在构建树时使用自举样本。

"""
属性
classes_:shape = [n_classes]的数组或这样的数组的列表,类标签(单输出问题)或类标签数组列表(多输出问题)。
featureimportances:array = [n_features]的数组, 特征重要性(越高,功能越重要)。
方法
fit(X,y [,sample_weight]) 从训练集(X,Y)构建一棵树林。

predict(X) 预测X的类

score(X,y [,sample_weight]) 返回给定测试数据和标签的平均精度。

decision_path(X) 返回森林中的决策路径

泰坦尼克号乘客数据案例
这里我们通过决策树和随机森林对这个数据进行一个分类,判断乘客的生还。

完整代码

import pandas as pd
import sklearn
from sklearn.cross_validation import train_test_split
from sklearn.feature_extraction import DictVectorizer
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier


titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt')

#选取一些特征作为我们划分的依据
x = titanic[['pclass', 'age', 'sex']]
y = titanic['survived']

# 填充缺失值
x['age'].fillna(x['age'].mean(), inplace=True)

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)

dt = DictVectorizer(sparse=False)

print(x_train.to_dict(orient="record"))

# 按行,样本名字为键,列名也为键,[{"1":1,"2":2,"3":3}]
x_train = dt.fit_transform(x_train.to_dict(orient="record"))

x_test = dt.fit_transform(x_test.to_dict(orient="record"))

# 使用决策树
dtc = DecisionTreeClassifier()

dtc.fit(x_train, y_train)

dt_predict = dtc.predict(x_test)

print(dtc.score(x_test, y_test))

print(classification_report(y_test, dt_predict, target_names=["died", "survived"]))

# 使用随机森林

rfc = RandomForestClassifier()

rfc.fit(x_train, y_train)

rfc_y_predict = rfc.predict(x_test)

print(rfc.score(x_test, y_test))

print(classification_report(y_test, rfc_y_predict, target_names=["died", "survived"]))

                                                                      

Guess you like

Origin www.cnblogs.com/lax-17xu/p/11792422.html