重现结果
用伪随机数得到相同的答案
GlobalSearch 和 MultiStart 使用伪随机数来选择起点。再次使用相同的伪随机数流:
比较各种算法设置。
让示例可重复运行。
延长一次运行,并了解上次运行的初始段。
GlobalSearch 和 MultiStart 都使用默认的随机数流。
重现结果的步骤
在运行问题之前,存储默认随机数流的当前状态:
stream = rng;
运行您的
GlobalSearch或MultiStart问题。恢复随机数流的状态:
rng(stream)
如果您再次运行您的问题,您将得到相同的结果。
示例:重现 GlobalSearch 或 MultiStart 结果
此示例显示如何获得 寻找全局或多个局部最小值 的可重现结果。该示例遵循 重现结果的步骤 中的步骤。
存储默认随机数流的当前状态:
stream = rng;
创建
sawtoothxy函数文件:function f = sawtoothxy(x,y) [t r] = cart2pol(x,y); % change to polar coordinates h = cos(2*t - 1/2)/2 + cos(t) + 2; g = (sin(r) - sin(2*r)/2 + sin(3*r)/3 - sin(4*r)/4 + 4) ... .*r.^2./(r+1); f = g.*h; end
创建
problem结构体和GlobalSearch对象:problem = createOptimProblem("fmincon",... objective=@(x)sawtoothxy(x(1),x(2)),... x0=[100,-50],options=... optimoptions(@fmincon,Algorithm="sqp")); gs = GlobalSearch(Display="iter");
运行问题:
[x,fval] = run(gs,problem)
Num Pts Best Current Threshold Local Local Analyzed F-count f(x) Penalty Penalty f(x) exitflag Procedure 0 200 555.7 555.7 0 Initial Point 200 1463 1.547e-15 1.547e-15 1 Stage 1 Local 300 1564 1.547e-15 5.709e+04 1.074 Stage 2 Search 400 1664 1.547e-15 1.646e+05 4.16 Stage 2 Search 500 1764 1.547e-15 2.262e+04 11.84 Stage 2 Search 600 1864 1.547e-15 1680 30.95 Stage 2 Search 700 1964 1.547e-15 1.138e+04 65.25 Stage 2 Search 800 2064 1.547e-15 1.573e+05 163.8 Stage 2 Search 900 2164 1.547e-15 3.676e+04 409.2 Stage 2 Search 977 2441 1.547e-15 669 707.8 622.5 0 Stage 2 Local 980 2525 1.547e-15 529.3 669 39.75 1 Stage 2 Local 1000 2545 1.547e-15 1634 505.5 Stage 2 Search GlobalSearch stopped because it analyzed all the trial points. 2 out of 4 local solver runs converged with a positive local solver exit flag. x = 1×2 1.0e-07 * 0.0414 0.1298 fval = 1.5467e-15运行此问题时您可能会获得不同的结果,因为随机流在运行开始时处于未知状态。
恢复随机数流的状态:
rng(stream)
再次运行该问题。您会得到相同的输出。
[x,fval] = run(gs,problem)
Num Pts Best Current Threshold Local Local Analyzed F-count f(x) Penalty Penalty f(x) exitflag Procedure 0 200 555.7 555.7 0 Initial Point 200 1463 1.547e-15 1.547e-15 1 Stage 1 Local 300 1564 1.547e-15 5.709e+04 1.074 Stage 2 Search 400 1664 1.547e-15 1.646e+05 4.16 Stage 2 Search 500 1764 1.547e-15 2.262e+04 11.84 Stage 2 Search 600 1864 1.547e-15 1680 30.95 Stage 2 Search 700 1964 1.547e-15 1.138e+04 65.25 Stage 2 Search 800 2064 1.547e-15 1.573e+05 163.8 Stage 2 Search 900 2164 1.547e-15 3.676e+04 409.2 Stage 2 Search 977 2441 1.547e-15 669 707.8 622.5 0 Stage 2 Local 980 2525 1.547e-15 529.3 669 39.75 1 Stage 2 Local 1000 2545 1.547e-15 1634 505.5 Stage 2 Search GlobalSearch stopped because it analyzed all the trial points. 2 out of 4 local solver runs converged with a positive local solver exit flag. x = 1×2 1.0e-07 * 0.0414 0.1298 fval = 1.5467e-15
并行处理和随机数流
当您以与串行计算相同的方式并行运行算法时,您可以从 MultiStart 获得可重复的结果。运行是可重现的,因为 MultiStart 在本地生成伪随机起点,然后将起点分发到并行处理器。因此,并行处理器不使用随机数。
要重现并行 MultiStart 运行,请使用 重现结果的步骤 中描述的步骤。有关如何并行运行 MultiStart 的说明,请参阅如何在 Global Optimization Toolbox 中使用并行处理。