【问题标题】:Torch, which command to insert data in a Torch Tensor?Torch,在 Torch 张量中插入数据的命令是什么?
【发布时间】:2015-09-20 12:54:51
【问题描述】:

我正在使用 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 张量可以让一切变得更高效。 所以我用

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

但不幸的是,我找不到任何能够替换 table.insert() 函数的张量函数。

你有什么想法吗?

【问题讨论】:

    标签: torch


    【解决方案1】:

    由于张量对象是固定大小的,因此没有与插入的附加功能相对应的功能。 我看到您的代码所做的是将三个表连接为一个。如果您使用的是张量:

     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)
    

    【讨论】:

      猜你喜欢
      • 2021-10-07
      • 2023-04-02
      • 2017-09-11
      • 2016-07-02
      • 2017-09-30
      • 2015-09-20
      • 2016-03-21
      • 2020-08-27
      • 2015-06-08
      相关资源
      最近更新 更多