网格搜索
如您所见,地形只是一个形状矩阵(1024,1024)。 由于我们的预算是25个实验,我们将在这个地形上进行一次5x5的网格搜索。 意即在x和y轴上选择5个等距点,并读取这些(x,y)位置处的地形矩阵值。 执行此操作的代码如下所示。 在轮廓图上的点的最佳值以蓝色标示。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | # 执行 (5x5)网格搜索 results = [] for x in np.linspace(0, SIZE-1, 5): for y in np.linspace(0, SIZE-1, 5): xi, yi = int(x), int(y) results.append([xi, yi, terrain[xi, yi]])
best_xyz = [r for r in sorted(results, key=operator.itemgetter(2))][0] grid_best = best_xyz[2] print(best_xyz)
xvals = [r[0] for r in results] yvals = [r[1] for r in results]
plt.title('grid search') contour = plt.contour(terrain, linewidths=2) plt.ylim(max(plt.ylim()), min(plt.ylim())) plt.scatter(xvals, yvals, color='b', marker='o') plt.scatter([best_xyz[0]], [best_xyz[1]], color='b', s=200, facecolors='none', edgecolors='b') plt.ylim(max(plt.ylim()), min(plt.ylim())) plt.colorbar(contour) |

网格搜索中最优点坐标为(767,767),值为109。
随机搜索
接下来进行实验的是纯随机搜索。由于实验预设为25个,所以这里仅随机生成x值和y值,然后在这些点中搜索地形矩阵值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | # 进行随机搜索 results = [] xvals, yvals, zvals = [], [], [] for i in range(25): x = np.random.randint(0, SIZE, 1)[0] y = np.random.randint(0, SIZE, 1)[0] results.append((x, y, terrain[x, y]))
best_xyz = sorted(results, key=operator.itemgetter(2))[0] rand_best = best_xyz[2] print(best_xyz)
xvals = [r[0] for r in results] yvals = [r[1] for r in results]
plt.title('random search') contour = plt.contour(terrain, linewidths=2) plt.ylim(max(plt.ylim()), min(plt.ylim())) plt.scatter(xvals, yvals, color='b', marker='o') plt.scatter([best_xyz[0]], [best_xyz[1]], color='b', s=200, facecolors='none', edgecolors='b') plt.colorbar(contour) |

在该测试中,随机搜索做得更好一些,找到坐标为(663,618)值为103的点。
本文由北邮@爱可可-爱生活 老师推荐,阿里云云栖社区组织翻译。
文章原标题《Random vs Grid Search: Which is Better?》,作者:Sujit Pal ,译者:伍昆





































苏公安网备 32011402010933号