1. 对于决策树的两种理解:
- 由if-then规则组成的集合
- 定义在特征空间上的类的条件概率分布
2. 决策树的三大要素:
特征选择,树的生成,树的剪枝
常用的决策树生成算法有: ID3,C4.5,CART
要素 | 注意要点 |
---|---|
特征选择 | 信息增益(ID3):过多关注取值可能较多的属性 信息增益比(C4.5):信息增益除以该属性的熵,不再关注取值可能较多的属性 基尼指数(CART):生成二叉树,对于某一个取值只区分是与否两种情况 |
树的生成 | 离散属性只能一次用于分割,连续属性可多次使用 可设置分割阈值,达不到阈值则不分割 |
树的剪枝 | 对于ID3和C4.5算法,定义损失函数 Loss=各个叶节点的熵之和+α*叶节点个数,α可用于控制树的复杂程度,剪枝过程为对于每个中间节点计算剪枝和不剪枝两种情况下整棵决策树的损失函数取值,比较两者大小,然后决定是否剪枝,而CART树的剪枝过程较复杂,具体见李航《统计学习方法》。 |
数据集:ch05-data.txt
青年 否 否 一般 否
青年 否 否 好 否
青年 是 否 好 是
青年 是 是 一般 是
青年 否 否 一般 否
中年 否 否 一般 否
中年 否 否 好 否
中年 是 是 好 是
中年 否 是 非常好 是
中年 否 是 非常好 是
老年 否 是 非常好 是
老年 否 是 好 是
老年 是 否 好 是
老年 是 否 非常好 是
老年 否 否 一般 否
代码:
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Created on 2020/1/23 14:47
@author: phil
"""
import numpy as np
class Node:
def __init__(self, split_index, pred_label=None):
self.split_index = split_index # 如果是中间节点则为用于分割的属性的索引,否则为None
self.pred_label = pred_label # 如果是叶节点则对应预测label,否则为None
self.children = {} # 存储孩子节点信息的字典,key为用于分割的属性的取值,value为子树
def empirical_entropy(col):
# 计算col列数据对应的经验熵
unique = np.unique(col) # col列所有可能的取值
ans = 0.0 # 经验熵
for i in range(len(unique)):
p = np.sum(col == unique[i]) / len(col)
ans += -p * np.log2(p)
return ans
def empirical_conditional_entropy(feature_col, label_col):
# 计算经验条件熵,feature_col为属性取值,label_col为标签列取值
unique = np.unique(feature_col)
ans = 0.0
for i in range(len(unique)):
feature_p = np.sum(unique[i] == feature_col) / len(feature_col)
ans += feature_p * empirical_entropy(label_col[np.where(feature_col == unique[i])])
return empirical_entropy(label_col) - ans
class DecisionTree:
def __init__(self):
self.root = None
def fit(self, X, y, tree_type="ID3"):
# 使用X,y构建决策树,tree_type指定树的类型
def build_tree(X, y, used_index, tree_type="ID3"):
# 当所有的数据点label都一样的时候则产生叶节点
if np.all(y == y[0]):
return Node(split_index=None, pred_label=y[0])
# 当所有的feature都已用于分割子树时则产生叶节点,预测label为当前节点对应的数据中出现次数最多的label
if len(used_index) == len(X[0]):
unique, counts = np.unique(y, return_counts=True)
return Node(split_index=None, pred_label=unique[np.argmax(counts)])
if tree_type == "ID3":
# ID3根据信息增益选择当前样本集的切分属性
feature_gain_ratio = []
# 计算每个属性的信息增益
for feature_index in range(len(X[0])):
feature_gain_ratio.append(empirical_conditional_entropy(X[:, feature_index], y))
# 在没有使用过属性中选择信息增益最大的属性作为切分属性
feature_gain_ratio = np.array(feature_gain_ratio)
if len(used_index) > 0:
feature_gain_ratio[np.array(used_index)] = 0 # 先将所有已经使用过的属性的信息增益设置为0
split_index = feature_gain_ratio.argmax() # 选出信息增益最大的属性作为切分属性,这里没有设置信息增益阈值
# 将已用于切分的属性加入到列表中
used_index.append(split_index)
# 根据选择的属性进行分割
node = Node(split_index=split_index, pred_label=None)
unique = np.unique(X[:, split_index])
for i in range(len(unique)):
selected_index = np.where(X[:, split_index] == unique[i])
node.children[unique[i]] = build_tree(X[selected_index], y[selected_index], used_index[:], tree_type=tree_type)
return node
elif tree_type == "C4.5":
# C4.5根据信息增益比选择当前样本集的切分属性
pass
elif tree_type == "CART":
# CART当属性为离散值时选择基尼指数选择当前样本集的切分属性
# 当属性为连续值时使用平方误差最小化准则选择切分属性
pass
self.root = build_tree(X, y, [])
def predict(self, X):
# 根据决策树对X进行预测
def predict_helper(Xi, node):
if node.pred_label is not None:
return node.pred_label
split_value = Xi[node.split_index]
return predict_helper(Xi, node.children[split_value])
preds = []
for i in range(X.shape[0]):
preds.append(predict_helper(X[i, :], self.root))
return np.array(preds)
if __name__ == "__main__":
path = r"ch05-data.txt"
X = []
y = []
with open(path, "r", encoding="utf-8") as f:
for line in f.readlines():
splited = line.strip().split(" ")
X.append(splited[:-1])
y.append(splited[-1])
X = np.array(X)
y = np.array(y)
print("原始数据")
print(X)
print(y)
model = DecisionTree()
model.fit(X, y)
print("预测值:")
print(model.predict(X))