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

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

相关推荐
好开心啊没烦恼18 分钟前
Python 数据分析:DataFrame,生成,用字典创建 DataFrame ,键值对数量不一样怎么办?
开发语言·python·数据挖掘·数据分析
AIbase202423 分钟前
国内MCP服务平台推荐!aibase.cn上线MCP服务器集合平台
运维·服务器·人工智能
周树皮不皮1 小时前
20250704【翻转&二叉树】|Leetcodehot100之226【pass】&今天计划
python
魔芋红茶1 小时前
spring-initializer
python·学习·spring
喜欢吃豆1 小时前
快速手搓一个MCP服务指南(九): FastMCP 服务器组合技术:构建模块化AI应用的终极方案
服务器·人工智能·python·深度学习·大模型·github·fastmcp
星融元asterfusion1 小时前
基于路径质量的AI负载均衡异常路径检测与恢复策略
人工智能·负载均衡·异常路径
一个天蝎座 白勺 程序猿1 小时前
Python(28)Python循环语句指南:从语法糖到CPython字节码的底层探秘
开发语言·python
zskj_zhyl1 小时前
智慧养老丨从依赖式养老到自主式养老:如何重构晚年生活新范式
大数据·人工智能·物联网
创小匠1 小时前
创客匠人视角下创始人 IP 打造与知识变现的底层逻辑重构
人工智能·tcp/ip·重构