如何高效选取TorchLua数组或张量的任意子集?
- 内容介绍
- 文章标签
- 相关推荐
本文共计379个文字,预计阅读时间需要2分钟。
我正在使用Python/Lua,并拥有一个包含10个元素的数组数据集。数据集如下:dataset={11, 12, 13, 14, 15, 16, 17, 18, 19, 20}。如果我想读取数组中的第1个元素,我可以直接访问dataset[1]。我只需要选择数组中的前3个元素。
我正在使用火炬/ Lua,并拥有10个元素的阵列数据集.dataset = {11,12,13,14,15,16,17,18,19,20}
如果我写数据集[1],我可以读取数组的第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是’start’索引,3是’end’索引.
使用Tensor.sub和Tensor.narrow查看更多替代方案Extracting Sub-tensors
在Lua 5.2以内
Lua表,如您的数据集变量,没有选择子范围的方法.
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
本文共计379个文字,预计阅读时间需要2分钟。
我正在使用Python/Lua,并拥有一个包含10个元素的数组数据集。数据集如下:dataset={11, 12, 13, 14, 15, 16, 17, 18, 19, 20}。如果我想读取数组中的第1个元素,我可以直接访问dataset[1]。我只需要选择数组中的前3个元素。
我正在使用火炬/ Lua,并拥有10个元素的阵列数据集.dataset = {11,12,13,14,15,16,17,18,19,20}
如果我写数据集[1],我可以读取数组的第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是’start’索引,3是’end’索引.
使用Tensor.sub和Tensor.narrow查看更多替代方案Extracting Sub-tensors
在Lua 5.2以内
Lua表,如您的数据集变量,没有选择子范围的方法.
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

