Genetic Algorithm + Parallel Computing + Global variables
18 ビュー (過去 30 日間)
古いコメントを表示
Hello to all,
I have been able to run a GA in parallel (10 workers in total). Now I want to store in a kind of "result matrix" what happens on each worker. For example the simulated individual, the CPU time, the cost and the number of iterations. I tried defining global variables in the main script, where I just call the ga(). Then in the objective function I call the global variables and assign new values. Unfortunately, I only get one row in my "result matrix".
I also tried parfevalOnAll and in the called function I load and assign the values. But this does not work at all.
Does anyone have any idea how to handle this?
Thanks a lot already!
0 件のコメント
回答 (2 件)
Matt J
2022 年 8 月 27 日
編集済み: Matt J
2022 年 8 月 29 日
If you're using UseVectorized, it should be relatively easy. Within your parfor loop, store the results of processing each population member to a struct array and store that to an externally scoped cell array ResultMatrix as below. Later you can aggregate the different ResultMatrix{i}(j) according to the worker label stored in ResultMatrix{i}(j).labindex.
function main
ResultMatrix={};
opts=optimoptions('ga','UseVectorized',true);
x=ga(@fitnessFunc,nvars,A,b,Aeq,beq,lb,ub,nonlcon,intcon,opts));
function out=fitnessFunc(X)
parfor i=1:size(X,1)
tic;
%process population members here
T=toc;
S(i).cpuTime=T;
S(i).popmember=X(i,:);
...
S(i).labindex=getCurrentTask().ID;
S(i).cost=cost;
end
ResultMatrix{end+1}=S;
out=vertcat(S.cost);
end
end
6 件のコメント
Walter Roberson
2022 年 8 月 28 日
global variables never transfer between parallel workers or workers and client.
Matt J
2022 年 8 月 28 日
編集済み: Matt J
2022 年 8 月 28 日
Do you or anyone else have any other ideas for a workaround? It doesn't have to be the prettiest solution.
You might be able to accumulate the results to a .mat file, as opposed to a global variable. In your fitness function, you would have something like,
filename="outfile"+getCurrentTask().ID; %worker-dependent temp file
result_matrix=[load(filename).result_matrix, result_matrix];
save(filename,'result_matrix');
1 件のコメント
Matt J
2022 年 8 月 28 日
You could also do the same kind of thing in a custom Output Function to add things like the current iteration number to the temp files.
参考
カテゴリ
Help Center および File Exchange で Surrogate Optimization についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!