博客
关于我
Python中进行特征重要性分析的9个常用方法
阅读量:797 次
发布时间:2023-03-09

本文共 5693 字,大约阅读时间需要 18 分钟。

特征重要性分析方法

特征重要性分析是机器学习中评估每个特征对模型预测结果影响大小的一种重要方法。通过这种分析,我们可以识别哪些特征对模型性能贡献最大,从而优化模型结构、减少过拟合并提高预测准确性。

1. 排列重要性 (PermutationImportance)

这是一种经典的特征重要性评估方法。通过随机排列每个特征的值,并监控模型性能下降的程度,可以判断特征的重要性。特征排列后性能下降越大,说明该特征越重要。

示例代码:

from sklearn.datasets import load_breast_cancerfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.inspection import permutation_importancefrom sklearn.model_selection import train_test_splitimport matplotlib.pyplot as plt# 加载数据集cancer = load_breast_cancer()X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target, random_state=1)# 训练随机森林模型rf = RandomForestClassifier(n_estimators=100, random_state=1)rf.fit(X_train, y_train)# 基线准确率baseline = rf.score(X_test, y_test)# 计算排列重要性result = permutation_importance(rf, X_test, y_test, n_repeats=10, random_state=1, scoring='accuracy')importances = result.importances_mean# 绘制排列重要性图plt.bar(range(len(importances)), importances)plt.xlabel('特征索引')plt.ylabel('排列重要性')plt.show()

2. 内置特征重要性 (coef_ 或 feature_importances_)

一些模型(如线性回归和随机森林)提供了内置的特征重要性评分。这些评分反映了每个特征对模型预测的贡献大小。

示例代码:

from sklearn.datasets import load_breast_cancerfrom sklearn.ensemble import RandomForestClassifier# 加载数据集X, y = load_breast_cancer(return_X_y=True)# 训练随机森林模型rf = RandomForestClassifier(n_estimators=100, random_state=1)rf.fit(X, y)# 查看特征重要性importances = rf.feature_importances_# 绘制特征重要性图plt.bar(range(X.shape[1]), importances)plt.xlabel('特征索引')plt.ylabel('特征重要性')plt.show()

3. Leave-one-out Cross-Validation

这种方法通过逐一移除每个特征,评估模型性能下降的程度来计算特征重要性。

示例代码:

from sklearn.datasets import load_breast_cancerfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.metrics import accuracy_scoreimport matplotlib.pyplot as pltimport numpy as np# 加载数据集X, y = load_breast_cancer(return_X_y=True)# 拆分训练集和测试集X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)# 训练随机森林模型rf = RandomForestClassifier(n_estimators=100, random_state=1)rf.fit(X_train, y_train)# 计算基线准确率base_acc = accuracy_score(y_test, rf.predict(X_test))# 初始化重要性列表importances = []# 逐一移除每个特征并评估准确率for i in range(X_train.shape[1]):    X_temp = np.delete(X_train, i, axis=1)    temp_rf = RandomForestClassifier()    temp_rf.fit(X_temp, y_train)    acc = accuracy_score(y_test, temp_rf.predict(np.delete(X_test, i, axis=1)))    importances.append(base_acc - acc)# 绘制特征重要性图plt.bar(range(len(importances)), importances)plt.xlabel('特征索引')plt.ylabel('特征重要性')plt.show()

4. 相关性分析

计算特征与目标变量之间的相关性,相关性越高的特征越重要。

示例代码:

import pandas as pdfrom sklearn.datasets import load_breast_cancer# 加载数据集X, y = load_breast_cancer(return_X_y=True)# 创建DataFramedf = pd.DataFrame(X, columns=range(30))df['y'] = y# 计算相关性correlations = df.corrwith(df.y).abs()# 排序并绘图correlations.sort_values(ascending=False).plot.bar()

5. 递归特征消除 (Recursive Feature Elimination)

通过递归删除特征,并观察模型性能的变化来确定特征的重要性。

示例代码:

from sklearn.ensemble import RandomForestClassifierfrom sklearn.feature_selection import RFEimport pandas as pdfrom sklearn.datasets import load_breast_cancerimport matplotlib.pyplot as plt# 加载数据集X, y = load_breast_cancer(return_X_y=True)# 创建DataFramedf = pd.DataFrame(X, columns=range(30))df['y'] = y# 训练随机森林模型rf = RandomForestClassifier()# 递归特征消除rfe = RFE(rf, n_features_to_select=10)rfe.fit(X, y)# 输出特征排名print(rfe.ranking_)

6. XGBoost 特性重要性

XGBoost模型提供了特征重要性评分,用于衡量特征在树拆分中的贡献。

示例代码:

import xgboost as xgbimport pandas as pdfrom sklearn.datasets import load_breast_cancerimport matplotlib.pyplot as plt# 加载数据集X, y = load_breast_cancer(return_X_y=True)# 创建DataFramedf = pd.DataFrame(X, columns=range(30))df['y'] = y# 训练XGBoost模型model = xgb.XGBClassifier()model.fit(X, y)# 查看特征重要性importances = model.feature_importances_# 绘制特征重要性图importances = pd.Series(importances, index=X.shape[1])importances.plot.bar()

7. 主成分分析 (PCA)

通过主成分分析(PCA),可以识别具有较高方差贡献的特征,从而评估其重要性。

示例代码:

from sklearn.decomposition import PCAimport pandas as pdfrom sklearn.datasets import load_breast_cancerimport matplotlib.pyplot as plt# 加载数据集X, y = load_breast_cancer(return_X_y=True)# 创建DataFramedf = pd.DataFrame(X, columns=range(30))df['y'] = y# 进行PCA分析pca = PCA()pca.fit(X)# 绘制主成分解释方差图plt.bar(range(pca.n_components_), pca.explained_variance_ratio_)plt.xlabel('PCA组件')plt.ylabel('解释方差')plt.show()

8. 方差分析 (ANOVA)

使用方差分析(ANOVA)来衡量特征与目标变量之间的关系,f值越大特征越重要。

示例代码:

from sklearn.feature_selection import f_classifimport pandas as pdfrom sklearn.datasets import load_breast_cancerimport matplotlib.pyplot as plt# 加载数据集X, y = load_breast_cancer(return_X_y=True)# 创建DataFramedf = pd.DataFrame(X, columns=range(30))df['y'] = y# 计算f值fval = f_classif(X, y)# 绘制f值图fval = pd.Series(fval[0], index=range(X.shape[1]))fval.plot.bar()

9. 卡方检验

通过卡方检验,评估特征是否独立于目标变量,卡方值越高特征越重要。

示例代码:

from sklearn.feature_selection import chi2import pandas as pdfrom sklearn.datasets import load_breast_cancerimport matplotlib.pyplot as plt# 加载数据集X, y = load_breast_cancer(return_X_y=True)# 创建DataFramedf = pd.DataFrame(X, columns=range(30))df['y'] = y# 计算卡方值chi_scores = chi2(X, y)# 绘制卡方值图chi_scores = pd.Series(chi_scores[0], index=range(X.shape[1]))chi_scores.plot.bar()

为什么不同的方法会检测到不同的特征?

不同的特征重要性方法可能会识别出不同的特征是最重要的,这是因为:

  • 不同的重要性衡量方式:

    • 排列重要性通过性能下降来衡量特征重要性。
    • 内置重要性(如随机森林和XGBoost)基于模型内部评分。
    • PCA关注方差贡献,其他方法则关注特征与目标变量的相关性。
  • 模型差异:

    • 线性模型(如Linear Regression)强调线性关系。
    • 树模型(如Random Forest)更关注特征的分类能力。
    • 深度学习模型则考虑复杂的非线性关系。
  • 交互作用:

    • 一些方法(如RFE)可以捕捉特征之间的相互作用,而其他方法则不能。
  • 不稳定性:

    • 不同的数据划分或随机性质可能导致同一方法在不同运行中结果的轻微差异。
  • 超参数影响:

    • 选择不同的超参数(如PCA的组件数量或树的深度)会直接影响特征重要性的评估结果。
  • 因此,不同的方法提供了不同的视角来评估特征重要性,建议结合多种方法来获得更全面的分析结果。

    选择特征重要性分析方法的一些最佳实践

  • 多方法尝试:

    使用多种方法可以互相验证,减少单一方法的局限性。

  • 结果集成:

    将不同方法的结果进行聚合,提高特征重要性的可靠性。

  • 关注相对顺序:

    相对重要性排名比绝对值更有意义,尤其是在特征数量较多时。

  • 理解差异原因:

    如果不同方法的结果有显著差异,深入分析数据和模型的结构,以找出原因。

  • 通过以上方法,我们可以更好地理解数据特征对模型的影响,从而优化模型性能和模型解释性。

    转载地址:http://kxlfk.baihongyu.com/

    你可能感兴趣的文章
    Python3组播通信编程实现教程(发送者+接收者)
    查看>>
    Python3编写网络爬虫10-数据存储方式三-CSV文件存储
    查看>>
    python3读取redis返回数据带有'b'的问题
    查看>>
    Python3连接MySQL
    查看>>
    Python关于isinstance函数的解析 | 附Demo(全)
    查看>>
    Python3:setup.py:完成所有任务的PIP安装(Build_ext+Install)
    查看>>
    python4.0 gil_Python 并发编程系列--1、浅谈GIL历史及对多线程的影响
    查看>>
    python60行绘图程序_天底下最简单的QT画图板,就一个类,60行代码
    查看>>
    Python: AES加密与解密
    查看>>
    Python: Range() 最大尺寸;动态的还是静态的?
    查看>>
    Python: Windows下用 multiprocessing 的深坑
    查看>>
    python:Could not find platform independent libraries <prefix>解决方法
    查看>>
    Python:datetime tzinfo 时区名称文档
    查看>>
    Python:deepcopy(list) vs new_list = old_list[:]
    查看>>
    Python:Google API - 从消息中获取 mimeTypes
    查看>>
    Python:Google API - 从消息中获取 mimeTypes
    查看>>
    Python:subprocess.call,stdout to file,stderr to file,在屏幕上实时显示stderr
    查看>>
    Python:TypeError:无法连接“str“和“int“对象
    查看>>
    Python:XPath 在 ElementTree 中不可用
    查看>>
    Python:从 FTP 服务器下载文件
    查看>>