假设我在MATLAB中有以下代码:
% Predefined data
SX = [1, 2, 3, 4];
parfor xx = 1:4
naming2 = SX(xx);
[BestM, BestX{xx}, fina_M{xx}, final_D{xx}, BestAA{xx}, final_Data{xx}] = Optmz(naming2, v_data);
end
Optmz
是一种优化算法。该优化算法应运行以优化回归模型(具有不同的输出和优化的输入功能选择)。如您所知,启发式优化算法是基于随机数的。每个parlor
循环中都有不同的初始随机数吗?这是减少我的申请时间的合适结构吗?我目前for
在上述结构中使用循环。
这是打印输出的一部分。迭代不排序。任何问题?根据上面的代码,我们应该有四个具有相同编号的迭代。我需要使用不同的初始随机数生成器的所有4个工作人员进行总计不同的计算。例如,就像我们无需并行计算就按顺序运行计算的方式一样。运行第一个,第二个,第三个,最后运行第四个。
******Iteration 24, Best Cost = 0.041201******
******Iteration 26, Best Cost = 0.034994******
******Iteration 26, Best Cost = 0.036624******
******Iteration 26, Best Cost = 0.039317******
******Iteration 25, Best Cost = 0.039584******
******Iteration 27, Best Cost = 0.034994******
******Iteration 27, Best Cost = 0.036624******
******Iteration 27, Best Cost = 0.039317******
******Iteration 28, Best Cost = 0.034994******
******Iteration 26, Best Cost = 0.039242******
******Iteration 28, Best Cost = 0.036624******
******Iteration 28, Best Cost = 0.03931******
******Iteration 29, Best Cost = 0.034994******
******Iteration 29, Best Cost = 0.036624******
******Iteration 27, Best Cost = 0.039048******
******Iteration 29, Best Cost = 0.03931******
******Iteration 30, Best Cost = 0.034994******
******Iteration 30, Best Cost = 0.036624******
******Iteration 28, Best Cost = 0.039048******
也许这就是您要的,也许不是,但是,如果您希望每个循环使用不同的种子,则可以给带有时间戳或类似内容的随机数生成器种子。这将确保每个循环具有不同的种子,并因此具有不同的随机数集
nLoops = 10
parfor ii = 1:nLoops
timeVals = strsplit(sprintf('%.9f',now),'.')
rng(str2double(timeVals{2}))
% do some stuff
end
或者您可以使用MATLAB内置的随机播放功能 rng
nLoops = 10
parfor ii = 1:nLoops
rng('shuffle')
% do some stuff
end
如果您不希望它在每个循环中都是随机的,则只需在进入循环之前创建一个数组即可,无论大小如何,都可以让每个循环访问相同的信息。强烈建议所有循环都不要编辑与此数组有关的任何内容
nLoops = 10;
randNums = rand(1,100)
parfor ii = 1:nLoops
%do something with randNums(someNum)
end
两种选择都相对容易。如果您正在执行优化问题,则可能要确保您的随机数有所不同,这就是优化的重点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句