Save fitcsvms running in parfor loop

2 views (last 30 days)
I have a code which I am trying to get running faster, it has 3 fitcsvm function. To do so (I cannot use the GPU) I decided to perform a parfor loop.
However, I cannot use the save function and if the save is outside the loop a 'variable not found' error occurs
parfor i = 1:3
if i == 1
SVM_tt = fitcsvm(features_dt(:,1:10),features_dt(:,11),...
'Standardize',true,'KernelFunction','RBF','BoxConstraint', tt_C, 'KernelScale',tt_sigma);
if i == 2
SVM_bb = fitcsvm(features_bp(:,1:10),features_bp(:,11),...
'Standardize',true,'KernelFunction','RBF','BoxConstraint', bb_C, 'KernelScale',bb_sigma);
if i == 3
SVM_ss = fitcsvm(features_swa(:,1:10),features_swa(:,11),...
'Standardize',true,'KernelFunction','RBF','BoxConstraint', ss_C, 'KernelScale',ss_sigma);
Without the parfor loop the code wors perfectly fine.
Thank you,

Accepted Answer

Edric Ellis
Edric Ellis on 6 Aug 2019
Your outputs are not available after the parfor loop because the parfor variable classification considers them to be loop temporary variables. More details in the doc.
The simplest thing to do here is to make cell array inputs and outputs for your parfor loop.
% Step 1 - set up input cell arrays
features = {features_dt, features_bp, features_swa};
constraints = {tt_C, bb_C, ss_C};
scales = {tt_sigma, bb_sigma, ss_sigma};
parfor i = 1:3
% Step 2 - access cell array contents in parfor loop
f = features{i};
SVM{i} = fitcsvm(f(:, 1:10), f(:, 11), ...
'BoxConstraint', constraints{i}, ...
% Step 3 - split output cell array
[SVM_tt, SVM_bb, SVM_ss] = deal(SVM{:});
This works because parfor sees the "sliced" assignment into SVM, and knows that you are performing independent computations, and that it can therefore make the value available after the loop completes.
  1 Comment
Edric Ellis
Edric Ellis on 6 Aug 2019
Moving answer from OP to comment:
Thank you so much!
It works perfectly. :)

Sign in to comment.

More Answers (0)


Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!