You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SequentialFeatureSelection拟合后获取模型系数?

解决SequentialFeatureSelection无法获取模型系数的问题

sklearn的SequentialFeatureSelection(SFS)和RFE、RFECV这类工具的设计逻辑不同——它完成特征筛选后,不会自动保留训练好的最终模型实例,所以没法直接通过estimator_属性获取系数。解决这个问题有两种直接可行的方式:

方法一:用选中的特征重新训练原始模型

先通过SFS拿到筛选后的特征,再用原始estimator重新拟合这些特征数据,就能获取系数:

from sklearn.linear_model import LinearRegression
from sklearn.feature_selection import SequentialFeatureSelection
from sklearn.metrics import make_scorer, r2_score

# 初始化模型与SFS选择器
estimator = LinearRegression()
sfs = SequentialFeatureSelector(estimator, n_features_to_select=3, scoring=make_scorer(r2_score))
sfs.fit(df[features], df.Y)

# 获取选中的特征列
selected_features = df[features].columns[sfs.get_support()]

# 用选中特征重新训练模型
final_estimator = LinearRegression()
final_estimator.fit(df[selected_features], df.Y)

# 提取系数
coef = final_estimator.coef_

方法二:用Pipeline整合SFS与模型(更规范)

把SFS和estimator封装进Pipeline,拟合完成后可以直接从Pipeline的最后一步提取训练好的模型,进而获取系数:

from sklearn.pipeline import Pipeline

# 构建包含特征选择与模型训练的Pipeline
pipe = Pipeline([
    ('sfs', SequentialFeatureSelector(estimator, n_features_to_select=3, scoring=make_scorer(r2_score))),
    ('model', LinearRegression())
])

# 拟合整个流程
pipe.fit(df[features], df.Y)

# 从Pipeline中提取最终模型并获取系数
coef = pipe.named_steps['model'].coef_

补充说明

两种方法的核心逻辑都是基于SFS筛选出的特征重新训练模型——因为SFS本身仅负责特征选择的迭代过程,不会为用户保存最终拟合好的模型实例。这样处理后,就能和RFE等工具的结果做直接对比了。

内容的提问来源于stack exchange,提问作者Abhay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:14:51