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

我正在尝试使用自助法(bootstrapping)从梯度提升中选择特征,通过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.columnsfeature = pd.DataFrame(np.array(model_features))df = pd.DataFrame(temp)df_total = pd.concat([feature, df], axis=1)

这种方法似乎成功地给出了超过我设定的重要性阈值的选定特征,但我不知道我是否找到了BaggingRegressor的真正特征选择,而SelectFromModel也会找到,或者(正如scikit-learn的错误暗示的那样)这种方法并不存在。对于这个问题的解释,我尝试使用BaggingRegressor进行自助法是因为单独使用梯度提升的SelectFromModel在选择的特征数量上波动,我读了一篇论文(第7.1节)说自助法可以减少这种方差(据我所理解,我没有计算机科学/统计学背景)。


回答:

你需要为这个问题创建一个BaggingRegressor的包装器。

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

关于这个问题,在sklearn中有一个现有的问题可以在这里找到,以及相应的PR

注意:如果你使用的base_estimator是GradientBoostingRegressor,你不需要选择BaggingRegressor。

使用subsample参数可以达到同样的效果。

subsample: float, optional (default=1.0)
用于拟合各个基础学习器的样本比例。如果小于1.0,将导致随机梯度提升。subsample与参数n_estimators交互。选择subsample < 1.0会导致方差减少和偏差增加。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注