随机搜索简介

Python 中的超参数调优

Alex Scriven

Data Scientist

您已掌握的内容

 

与网格搜索非常相似:

  • 定义估计器、要调的超参数及其取值范围。
  • 仍需设置交叉验证方案和评分函数。

 

但我们改为"随机"选择网格单元。

Python 中的超参数调优

为什么有效?

Bengio 与 Bergstra(2012):

本文通过实证与理论表明,随机选择的试验在超参数优化上比网格试验更高效。

两大原因:

  1. 并非每个超参数都同等重要。
  2. 一个小小的概率技巧。
Python 中的超参数调优

一个概率小技巧

网格搜索:

10x10 不同模型

要达到 95% 概率命中绿色方格,需运行多少个模型?

我们的最佳模型:

10x10 不同模型

Python 中的超参数调优

一个概率小技巧

 

若均匀随机选择超参数组合,考虑"每次都错过"的概率,以说明其不太可能:

  • 试验1:成功概率 0.05,错过概率 (1 − 0.05)。

    • 试验2:错过概率 (1−0.05) × (1−0.05)。
      • 试验3:错过概率 (1−0.05) × (1−0.05) × (1−0.05)。
  • 一般地,n 次试验全部错过的概率为 (1−0.05)^n。

Python 中的超参数调优

一个概率小技巧

 

要有较高(95%)的概率落入该区域,需要多少次试验?

  • 全部错过的概率为 (1-0.05)^n。
  • 因此命中的概率为 1 − 全部错过,即 1 − (1-0.05)^n。
  • 解 1 − (1-0.05)^n ≥ 0.95 得 n ≥ 59
Python 中的超参数调优

一个概率小技巧

 

这意味着什么?

  • 随机选点时,长期完全错过"好区域"的可能性很低。
  • 网格搜索为穷举覆盖,可能在"差区域"耗费大量时间。
Python 中的超参数调优

一些重要说明

 

请记住:

  1. 最优结果仍受您设定的网格所限。

  2. 与网格搜索公平比较时,应使用相同的建模"预算"。

Python 中的超参数调优

随机抽样超参数

我们可以自行随机抽样超参数组合:

# Set some hyperparameter lists
learn_rate_list = np.linspace(0.001,2,150)
min_samples_leaf_list = list(range(1,51))
# Create list of combinations
from itertools import product
combinations_list = [list(x) for x in 
                    product(learn_rate_list, min_samples_leaf_list)]
# Select 100 models from our larger set
random_combinations_index = np.random.choice(
                            range(0,len(combinations_list)), 100, 
                            replace=False)
combinations_random_chosen = [combinations_list[x] for x in 
                            random_combinations_index]
Python 中的超参数调优

可视化随机搜索

我们也可把超参数选择绘制在 X、Y 轴上,来可视化随机搜索的覆盖范围。

随机搜索覆盖图

注意:散点范围广,但覆盖不深。

Python 中的超参数调优

Passons à la pratique !

Python 中的超参数调优

Preparing Video For Download...