如何使用 GridSearchCV (python) 最大化或最小化带参数的函数?

How to use GridSearchCV (python) for maximizing or minimizing a function with parameters?

我想最大化一个函数:func(minCount, wordNgrams, lr, epoch, loss) 仅在这些值上使用 GridSearch:

`{'minCount': [2, 3],
'wordNgrams': [1, 2, 3, 4, 5],
'lr': [0.1, 0.01, 0.001, 0.0001],
'epoch': [5, 10, 15, 20, 25, 30],
'loss': [hs, ns, softmax]}`

我读过 sklearn.model_selection.GridSearchCV(estimator, param_grid, ...) 但是,我不知道,我应该把我的func(minCount, wordNgrams, lr, epoch, loss)

放在哪里

顺便说一下,我读过贝叶斯优化 (https://github.com/fmfn/BayesianOptimization),但不了解如何将其与 stringint 参数一起使用

根据 the documentation ,你有两个解决方案:

  • 您可以将 estimator = func 传递给 GridSearchCV,但是您 还需要传递一个评分函数 。评分函数将采用 func 的输出和 return GridSearchCV 将寻求优化的分数(浮点数)。示例:
def my_scoring_function(func_outputs):

  """
  process the outputs of func and return a score. 

  if func already reutrns the value you want to minimize, 
  my_scoring_function will be the identity function.

  score is the value to optimize
  """

  return score


cv = GridSearchCV(estimator=func, param_grid=my_param_grid, scoring=my_scoring_function)


  • 更复杂,但更优雅:您可以将 func 重写为实现 scikit-learn 估计器方法 (good tutorial here with a gid search example) 的对象。这意味着它将基本上遵循一组约定,使您的函数表现得像 scikit-learn 的对象。 GridSearchCV 将知道如何处理它。不过,这对您的问题来说可能有点矫枉过正。


关于贝叶斯优化,如果您的问题满足以下条件,那将很有趣:

  • 评估您的函数的成本非常高(就 time/resource... 而言)并且您无法承受网格搜索要求您调用它的次数。在您的情况下,您有 720 种参数组合需要探索,因此如果一次评估花费 10 秒,您将不得不 运行 网格搜索 7200 秒。
  • 您想要探索更广泛的参数 space,或者您想要连续 space 搜索一些参数。通常,学习率可能很有趣。这种情况下,也可以使用随机搜索,also implemented in scikit learn.

有关贝叶斯优化的更多详细信息,我会推荐 this article,我认为它非常全面。