【Python机器学习】决策树——树的特征重要性

利用一些有用的属性来总结树的工作原理,其中最常用的事特征重要性,它为每个特征树的决策的重要性进行排序。对于每个特征来说,它都是介于0到1之间的数字,其中0代表"根本没有用到",1代表"完美预测目标值"。特征重要性的求和为1。

将特征重要性进行可视化:

python 复制代码
import mglearn.datasets
import numpy as np
from sklearn.tree import DecisionTreeClassifier,export_graphviz
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer


def plot_importances(model):
    n_feature=cancer.data.shape[1]
    plt.barh(range(n_feature),model.feature_importances_,align='center')
    plt.yticks(np.arange(n_feature),cancer.feature_names)
    plt.xlabel('特征重要性')
    plt.ylabel('特征')

plt.rcParams['font.sans-serif'] = ['SimHei']

cancer=load_breast_cancer()
X_train,X_test,y_train,y_test=train_test_split(
    cancer.data,cancer.target,stratify=cancer.target,random_state=42
)
tree=DecisionTreeClassifier(max_depth=4,random_state=0)
tree.fit(X_train,y_train)

plot_importances(tree)
plt.show()

可以看到,"worst radius" 是最重要的特征。

如果某个特征的feature_importance_很小,不代表这个特征没有提供任何信息,只能说明这个特征没有被树选中,可能是因为另一个特征也包含的同样的信息。

与线性模型的系数不同,决策树的特征重要性一定为正数。

相关推荐
故乡de云9 小时前
IntelliJ IDEA 接入 Code0:OpenAI 兼容接口的配置、模型名与常见错误排查
人工智能
cd_949217219 小时前
为什么AI3D创作中贴图材质尤为重要?因为它决定模型能否成为可用资产
人工智能·3d·贴图
智圣新创0110 小时前
重构沉浸式育人链路:智圣新创智慧学生社区平台建设的行业全域参考
大数据·人工智能·重构
Proaiapi10 小时前
GPT-5.6 使用指南:从 ChatGPT 到 Codex,AI 开发进入 Agent 时代
人工智能·gpt·chatgpt
冬奇Lab10 小时前
MCP 系列(07):企业级部署——安全、认证与版本管理
人工智能·llm·mcp
老余说AI10 小时前
AI声音克隆的“冰与火之歌“:你的声音正在被谁盗用?
人工智能·跨境电商·soundview
ywl47081208710 小时前
【SpringAI 09】SpringAI入门
人工智能·springai
yaoxin52112311 小时前
462. Java 反射 - 获取声明类与封闭类
java·开发语言·python
米小虾11 小时前
2026 AI智能体十大趋势:从工具到伙伴,Agent正在重塑什么?
人工智能
We0 AI11 小时前
2026 年 SEO 友好型网站构建器对比:We0 AI、Webflow、WordPress、10Web,谁更适合被收录?
人工智能·#ai建站