Torch,它命令在Torch Tensor中插入数据?

时间:2015-07-02 20:22:35

标签: torch

我使用Torch命令将数据插入到一个简单的表中,它运行正常:

completeProfile = {};
table.foreach(firstHalf, function(i,v)table.insert(completeProfile,v) end);
table.foreach(secondHalf, function(i,v)table.insert(completeProfile,v) end);
table.foreach(presentWord, function(i,v) table.insert(completeProfile,v) end);

现在有人让我注意到使用Torch Tensors会让一切变得更有效率。 所以我用

替换了第一行
completeProfile = torch.Tensor(CONSTANT_NUMBER);

但遗憾的是我找不到任何能够替换table.insert()函数的Tensor函数。

你有什么想法吗?

1 个答案:

答案 0 :(得分:2)

由于Tensor对象是固定大小,因此没有与insert的追加功能相对应的函数。 我看到你的代码正在做的是将三个表连接成一个。如果您使用的是Tensors:

 firstHalf = torch.Tensor(firstHalf)
 secondHalf = torch.Tensor(secondHalf)
 presentWord = torch.Tensor(presentWord)

然后将它们连接在一起很容易:

 completeProfile = firstHalf:cat(secondHalf):cat(presentWord)

另一种选择是存储您插入的最后一个索引,以便您知道在哪里"追加"在张量上。下面的函数创建一个闭包,用于跟踪最后一个索引。

function appender(t)
   local last = 0
   return function(i, v)
       last = last + 1
       t[last] = v
   end
end

completeProfile = torch.Tensor(#firstHalf + #secondHalf + #presentWord)

profile_append = appender(completeProfile)

table.foreach(firstHalf, profile_append)
table.foreach(secondHalf, profile_append)
table.foreach(presentWord, profile_append)
相关问题