python - 仅在将 RandomForest max_features 参数添加到 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]}")
max_depth
当我用in运行这段代码时param_grid
,我得到一个 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
有可能的,并且在这种情况下模型将无法训练。