arrays - torch /Lua,如何选择数组或张量的子集?

标签 arrays lua torch

我正在研究Torch/Lua,并且具有10个元素的dataset数组。

dataset = {11,12,13,14,15,16,17,18,19,20}

如果我写dataset[1],我可以读取数组的第一个元素的结构。
th> dataset[1]
11  

我只需要在全部10个元素中选择3个元素,但是我不知道要使用哪个命令。
如果我在Matlab上工作,我会写:dataset[1:3],但是这里不起作用。

你有什么建议吗?

最佳答案

在火炬

th> x = torch.Tensor{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

要选择范围,例如前三个,请使用the index operator:
th> x[{{1,3}}]
1
2
3

其中1是“开始”索引,而3是“结束”索引。

有关Tensor.sub和Tensor.narrow的更多替代方案,请参见Extracting Sub-tensors

在Lua 5.2或更低版本中

Lua表(例如dataset变量)没有选择子范围的方法。
function subrange(t, first, last)
  local sub = {}
  for i=first,last do
    sub[#sub + 1] = t[i]
  end
  return sub
end

dataset = {11,12,13,14,15,16,17,18,19,20}

sub = subrange(dataset, 1, 3)
print(unpack(sub))

哪个打印
11    12   13

在Lua 5.3中

在Lua 5.3中,您可以使用 table.move
function subrange(t, first, last)
     return table.move(t, first, last, 1, {})
end

关于arrays - torch /Lua,如何选择数组或张量的子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31304601/

相关文章:

ios - 显示选定单元格的 UICollectionView

c - 一次一行从 .txt 文件读取到数组(Matlab 或 C)。 "Insufficient memory"使用 'A=load()' 一次加载整个文件。

python - 如何将 ndarray 转换为 scipy 中的矩阵?

lua - 如何在 Lua 中以格式化字符串的形式获取本地时间

python - "AssertionError: Torch not compiled with CUDA enabled"尽管升级到 CUDA 版本

android - torch 应用程序问题

python - 撇号和列表错误

c++ - 使用可变参数模板从 Lua 函数回调 (C api) 中提取参数

loops - Lua:表的意外迭代结果

python - 来自 torch._C import * ImportError : DLL load failed: The specified module could not be found