Machine Learning Notes-Decision Trees-Udacity

什么是 Decision Tree?

Decision Tree 可以把 Input 映射到离散的 Labels。对每个节点上的 Attribute 提问,取不同的 Value 走向不同的 Children,最终得到结果。

例如,这是一个不能 Linearly Separated 的问题,但是可以被 Decision Tree 分开。

当 instances 是连续的时候也可以用 DT。

怎样构建 Decision Tree?

先要找到最佳的 Attribute,然后提出合适的问题,可以把数据尽量地分成两份。

ID3 Algorithm 可以用来寻找 Best Attribute。

什么是 Best Attribute?

通俗地讲,就是最好可以直接把数据分成目标类别,用数学的角度衡量就是用 Entropy 来计算 Information Gain。


用 sklearn 来 create 和 train Decision Trees。

Step-1: Decision Tree Classifier

Resources:
http://scikit-learn.org/stable/modules/tree.html#classification

def classify(features_train, labels_train):
    
    ### your code goes here--should return a trained decision tree classifer
    from sklearn import tree
    
    clf=tree.DecisionTreeClassifier()
    clf=clf.fit(features_train, labels_train)
    
    
    return clf
#!/usr/bin/python

""" lecture and example code for decision tree unit """

import sys
from class_vis import prettyPicture, output_image
from prep_terrain_data import makeTerrainData

import matplotlib.pyplot as plt
import numpy as np
import pylab as pl
from classifyDT import classify

features_train, labels_train, features_test, labels_test = makeTerrainData()



### the classify() function in classifyDT is where the magic
### happens--fill in this function in the file 'classifyDT.py'!
clf = classify(features_train, labels_train)


#### grader code, do not modify below this line

prettyPicture(clf, features_test, labels_test)
output_image("test.png", "png", open("test.png", "rb").read())

Decision Tree Boundary 很独特,像现代艺术,还有一些小岛。
但是有些 Overfitting,

Step-2: Accuracy

Resources:
http://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html

import sys
from class_vis import prettyPicture
from prep_terrain_data import makeTerrainData

import numpy as np
import pylab as pl

features_train, labels_train, features_test, labels_test = makeTerrainData()

#################################################################################

########################## DECISION TREE #################################

#### your code goes here
from sklearn import tree
clf=tree.DecisionTreeClassifier()
clf=clf.fit(features_train, labels_train)
labels_predict=clf.predict(features_test)

from sklearn.metrics import accuracy_score


acc = accuracy_score(labels_test,labels_predict)
### you fill this in!
### be sure to compute the accuracy on the test set


    
def submitAccuracies():
  return {"acc":round(acc,3)}

上述 Classifier 得到准确率大约在 91%,在这里有一些 Overfitting,我们也许可以通过 Tuning some Parameters 来改善这个精度。

Step-3: 接下来看哪些 Parameters 可以 Tune

Resource:
Parameters of Decision Tree
http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier

DecisionTreeClassifier 有如下几个 Parameters

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,
class_weight=None,
presort=False)

其中 min_samples_split 如果太小,可能会造成 Overfitting,因为它的意思是,当 Node 上的值小于什么时就不能再分下去了,因此越小的话,分出来的层就越多。当把默认值改成 50 时,就看不到 Overfitting 的那条线了。

用代码运行一下,看哪个值可以得到更高的准确率:

import sys
from class_vis import prettyPicture
from prep_terrain_data import makeTerrainData

import matplotlib.pyplot as plt
import numpy as np
import pylab as pl

features_train, labels_train, features_test, labels_test = makeTerrainData()



########################## DECISION TREE #################################


### your code goes here--now create 2 decision tree classifiers,
### one with min_samples_split=2 and one with min_samples_split=50
### compute the accuracies on the testing data and store
### the accuracy numbers to acc_min_samples_split_2 and
### acc_min_samples_split_50, respectively

from sklearn import tree
clf_2=tree.DecisionTreeClassifier(min_samples_split=2)
clf_2=clf_2.fit(features_train, labels_train)
labels_predict_2=clf_2.predict(features_test)

clf_50=tree.DecisionTreeClassifier(min_samples_split=50)
clf_50=clf_50.fit(features_train, labels_train)
labels_predict_50=clf_50.predict(features_test)

from sklearn.metrics import accuracy_score

acc_min_samples_split_2=accuracy_score(labels_test,labels_predict_2)
acc_min_samples_split_50=accuracy_score(labels_test,labels_predict_50)




def submitAccuracies():
  return {"acc_min_samples_split_2":round(acc_min_samples_split_2,3),
          "acc_min_samples_split_50":round(acc_min_samples_split_50,3)}

比较 min_samples_split 等于50 的时候,精度比 2 的时候大。

{"message": "{'acc_min_samples_split_50': 0.912, 'acc_min_samples_split_2': 0.908}"}

熵,很重要,决定着 Decision Tree 如何划分 data。

Definition: measure of impurity of a bunch of examples.

Formular:

例:
下面这个例子,计算它的 Entropy:

最后的 Entropy 结果如下:


那么熵是如何影响 Decision Tree 的呢?
Information Gain:

Decision Tree 就是要最大化 Information Gain

现在看 grade 这个node上,当 grade=steep 时,slow和fast的熵是多少,当 grade=flat 时,这个熵=0,因为只有一类 fast,取对数时=0. Remember we are calculating entropy, not counting observations. What is the entropy of a set that contains observations of the same class?

例:

数据:


要计算Information Gain:

Entropy of Parent,即 speed

Entropy of Children,即 grade

其中 flat children的熵是:


其中 steep children的熵是:


接着计算公式的后半部分:


最后得到 Information gain=1-3/4*0.9184-0=0.3112

接着计算下一个Children

所以 bumpiness 的 Information Gain=0,也就是我们没有从 bumpiness 得到任何有用的信息。

接着看 speed limit 这个children的 Information Gain=1,也就是非常的 Pure,这是我们希望用来 split 的因素。

综上,
steep children 的 Information gain=0.3112
bumpiness 的 Information Gain=0
speed limit 的 Information Gain=1
所以选择 speed limit 来作为split node。


此外 Decision Tree 的这个Parameter :criterion='gini' 也是可以 Tune 的,gini index 是类似于 metric of impurity,它和 Entropy Information Gain 略有不同,但是效果是一样的。


Bias and Variance


Strengths and Weakness

Weakness:

prone to overfitting: when lots of features, complicate tree
so, need to tune parameters, stop the growth of trees at appropriate time.

Strengths:

Ensemble method: Build bigger classifier out of decision trees,

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,902评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,037评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,978评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,867评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,763评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,104评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,565评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,236评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,379评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,313评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,363评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,034评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,637评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,719评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,952评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,371评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,948评论 2 341

推荐阅读更多精彩内容

  • 多年后,有人问她,你最爱的人为你做过的最让你感动的一件事是什么,她眼角微溢出一点不可控制了的笑意——“他为了...
    爵堯目阅读 219评论 0 1
  • 数据刷新 添加数据 删除数据 更改数据 全局刷新方法(最常用) [self.tableViewreloadData...
    iOS_Cqlee阅读 596评论 0 2
  • 引语:你有没想过,有一天突然惊醒,发现自己在高中的课堂上睡着了。现在经历的所有其实只是一场梦。阳光照的你脸皱成一团...
    肆年ForYou阅读 772评论 2 6