大家好!上一篇文章我们介绍了什么是决策树(👇点击回顾),今天我们来聊聊决策树家族的三大经典算法:CART、ID3和C4.5。它们就像三位武林高手🥷,各有绝技,在机器学习江湖中占据重要地位。让我们一起来揭开它们的神秘面纱吧!
📚 决策树三种算法对比(速查表)
| 特性 | ID3 | C4.5 | CART |
|---|---|---|---|
| 适用场景 | 分类 | 分类 | 分类+回归 |
| 分裂标准 | 信息增益 | 增益率 | 基尼指数/均方误差 |
| 树结构 | 多叉树 | 多叉树 | 二叉树 |
| 连续值处理 | ❌ | ✅ | ✅ |
| 缺失值处理 | ❌ | ✅ | ✅ |
| 主流工具 | 少 | 少 | sklearn |
| 剪枝 | 不支持 | 支持 | 支持 |
| 特征类型 | 仅离散 | 离散+连续 | 离散+连续 |
📊 三大决策树算法详解
⚙️ 1. ID3算法:信息增益的奠基者
定义:是最早的决策树算法之一,核心思想是选择信息增益最大的特征进行划分。ID3 只能对离散属性的数据集构造决策树。
原理:

H(D):数据集D的熵(混乱度)D_v:按特征取值划分的子集
特点:- 🚫 只能处理离散特征
- 🚫 容易偏向取值多的特征
- 🚫 不支持剪枝,容易过拟合
示例场景:
- 天气预报(晴/雨/阴)
- 水果分类(苹果/香蕉/橙子)
💻 ID3简易代码实现:
import numpy as np
from collections import Counter
class ID3DecisionTree:
def __init__(self, max_depth=3):
self.max_depth = max_depth
self.tree = None
def _entropy(self, y):
"""计算熵"""
counts = np.bincount(y)
probs = counts / len(y)
return -np.sum([p * np.log2(p) for p in probs if p > 0])
def _best_split(self, X, y, feature_types):
"""寻找最佳划分特征(仅离散特征)"""
best_gain = -1
best_feature = None
current_entropy = self._entropy(y)
for feature in range(X.shape[1]):
if feature_types[feature] == 'continuous': # ID3不支持连续特征
continue
values = np.unique(X[:, feature])
for value in values:
left_indices = X[:, feature] == value
right_indices = ~left_indices
if len(y[left_indices]) == 0 or len(y[right_indices]) == 0:
continue
left_entropy = self._entropy(y[left_indices])
right_entropy = self._entropy(y[right_indices])
gain = current_entropy - \
(len(y[left_indices])/len(y)) * left_entropy - \
(len(y[right_indices])/len(y)) * right_entropy
if gain > best_gain:
best_gain = gain
best_feature = feature
return best_feature
def _build_tree(self, X, y, feature_types, depth=0):
"""递归构建决策树"""
n_samples, n_features = X.shape
n_classes = len(np.unique(y))
if (depth >= self.max_depth or
n_samples < 2 or
n_classes == 1):
leaf_value = Counter(y).most_common(1)[0][0]
return {'leaf': True, 'value': leaf_value}
feature = self._best_split(X, y, feature_types)
if feature is None:
leaf_value = Counter(y).most_common(1)[0][0]
return {'leaf': True, 'value': leaf_value}
values = np.unique(X[:, feature])
subtrees = {}
for value in values:
indices = X[:, feature] == value
subtree

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



