谁更胜一筹?--随机搜索 V.S. 网格搜索
在进行超参数优化工作时,我不断思考该使用随机搜索还是网格搜索呢?这时候,一个同事给我介绍了一篇由Bergstra和Bengio编写的随机搜索超参数优化论文(链接),文中认为在进行参数优化时随机搜索比网格搜索更有效。
我想通过测试来得到自己的答案,我的实验设置如下。给定空间为(1024,1024)的超参数空间,可由相同形状的矩阵表示。我们为寻找最佳超参数设置的预算是25个实验。因此,这将允许我们进行网格搜索,其中我们设置每个超参数有5个值的组合,或者在该空间中的25个随机搜索。此外,我设置了一个“批量”版本的随机搜索,执行5批次每批次5次随机搜索,优化调整每次批次后的搜索。生成多个这样的随机超参数空间后,计算两种随机搜索优于网格搜索的次数。
生成空间
这一步是生成随机2D超参数空间,例如某种地形。 我使用了Hill地形算法(链接)。 它是一个简单而优雅的算法。 代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import operator %matplotlib inline
SIZE = 1024 NUM_ITERATIONS = 200
terrain = np.zeros((SIZE, SIZE), dtype='float') mod_iter = NUM_ITERATIONS // 10 for iter in range(NUM_ITERATIONS): if iter % mod_iter == 0: print('iteration: {:d}'.format(iter)) r = int(np.random.uniform(0, 0.2 * SIZE)) xc, yc = np.random.randint(0, SIZE - 1, 2) z = 0 xmin, xmax = int(max(xc - r, 0)), int(min(xc + r, SIZE)) ymin, ymax = int(max(yc - r, 0)), int(min(yc + r, SIZE)) for x in range(xmin, xmax): for y in range(ymin, ymax): z = (r ** 2) - ((x - xc) ** 2 + (y - yc) ** 2) if z > 0: terrain[x, y] += z print('total iterations: {:d}'.format(iter)) # 标准化单元高度 zmin = np.min(terrain) terrain -= zmin zmax = np.max(terrain) terrain /= zmax # 通过z值平滑地形 terrain = np.power(terrain, 2) # 乘以255以使地形以灰度表示 terrain = terrain * 255 terrain = terrain.astype('uint8') |
从上面代码生成的一个可能的地形如下所示。 我还为它生成了一个等高线图。
1 2 3 4 5 6 7 8 9 | plt.title('terrain') image = plt.imshow(terrain, cmap='gray') plt.ylim(max(plt.ylim()), min(plt.ylim())) plt.colorbar(image, shrink=0.8)
plt.title('contours') contour = plt.contour(terrain, linewidths=2) plt.ylim(max(plt.ylim()), min(plt.ylim())) plt.colorbar(contour, shrink=0.8, extend='both') |

本文由北邮@爱可可-爱生活 老师推荐,阿里云云栖社区组织翻译。
文章原标题《Random vs Grid Search: Which is Better?》,作者:Sujit Pal ,译者:伍昆





































苏公安网备 32011402010933号