首页 > 解决方案 > 使用 python 中的 hypopt 包在 GridSearch 函数中指定评分指标

问题描述

我正在使用 hypopt 包中的 Gridsearch 函数来使用指定的验证集进行超参数搜索。分类的默认指标似乎是准确性(不太确定)。在这里,我想使用 F1 分数作为指标。我不知道应该在哪里指定指标。我查看了文档,但有点困惑。

熟悉hyopt package的人知道我该怎么做吗?提前非常感谢。

from hypopt import GridSearch

log_reg_params = {"penalty": ['l1'], 'C': [0.001, 0.01]}
opt = GridSearch(model=LogisticRegression())
opt.fit(X_train, y_train, log_reg_params, X_val, y_val)

标签: pythonmachine-learninggrid-searchhyperparameters

解决方案


包的默认指标hypopt是您使用的任何模型的score()功能,因此在您的情况下,LogisticRegression().score()它默认为准确性。

如果您通过 将 hypopt 包升级到版本 1.0.8 ,您可以在 的参数中pip install hypopt --upgrade指定您选择的任何指标,例如. 这是一个简单的工作示例,基于您使用 F1 指标的代码:scoringGridSearch.fit()fit(scoring='f1')

from hypopt import GridSearch

param_grid = {"penalty": ['l1'], 'C': [0.001, 0.01]}
opt = GridSearch(model=LogisticRegression(), param_grid = param_grid)
# This will use f1 score as the scoring metric that you optimize.
opt.fit(X_train, y_train, X_val, y_val, scoring='f1')

hypopt支持大多数支持的评分功能sklearn

  • 对于分类,hypopt支持这些指标(作为字符串):'accuracy'、'brier_score_loss'、'average_precision'、'f1'、'f1_micro'、'f1_macro'、'f1_weighted'、'neg_log_loss'、'precision'、'recall' ,或“roc_auc”。
  • 对于回归,hypopt支持:“explained_variance”、“neg_mean_absolute_error”、“neg_mean_squared_error”、“neg_mean_squared_log_error”、“neg_median_absolute_error”、“r2”。

your_custom_score_func(y_true, y_pred)您还可以通过将其包装到如下对象中来创建自己的指标:

from sklearn.metrics import make_scorer
scorer = make_scorer(your_custom_score_func)
opt.fit(X_train, y_train, X_val, y_val, scoring=scorer)

hypopt.GridSearch.fit()您可以在此处的文档字符串中了解更多信息:

您可以在此处了解有关创建自己的自定义评分指标的更多信息:


推荐阅读