决策树 = 商业分析里最容易跟业务方解释的算法。本文是"商业分析四大算法"系列的第 4 篇,在 UCI Adult Income (48K 样本, 预测收入 >50K) 上跑 4 个模型 (DT / RF / XGBoost / SHAP),反复论证找出业务一致的 Top 3 特征。
CART 树 (sklearn 默认):
分裂准则 = Gini impurity (分类) / MSE (回归)
Gini = 1 - Σ pᵢ² (越小越纯)
关键参数:
max_depth → 深度 (越深越容易过拟合)
min_samples_leaf → 叶节点最小样本数
n_estimators → RF/Boosting 的树数
集成学习 vs 单树:
DT: 可解释,但方差大
RF: bagging → 降方差
XGBoost: boosting → 降偏差
数据集: UCI Adult Income (4MB, 48,842 样本, 14 特征, 目标 = 收入 >50K)。
from sklearn.tree import DecisionTreeClassifier
dt = DecisionTreeClassifier(
max_depth=6, min_samples_leaf=20,
class_weight="balanced", random_state=42
)
dt.fit(X_train, y_train)
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(
n_estimators=300, max_depth=12, min_samples_leaf=10,
class_weight="balanced", random_state=42, n_jobs=-1
)
rf.fit(X_train, y_train)
ratio = (y_train == 0).sum() / (y_train == 1).sum()
xgb = XGBClassifier(
scale_pos_weight=ratio, eval_metric="aucpr",
random_state=42, use_label_encoder=False, n_jobs=-1
)
# Grid 8 组常见参数
for n_est, depth, lr in product([200,400], [4,6], [0.05,0.1]):
xgb.set_params(n_estimators=n_est, max_depth=depth, learning_rate=lr)
xgb.fit(X_train, y_train)
import shap
explainer = shap.TreeExplainer(xgb)
shap_values = explainer.shap_values(X_test[:500])
shap.summary_plot(shap_values, X_test[:500], feature_names=feature_names)
| 模型 | AUC | KS | PR-AUC | Precision | Recall | F1 |
|---|---|---|---|---|---|---|
| Decision Tree | 0.8917 | 0.6280 | 0.7186 | 0.5770 | 0.8082 | 0.6733 |
| Random Forest | 0.9068 | 0.6462 | 0.7785 | 0.5570 | 0.8689 | 0.6789 |
| XGBoost (Grid) | 0.9254 | 0.6828 | 0.8272 | 0.6256 | 0.8466 | 0.7195 |
完 · 2026-08-24 · Chase's Personal Page · 100% 本机真实运行