在 torch7 中初始化张量的快速方法

Fast way to initialize a tensor in torch7

我需要在 torch7 中使用索引相关函数初始化 3D 张量,即

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

然后我像这样初始化一个 3D 张量 A:

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

但是这段代码运行起来很慢,我发现它占用了总运行时间的92%。有没有更有效的方法来初始化 torch7 中的 3D 张量?

请参阅 Tensor:apply

的文档

These functions apply a function to each element of the tensor on which the method is called (self). These methods are much faster than using a for loop in Lua.

文档中的示例根据其索引 i(在内存中)初始化一个二维数组。下面是 3 维的扩展示例,下面是 N-D 张量的扩展示例。使用 apply 方法很多,much 在我的机器上更快:

require 'torch'

A = torch.Tensor(100, 100, 1000)
B = torch.Tensor(100, 100, 1000)

function func(i,j,k) 
    return i*j*k    
end

t = os.clock()
for i=1,A:size(1) do
    for j=1,A:size(2) do
        for k=1,A:size(3) do
            A[{i, j, k}] = i * j * k
        end
    end
end
print("Original time:", os.difftime(os.clock(), t))

t = os.clock()
function forindices(A, func)
  local i = 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 then
      k = 1
      j = j + 1
      if j > d2 then
        j = 1
        i = i + 1
      end
    end
    return func(i, j, k)
  end
end

B:apply(forindices(A, func))
print("Apply method:", os.difftime(os.clock(), t))

编辑

这适用于任何张量对象:

function tabulate(A, f)
  local idx = {}
  local ndims = A:dim()
  local dim = A:size()
  idx[ndims] = 0
  for i=1, (ndims - 1) do
    idx[i] = 1
  end
  return A:apply(function()
    for i=ndims, 0, -1 do
      idx[i] = idx[i] + 1
      if idx[i] <= dim[i] then
        break
      end
      idx[i] = 1
    end
    return f(unpack(idx))
  end)
end

-- usage for 3D case.
tabulate(A, function(i, j, k) return i * j * k end)