我正在尝试使用自助法(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会导致方差减少和偏差增加。