Speed up Some Code

25 visualizzazioni (ultimi 30 giorni)
Stephen Gray il 18 Mag 2024 alle 15:03
Commentato: Voss il 19 Mag 2024 alle 16:35
Hi all. I'm trying to speed up the code below. It's from the SMOTE function that was wrtitten for MATLAB and works really well. The only thing is that the loops are not fast. I've looked at Parfor but that wouldn't work and I can't see how I can vectorise it either. It could be I just have to suck it up and wait but just in case, the code is :-
% This is where the magic happens ;-)
% X : Observational matrix (rows are observations, columns are variables)
% J : Synthesization vector. It has the same length as the number of
% observations (rows) in X. J determines how many times each
% observation is used as a base for synthesization.
% k : Number of nearest neighbors to consider when synthesizing.
function Xn = simpleSMOTE(X,J,k)
tic
HNSMdl = hnswSearcher(X); % To remove this, comment out this line and replace the HNSMdl below with X
[idx, ~] = knnsearch(HNSMdl,X,'k',k+1); % Find nearest neighbors (add one to the number of neighbors to find, as observations are their own nearest neighbor)
toc
Xn = nan(sum(J),size(X,2)); % Pre-allocate memory for synthesized observations
% Iterate through observations to create to synthesize new observations
for ii=1:numel(J)
P = randperm(k,J(ii))+1; % Randomize nearest neighbor pick (never pick first nearest neighbor as this is the observation itself)
for jj=1:J(ii)
x = X(idx(ii,1),:); % Observation
xk = X(idx(ii,P(jj)),:); % Nearest neighbor
Xn(sum(J(1:ii-1))+jj,:) = (xk-x)*rand+x; % Synthesize observation
end
end
end
It's from the 'for ii' bit that is slow and there are around 750000 items of 13 variables.
Steve
0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Risposta accettata

Voss il 18 Mag 2024 alle 19:14
% generate and collect all the P's first
nJ = numel(J);
P = cell(1,nJ);
for ii = 1:nJ
P{ii} = randperm(k,J(ii))+1;
end
P = [P{:}];
% then do the rest in one fell swoop
ii = repelem(1:nJ,J);
xk = X(idx(sub2ind(size(idx),ii,P)),:);
x = X(idx(ii,1),:);
Xn = (xk-x).*rand(numel(ii),1)+x;
2 CommentiMostra NessunoNascondi Nessuno
Stephen Gray il 19 Mag 2024 alle 12:18
Much quicker thanks! Also a good example of how to vectorise.
Steve
Voss il 19 Mag 2024 alle 16:35
You're welcome!

Accedi per commentare.

Categorie

Scopri di più su Nearest Neighbors in Help Center e File Exchange

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by