在 sklearn 中使用基于组的验证方法搜索模型的超参数

Searching hyperparameters for models with group based validation methods in sklearn

我想对我在 Scikit-Learn 中训练的模型执行超参数优化。我想首先使用随机搜索来了解一个好的搜索区域,然后再进行网格搜索。我需要使用的验证方法是Leave One Group Out (LOGO)。

所以有这样的效果:

distributions = {
    "n_estimators": randint(low=1, high=500),
    "criterion": ["squared_error", "absolute_error", "poisson"],
    "max_depth": randint(low=1, high=100)
}

random_search = RandomizedSearchCV(
    forest_reg, 
    distributions, 
    cv=LeaveOneGroupOut(), 
    groups=group, 
    scoring="neg_mean_squared_error", 
    return_train_score=True, 
    random_state=42,
    n_jobs=-1,
    n_iter=20
)

random_search.fit(X, y)

RandomizedSearchCV 或 GridSearchCV 均不支持使用组定义进行 LOGO 验证。当我使用 cross_val_score() 之类的方法时,我可以发送选择的交叉验证方法,例如

scores = cross_val_score(
    forest_reg, 
    X, 
    y, 
    scoring="neg_mean_squared_error", 
    cv=LeaveOneGroupOut(), 
    groups=group, 
    n_jobs=-1
)

是否有任何一种超参数搜索方法不支持相同的原因?我以错误的方式使用 API 吗?有没有一种方法可以使用 sklearn 实现我想要的,而无需自己将某些东西放在一起?

使用 LeaveOneGroupOut 时应将组传递到 fit() 方法中。

RandomizedSearchCV.fit() 文档指定参数 groups 应仅与“组”cv 实例结合使用,例如 GroupKFoldLeaveOneGroupOut.

参见下面的示例:

from sklearn.datasets import make_regression
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import RandomizedSearchCV, LeaveOneGroupOut
import numpy as np

params = {
    "n_estimators": [1, 5, 10],
    "max_depth": [2, 5, 10]
}

X, y = make_regression()
groups = np.random.randint(5, size=y.shape)
cv = RandomizedSearchCV(RandomForestRegressor(),
                        params,
                        cv=LeaveOneGroupOut()
)

cv.fit(X, y, groups=groups)