我想尝试库中的所有回归器。由于我知道一些回归器需要更多的输入,所以我构建了尝试和异常捕获块。
for name, estimator in sklearn.utils.all_estimators(type_filter='regressor'): model = make_pipeline(StandardScaler(), estimator) try: scores = cross_validate(model, X, y, scoring='r2') print(name, ': ', np.mean(scores['test_score'])) except: print('不会被打印。')
这会多次返回以下片段:
FitFailedWarning: 估计器拟合失败。这次训练-测试分区的这些参数的得分将被设置为nan。详细信息:Traceback (most recent call last): File "venvpath\lib\site-packages\sklearn\model_selection\_validation.py", line 598, in _fit_and_score estimator.fit(X_train, y_train, **fit_params) File "venvpath\venv\lib\site-packages\sklearn\pipeline.py", line 346, in fit self._final_estimator.fit(Xt, y, **fit_params_last_step)TypeError: fit() 缺少一个必需的位置参数: 'y'
在我看来,这里有两个问题。首先,except 从未被调用。其次,y 输入未被识别。
对任何形式的帮助表示感谢。
回答:
all_estimators
不返回估计器的实例,而只返回它们的类(请参阅文档)。在定义管道时,您应该实例化该类的对象:
for name, estimator in sklearn.utils.all_estimators(type_filter='regressor'): model = make_pipeline(StandardScaler(), estimator()) # <-- 此行有改动
注意 estimator
后的 ()
。现在您有了可以拟合数据的实际对象。
关于 except
块: 默认情况下,如果发生错误,cross_validate
会将分数设置为 np.nan
。要实际引发错误,请在 cross_validate
中设置 error_score='raise'
:
scores = cross_validate(model, X, y, scoring='r2', error_score='raise')