Matlab效率 - 矢量化

时间:2014-05-31 08:29:27

标签: matlab vectorization performance

我有运行的这个Matlab代码,但我希望通过删除for循环使其更快,并且基本上仅使用矩阵进行相同的计算(我的数据集非常大,所以我需要这种优化):

Matrices dimensions: x(N,D), m(K,D), p(K), fL(N,K), maxf(N), maxfL(N), z(N,K).
Also p, maxf, maxfL are row vectors

代码1:

f = zeros(N,K);
maxf = zeros(1,N);

for n=1:N
   for k=1:K
      % here i had a loop for d dimension but made it more efficient like this:
      f2 = x(n,:) * log(m(k,:))' + (1 - x(n,:)) * log(1 - m(k,:))';
      f(n,k) = log(p(k)) + f2;
   end
   maxf(n) = max(f(n,:));
   f(n,:) = f(n,:) - maxf(n);
end

代码2:

for k=1:K
  sum2 = sum(z(:,k)); 
  p(k)= sum2/N;
  for d=1:D
     % here i had a n loop for sum1 and made it like this:
     sum1 = z(:,k)' * x(:,d); 
     m(k,d) = sum1/sum2;
  end
end

CODE3:

L_new = 0;
for n=1:N
  suma = sum(fL(n,:));
  L_new = L_new + maxfL(n) + log(suma);
end

我现在将在工作量中使用以下提供的答案(N = 1000,K = 2,D = 784)总结一些平均执行时间(结果以秒为单位):

CodeNumber                      Execution Time
    1           3.98(for_loops), 1.01(Divakar), 0.5(Nishant)
    2           0.2(for_loops), 0.40-0.42(Divakar-2 approaches), 0.13(Nishant)
    3           0.03(for_loops), 0.0026(Divakar), 0.0024(Nishant)

感谢您的回答!!

2 个答案:

答案 0 :(得分:2)

代码1:

f2 = x*log(m)' + (1-x)*(log(1-m))' ;
f = f2 + ones(N,1)*log(p);
maxf = max(f');
f = f - maxf'*ones(1,K);

代码2:

sum2 = sum(z);
sum1 = z'*x;
temp = sum2'*ones(1,D);
m = sum1./temp;
p  = sum2/N;  

代码3:

L_new = sum(log(sum(fL'))) + sum(maxfL');

答案 1 :(得分:1)

试试这些 -

代码1:

tp1 = squeeze(sum(bsxfun(@times,x,permute(log(m),[3 2 1])),2))
tp2 = squeeze(sum(bsxfun(@times,1-x,permute(log(1-m),[3 2 1])),2))
tp3 = tp1 + tp2
f = bsxfun(@plus,tp3,log(p))
f = bsxfun(@minus,f,max(f,[],2))

代码2:

p = sum(z)./N;
m = bsxfun(@rdivide,squeeze(sum(bsxfun(@times,x,permute(z,[1 3 2]))))',sum(z)');

代码2: [方法2] -

p = sum(z)./N;
sum2_1 = sum(z);
m = zeros(K,D);
for k=1:K  
  m(k,:) = sum(bsxfun(@times,x,z(:,k)))./sum2_1(k);
end

代码3:(假设您从某处获得maxfL

L_new = sum(maxfL' + log(sum(fL,2)))