fit options in a parfor loop
12 ビュー (過去 30 日間)
古いコメントを表示
Elizabeth Jones
2019 年 11 月 14 日
回答済み: Elizabeth Jones
2019 年 11 月 19 日
I am performing a fit of data multiple times using a loop. When I use a "for" loop, everything works as expected. However, if I use a "parfor" loop, I get an error. If I remove the fit options (fo), then the parfor loop works as expected. Does anyone know why the parfor loop generates an error when I specify the fit method using the fitoptions?
% Generate some data
Npts = 50;
Ntime = 10;
tau = 10;
x = repmat( (1:Npts)',1,Ntime);
y = exp(-x/tau) + (rand(Npts,Ntime)-0.5)/10;
% Plot the data
figure;
plot(x(:,1),y(:,1),'-o')
title('Data for first time step')
% Fit options
ft = fittype('exp1');
fo = fitoptions( 'Method', 'NonlinearLeastSquares' );
% Pre-allocate the decay constant, tau
tau = NaN(1,Ntime);
parfor q = 1:Ntime
% Perform the exponential fit at time step q
fitresult = fit( x(:,q), y(:,q), ft, fo);
% Save the decay constant, tau
tau(q) = -1/fitresult.b;
end
2 件のコメント
Walter Roberson
2019 年 11 月 14 日
I confirm that the fo object is arriving empty on the worker, the way you would expect a global variable to look.
The work-around for the moment appears to be to assign fo inside the parfor loop.
採用された回答
その他の回答 (2 件)
Matt J
2019 年 11 月 15 日
編集済み: Matt J
2019 年 11 月 15 日
A guess as to why this might be happening is that fitoptions objects don't seem to implement proper save/load behavior, as indicated by this small experiment,
>> fo = fitoptions( 'Method', 'NonlinearLeastSquares' );
>> save fo_file fo
>> S=load('fo_file');
>> isequal(S.fo,fo)
ans =
logical
0
This is signifcant, because parpools use save/load operations to clone objects to the workers, as is alluded here.
However, this does not explain why the version of fo that gets loaded on the workers ends up empty. Reloading a fitoptions object outside a parpool doesn't have that effect:
>> isempty(S.fo)
ans =
logical
0
0 件のコメント
Edric Ellis
2019 年 11 月 15 日
Unfortunately, this is a limitation in the implementation of the fitoptions class. You can work around this either by constructing the fitoptions inside the parfor loop, or you can use parallel.pool.Constant, like this:
% Use the "function handle" form constructor of parallel.pool.Constant to
% ensure that the fitoptions object is constructed on the workers
fo_c = parallel.pool.Constant(@() fitoptions( 'Method', 'NonlinearLeastSquares' ));
parfor ...
...
% Extract the fitoptions from the Constant
fo = fo_c.Value;
% Perform the exponential fit at time step q
fitresult = fit( x(:,q), y(:,q), ft, fo);
end
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!