如何使用 baggingregressor 进行特征选择?

How to perform feature selection with baggingregressor?

我正在尝试 select 使用自举的梯度提升功能 - 通过 scikit-learn 中的 BaggingRegressor 执行自举。我不确定这是可能的还是正确的,但这是我尝试过的:

bag = BaggingRegressor(base_estimator=GradientBoostingRegressor(), bootstrap_features=True, random_state=seed)
bag.fit(X,Y)
model = SelectFromModel(bag, prefit=True, threshold='mean')
gbr_boot = model.transform(X)
print('gbr_boot', gbr_boot.shape)

这给出了错误:

ValueError: The underlying estimator BaggingRegressor has no `coef_` or `feature_importances_` attribute. Either pass a fitted estimator to SelectFromModel or call fit before calling transform.

我不确定如何解决这个错误,我认为梯度提升给出了 feature_importances_。我尝试使用以下方法解决它:

bag = BaggingRegressor(base_estimator=GradientBoostingRegressor(), bootstrap_features=True, random_state=seed)
bag.fit(X,Y)

feature_importances = np.mean([
    tree.feature_importances_ for tree in bag.estimators_
], axis=0)

threshold = np.mean(feature_importances)


temp=()
for i in feature_importances: 
    if i > threshold:
        temp=temp + ((i),)
    else:
        temp=temp + (('null'),) 


model_features=data.columns

feature = pd.DataFrame(np.array(model_features))

df = pd.DataFrame(temp)

df_total = pd.concat([feature, df], axis=1)

这似乎成功地提供了 selected 特征,超过了我设定的重要性阈值,但我不确定我是否从 [=13] 中找到了真正的特征 selection =] SelectFromModel 也会找到,或者如果(正如 scikit-learn 错误对我暗示的那样)它不存在于此方法中。为清楚起见,我尝试 BaggingRegressor 自举的原因是 SelectFromModel 单独使用梯度提升的特征数量波动 selects,我读了一篇 paper(第 7.1 节)说自举可以减少这种差异(据我了解,我没有 CS/stats 背景)。

您必须在 BaggingRegressor 上为这个问题创建一个包装器。

class MyBaggingRegressor(BaggingRegressor):
    @property
    def feature_importances_(self):
        return self.regressor_.feature_importances_

    @property
    def coef_(self):
        return self.regressor_.coef_

sklearn here and the corresponding PR 中存在与此相关的问题。

注意:如果您的 base_estimator 是 GradientBoostingRegressor,则您不必选择 BaggingRegressor。

使用 subsample 参数实现同样的效果。

subsample: float, optional (default=1.0)
The fraction of samples to be used for fitting the individual base learners. If smaller than 1.0 this results in Stochastic Gradient Boosting. subsample interacts with the parameter n_estimators. Choosing subsample < 1.0 leads to a reduction of variance and an increase in bias.