Decision Tree Classifier
from sklearn.tree import DecisionTreeClassifier as DTC
y = df.target
X = df.features
dtc = DTC(criterion='entropy', mim_samples_slit=20, random_state=90)
dtc.fit(X, y)
official example
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier(random_state=0)
iris = load_iris()
cross_val_score(clf, iris.data, iris.target, cv=10)
Visualizing the tree
in advance you should install Graphviz
from sklearn.tree import export_graphviz
def visualize_tree(tree, feature_names):
"""Create tree png using graphviz.
Args
----
tree -- scikit-learn DecsisionTree.
feature_names -- list of feature names.
usage
---
features = X.columns
visualize_tree(dtc, features)
"""
with open("dt.dot", 'w') as f:
export_graphviz(tree, out_file=f,
feature_names=feature_names)
#generate png
command = ["dot", "-Tpng", "dt.dot", "-o", "dt.png"]
#or pdf
#command = ["dot", "-Tpdf", "dt.dot", "-o", "dt.pdf"]
try:
subprocess.check_call(command)
except:
exit("Could not run dot, ie graphviz, to "
"produce visualization")
#open image
from PIL import Image
im = Image.open("od.png")
im.show()
Decision Tree Regression
Decision Tree Regression with AdaBoost
from sklearn.tree import DecisionTreeRegressor
regr = DecisionTreeRegressor(max_depth=2)
regr.fit(X, y)
y_predict = regr_1.predict(X_test)
ID3 (Iterative Dichotomiser)
属性集合 A={a1,a2,…,am} 如{身高,体重,是否近视}
样本集合 D={(x1;y1),(x2;y2),…,(xm;ym)} 如{(身高175,体重63,近视1;不符合应聘要求0),…}
根据某属性a的划分 D1,D2,…
informathin entropy
pk 是每类样本占当前样本集合 D 中的比例
Ent越小纯度越高
决策树根节点的D包含所有样本,如果y只有0,1两个取值,正3个负2个,则
information gain
根据某属性a划分得到
Dv(v=1,2,…,V)
Gain越大划分得到的纯度提升越高
example
假设有A = {行为习惯,饮食偏好, 体育运动}三个属性,判断是否会得某种病。
总共6个得病9个不得
行为习惯 | 得病 | 不得病 | 得病占该习惯总数比例 | 该行为习惯占总人数的比例 |
---|---|---|---|---|
抽烟 | 1 | 5 | 1/6 | 6/15 |
喝酒 | 2 | 3 | 2/5 | 5/15 |
吸毒 | 3 | 1 | 3/4 | 4/15 |
根据行为习惯划分出抽烟,喝酒,吸毒三个子集 D1,D2,D3
之后再算 Gain(D,饮食偏好)
假设 Gain(D,行为习惯)>Gain(D,饮食偏好)>Gain(D,体育运动)
那么分别取 D1,D2,D3 为新的D,剩下的属性为A={饮食偏好,体育运动} ,进行迭代算 Gain(D,饮食偏好) 和 Gain(D,体育运动)
C4.5
基于增益率(gain ratio)减少ID3偏好可取数目多带来的影响。
剪枝
预剪枝
划分训练集和测试集。
如果使用某一划分,算出验证集精度。
如果停止划分采用样本中占多数的结果作为该分支结果,计算精度。
如果停止划分精度反而更高则停止划分。
后剪枝
从完整的决策树的倒数第二个节点开始。
如果剪掉倒数第一个节点精度提高则剪掉。
依次往上类推
连续数据
采用二分法划分,既划分成 ≤t 和 >t , t取遍两个相邻离散数据的平均值然后找出信息熵增Gain最小的。
缺失值处理
先算出对该属性而言无缺失值的Entropy, 然后计算出对该属性而言无缺失值的Gain。
然后乘上无缺失值样本所占比例 ρ 最终的Gain。
多变量决策树(multivariate decision tree)
使用斜线来划分多变量。
既用多变量的线性组合 W⋅Attribtes≤t? 来划分。