【问题标题】:How to extract important features after k-fold cross validation, with or without a pipeline?如何在 k 折交叉验证后提取重要特征,无论有无管道?
【发布时间】:2019-10-26 23:14:29
【问题描述】:

我想构建一个使用交叉验证的分类器,然后从每个折叠中提取重要特征(/系数),以便查看它们的稳定性。目前我正在使用 cross_validate 和管道。我想使用一个管道,以便我可以在每个折叠中进行特征选择和标准化。我被困在如何从每个折叠中提取特征。如果这是问题的话,我有一个不同的选择来使用下面的管道。

这是我目前的代码(我想尝试SVM 和逻辑回归)。我已经包含了一个小的 df 作为示例:

from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import mutual_info_classif
from sklearn.model_selection import cross_validate
from sklearn.model_selection import KFold
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
import pandas as pd

df = pd.DataFrame({'length': [5, 8, 0.2, 10, 25, 3.2], 
                   'width': [60, 102, 80.5, 30, 52, 81],
                   'group': [1, 0, 0, 0, 1, 1]})

array = df.values
y = array[:,2]
X = array[:,0:2]

select = SelectKBest(mutual_info_classif, k=2)
scl = StandardScaler()
svm = SVC(kernel='linear', probability=True, random_state=42)
logr = LogisticRegression(random_state=42)

pipeline = Pipeline([('select', select), ('scale', scl), ('svm', svm)])

split = KFold(n_splits=2, shuffle=True, random_state=42)

output = cross_validate(pipeline, X, y, cv=split, 
                scoring = ('accuracy', 'f1', 'roc_auc'),
                return_estimator = True,
                return_train_score= True)

我想我可以这样做:

pipeline.named_steps['svm'].coef_

但我收到错误消息:

AttributeError: 'SVC' object has no attribute 'dual_coef_'

如果无法使用管道执行此操作,我可以使用“手动”交叉验证来执行此操作吗?例如:

for train_index, test_index in kfold.split(X, y):

        kfoldtx = [X[i] for i in train_index]
        kfoldty = [y[i] for i in train_index]

但我不知道下一步该做什么!任何帮助将不胜感激。

【问题讨论】:

    标签: python-3.x scikit-learn cross-validation


    【解决方案1】:

    您应该使用cross_validateoutput 来获取拟合模型的参数。原因是cross_validate 会克隆管道。因此,在将给定的pipeline 变量输入到cross_validate 后,您将找不到合适的变量。

    output 是字典,其中有estimator 作为键之一,其值是k_fold 拟合pipeline 对象的数量。

    来自Documentation

    return_estimator : 布尔值,默认为 False

    是否返回适合每个拆分的估计器。

    试试这个!

    >>> fitted_svc = output['estimator'][0].named_steps['svm'] # choosing the first fold comb
    >>> fitted_svc.coef_
    
    array([[1.05826838, 0.41630046]])
    

    【讨论】:

    • 有效!太棒了,谢谢你,多年来一直在为此苦苦挣扎。我可以与您确认我正在正确使用管道吗?我不需要在任何地方调用.fit,因为这是使用cross_validate 实现的?您能否指出我正确的方向,将系数数组映射到原始 df 列标题?当我尝试使用更大的数据集时,我得到ValueError: Shape of passed values is (1, 5), indices imply (50, 302)
    • 是的,您不必重新安装,每个型号都已经安装好了。注意:你会得到k_fold 的模型数量。您的第二部分问题不清楚!你能在你的问题中添加更多关于它的细节吗?
    • 可能对您有用:coef_ 的形状将是 [n_class * (n_class-1) / 2, n_features]。在documentation中阅读更多信息
    • 好的,我想,但想检查:)。第二部分:因为我使用的是SelectKbest,例如选择前 5 个特征,我有一个每折叠 5 个系数的数组。我如何知道它们对应的功能名称,哪些是我原始 df 中的列标题?我希望我能更好地解释自己!
    • output['estimator'][0]['select'].get_support() 这将为您提供所选变量的列表。
    猜你喜欢
    • 2016-01-15
    • 1970-01-01
    • 2016-09-30
    • 2020-08-29
    • 2020-05-05
    • 2021-04-06
    • 2016-12-15
    • 2018-08-29
    • 2017-06-09
    相关资源
    最近更新 更多