【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_很小,不代表这个特征没有提供任何信息,只能说明这个特征没有被树选中,可能是因为另一个特征也包含的同样的信息。

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

相关推荐
明明如月学长几秒前
OpenClaw 帮我睡后全自动完成了老板交代的任务
人工智能
用户962377954487 分钟前
🚀 docx2md-picgo:Word 文档图片一键上传图床工具
python·markdown
uuware10 分钟前
Lupine.Press + AI 助您分分钟搞定技术项目的文档网站
人工智能·前端框架
海上日出13 分钟前
使用 QuantStats 进行投资组合绩效分析:Python 量化实战指南
人工智能
Qinana14 分钟前
150行代码搞定私有知识库!Node.js + LangChain 打造最小化 RAG 系统全流程
人工智能·程序员·node.js
猿猿长成记15 分钟前
AI专栏 | AI大法则之思维链、自洽性、思维树
人工智能
用户51914958484522 分钟前
CrushFTP 条件竞争认证绕过漏洞利用工具 (CVE-2025-54309)
人工智能·aigc
一拳不是超人30 分钟前
AI时代,35岁程序员焦虑终结:经验从负债变资产
人工智能·程序员
IT_陈寒1 小时前
Vite快得离谱?揭秘它比Webpack快10倍的5个核心原理
前端·人工智能·后端
风象南2 小时前
OpenClaw 登顶 GitHub Star 榜首:一个程序员 13 年后的"重新点火"故事
人工智能·后端