python - 如何使用 scikit-learn 中的 SelectFromModel 正确进行特征选择?

标签 python machine-learning scikit-learn logistic-regression gridsearchcv

我正在使用very simple kaggle dataset了解 SelectFromModel 与逻辑回归的工作原理。我们的想法是创建一个非常简单的管道,其中包含一些基本的数据处理(删除列+缩放),将其传递给特征选择(logreg),然后拟合 xgboost 模型(不包含在代码中)。通过阅读documentation ,我的理解是,给定我的 X_train 和 y_train ,拟合一个 logreg 模型,并选择那些系数高于或等于阈值的特征。就我而言,我将阈值设置为mean*1.25。

我无法理解为什么输出 selector.threshold_selector.estimator_.coef_.mean()*1.25 不同。 我期望得到相同的结果值,为什么不是这样?

enter image description here

展望 future ,我想做 GridSearchCV 来微调我的管道参数。我通常这样做:

from sklearn.model_selection import GridSearchCV

params = {}
params['gradientboostingclassifier__learning_rate'] = [0.05, 0.1, 0.2]
params['selectfrommodel__estimator__C'] = [0.1, 1, 10]
params['selectfrommodel__estimator__penalty']= ['l1', 'l2']
params['selectfrommodel__estimator__threshold']=['median', 'mean', '1.25*mean', '0.75*mean']

grid = GridSearchCV(pipe, params, cv=5, scoring='recall')
%time grid.fit(X_train, y_train);

不幸的是,阈值似乎不在参数列表中(pipe.named_steps.selectfrommodel.estimator.get_params().keys()),因此要使 GridSearchCV 正常工作,此行需要进行评论。

params['selectfrommodel__estimator__threshold']=['median', 'mean', '1.25*mean', '0.75*mean']

有办法微调阈值吗?

最佳答案

因为重要性是基于系数绝对值的平均值。如果对相对值求平均值,平均重要性会更低

我构建了一个示例来演示该行为:

from sklearn.feature_selection import SelectFromModel
from sklearn.linear_model import LogisticRegression
X = [[ 0.87, -1.34,  0.31 ],
     [-2.79, -0.02, -0.85 ],
     [-1.34, -0.48, -2.55 ],
     [ 1.92,  1.48,  0.65 ]]
y = [0, 1, 0, 1]
selector = SelectFromModel(estimator=LogisticRegression(), threshold="1.25*mean").fit(X, y)
print(selector.estimator_.coef_)
print(selector.threshold_) # 0.6905659148858644
# note here the absolute transformation before the mean
print(abs(selector.estimator_.coef_).mean()*1.25) # 0.6905659148858644

另请注意,特征重要性是模型训练的结果,而不是您可以先验定义的东西。这就是原因,因为您无法适应阈值,该阈值仅在训练后获得

关于python - 如何使用 scikit-learn 中的 SelectFromModel 正确进行特征选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64581307/

相关文章:

machine-learning - 特定组/范围的 ML 准确性

python - 自动机器学习 python 等效代码

scikit-learn - 将目标/标签数据传递给 Scikit-learn GridSearchCV 的 OneClassSVM 拟合方法

python - 多项选择 react python (discord.py)

python - 有没有办法从 Python Web 服务部分返回结果......?

python - 神经网络似乎在每次执行时都停留在单个输出上

Python - SkLearn 逻辑回归 : One-by-one train instance

Python:循环中IF语句的处理不一致

python - SqlAlchemy - 按定义为 ForeignKey 的字段过滤

javascript - 为什么我的神经网络训练方法没有被调用? (ML5.JS)