“UserWarning:一个或多个测试分数是非有限的”仅在将 RandomForest max_features 参数添加到 RandomizedSearchCV 时发出警告

“UserWarning: One or more of the test scores are non-finite” warning only when adding RandomForest max_features parameter to RandomizedSearchCV

from sklearn.model_selection import RandomizedSearchCV

# --initialise classifier
classifier = RandomForestClassifier(n_estimators=300)

# -- set hyperparameters to tune
param_grid = {
   "max_depth": np.arange(20, 60, 10),
   "min_samples_leaf": np.arange(1, 15),
   'max_features': np.arange(0, 1, 0.05),
}

random = np.random.RandomState(42)

# -- initialise grid search
random_model_search = RandomizedSearchCV(
    estimator=classifier,
    param_distributions=param_grid,
    n_iter=100,
    scoring="f1",
    return_train_score=True,
    n_jobs=-1,
    cv=3,
    random_state=random
)

# -- fit the model and extract best score
random_model_search.fit(X_train_encoded, Y_train)
print(f"Best score: {random_model_search.best_score_}")

print("Best parameters set:")
best_parameters_random = random_model_search.best_estimator_.get_params()
for param_name in sorted(param_grid.keys()):
    print(f"\t{param_name}: {best_parameters_random[param_name]}")

当我 运行 此代码与 param_grid 中的 max_depth 时,我收到一个 UserWarning 说一些测试分数是 nan 值。但是,如果我把这个超参数去掉,随机搜索 运行s 就好了,没有警告。据我所知,当 validation/test 集中的类别在训练集中不存在且未正确编码时,会出现此警告。我正在使用训练集进行随机搜索,整个训练集都已编码,所以我不确定为什么会出现此警告?有人可以就此提出建议吗?

编码和缩放代码如下:

# Set encoding and scaling instructions
column_transform = make_column_transformer(
    (OneHotEncoder(handle_unknown = "ignore"), columns_for_onehot),
    (OrdinalEncoder(categories=[ordinal_order], handle_unknown='use_encoded_value', unknown_value=3), columns_for_ordinal),
    remainder=MinMaxScaler()
)

# Apply column transformer to features
X_train_encoded = column_transform.fit_transform(X_train)

通常要调试,您应该检查 random_model_search.cv_results_ 以找出哪些超参数组合导致 nan 分数,以及它们是否出现在给定超参数组合的所有折叠中。

在这种情况下,我强烈怀疑问题是 max_features=0 是一种可能性,在这种情况下模型将无法训练。