张芷铭的个人博客

Gini 重要性(平均不纯度减少)是随机森林中评估特征重要性的核心指标,通过量化特征对节点分裂的贡献度进行排序。

定义

特征重要性 = 该特征在所有决策树中带来的基尼不纯度减少量的平均值。

数学推导

基尼不纯度

$$G = 1 - \sum_{k=1}^{K}p_k^2$$

  • $G=0$:纯度最高(所有样本同类)
  • $G=(K-1)/K$:纯度最低(样本均匀分布)

不纯度减少量

$$\Delta G(k,j) = G(k) - \frac{N_{left}}{N_k}G(left_k) - \frac{N_{right}}{N_k}G(right_k)$$

Gini 重要性聚合

$$FI_{Gini}(j) = \frac{1}{T}\sum_{t=1}^{T}FI_t(j)$$

核心性质

优势局限性
计算高效(仅平方运算)高基数特征偏向
可解释性强训练数据依赖
适配大规模数据相关特征相互稀释
集成鲁棒性不适用于回归任务

适用场景

适用:分类任务特征筛选、模型可解释性分析、大规模数据探索

不适用:因果分析、高基数特征场景、回归任务、高精度评估

代码实现

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
import numpy as np

data = load_iris()
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(data.data, data.target)

importances = rf.feature_importances_
indices = np.argsort(importances)[::-1]

for idx in indices:
    print(f"{data.feature_names[idx]}: {importances[idx]:.4f}")

去偏实现

1
2
3
4
5
6
7
8
from ranger import RangerForestClassifier

rf_debias = RangerForestClassifier(
    n_estimators=100,
    importance="impurity_debiased"  # 启用去偏
)
rf_debias.fit(X, y)
debiased_importances = rf_debias.feature_importances_

实践技巧

  1. 规避高基数偏向:合并低频类别、结合排列重要性验证
  2. 参数调优n_estimators≥100、限制 max_depth 减少过拟合
  3. 结果解读:关注排序而非绝对值、处理类别不平衡后再评估

Comments