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

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

相关推荐
IT_陈寒7 分钟前
React的useEffect依赖数组把我坑惨了
前端·人工智能·后端
大模型真好玩8 分钟前
DeepSeek Harness 插件的服务与事件监听详解
人工智能·agent·deepseek
迪菲赫尔曼10 分钟前
【基础篇 11】把官方源码放到服务器:版本、解压层级和安装位置,一次弄清楚
运维·服务器·开发语言·人工智能·python·yolo·目标检测
用户83562907805114 分钟前
Python 调整 Excel 工作表显示设置
后端·python
阿里云大数据AI技术15 分钟前
阿里云DLF年度发布:Agentic Lake全模态 AI 数据湖底座
人工智能
小咕聊编程1 小时前
教育大数据可视化系统
python·django·flask
lusklusklusk1 小时前
Python 巡检脚本:进程运行状态、数据库写入时效检查及邮件通知与告警
数据库·python·oracle
玩AI的奶茶1 小时前
MiniMax H3 出 30 秒长片:显存账、拼接法和一次的成本
大数据·人工智能·ai·gpu算力·算力租赁
杭州默安科技1 小时前
从“被动响应”到“主动遏制”:AI Agent时代,网络防御体系如何重构?
人工智能·网络安全·ai智能体
Angeldream1231 小时前
第 10 章 医学影像伦理与安全
图像处理·人工智能·python·安全·机器学习·医学影像