只有在向RandomizedSearchCV添加RandomForest max_Feature参数时,才会出现“UserWarning:一个或多个测试分数是非限定的”警告 [英] “UserWarning: One or more of the test scores are non-finite” warning only when adding RandomForest max_features parameter to RandomizedSearchCV

查看:14
本文介绍了只有在向RandomizedSearchCV添加RandomForest max_Feature参数时,才会出现“UserWarning:一个或多个测试分数是非限定的”警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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"	{param_name}: {best_parameters_random[param_name]}")

当我在param_grid中使用max_depth运行此代码时,我收到一个UserWarning,指出某些测试分数是NaN值。然而,如果我去掉这个超参数,随机搜索运行得很好,没有任何警告。我知道,当验证/测试集中存在训练集中不存在的类别,因此没有正确编码时,就会出现此警告。我使用列车集进行随机搜索,并对整个列车集进行了编码,所以我不确定为什么会出现这个警告?有人能对此提出建议吗?

编码和伸缩码如下:

# 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是一种可能性,在这种情况下模型将无法训练。

这篇关于只有在向RandomizedSearchCV添加RandomForest max_Feature参数时,才会出现“UserWarning:一个或多个测试分数是非限定的”警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆