for loop - Fast way to initialize a tensor in torch7 -


i need initialize 3d tensor index-dependent function in torch7, i.e.

func = function(i,j,k)  --i, j index of element in tensor     return i*j*k        --do operations within func which're dependent of i, j end 

then initialize 3d tensor this:

for i=1,a:size(1)     j=1,a:size(2)         k=1,a:size(3)             a[{i,j,k}] = func(i,j,k)         end     end end 

but code runs slow, , found takes 92% of total running time. there more efficient ways initialize 3d tensor in torch7?

see documentation tensor:apply

these functions apply function each element of tensor on method called (self). these methods faster using loop in lua.

the example in docs initializes 2d array based on index (in memory). below extended example 3 dimensions , below 1 n-d tensors. using apply method much, much faster on machine:

require 'torch'  = torch.tensor(100, 100, 1000) b = torch.tensor(100, 100, 1000)  function func(i,j,k)      return i*j*k     end  t = os.clock() i=1,a:size(1)     j=1,a:size(2)         k=1,a:size(3)             a[{i, j, k}] = * j * k         end     end end print("original time:", os.difftime(os.clock(), t))  t = os.clock() function forindices(a, func)   local = 1   local j = 1   local k = 0   local d3 = a:size(3)   local d2 = a:size(2)    return function()     k = k + 1     if k > d3       k = 1       j = j + 1       if j > d2         j = 1         = + 1       end     end     return func(i, j, k)   end end  b:apply(forindices(a, func)) print("apply method:", os.difftime(os.clock(), t)) 

edit

this work tensor object:

function tabulate(a, f)   local idx = {}   local ndims = a:dim()   local dim = a:size()   idx[ndims] = 0   i=1, (ndims - 1)     idx[i] = 1   end   return a:apply(function()     i=ndims, 0, -1       idx[i] = idx[i] + 1       if idx[i] <= dim[i]         break       end       idx[i] = 1     end     return f(unpack(idx))   end) end  -- usage 3d case. tabulate(a, function(i, j, k) return * j * k end) 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -