减少Lua Torch中张量的一个维度

时间:2015-12-11 06:42:55

标签: torch

我有一个形状的张量X

(2,[...])

其中三个点可以是任何尺寸矢量(即:4,4)

我想将此张量转换为形状为

的张量
(1,[...])

换句话说,我想减少第一维的维度。当然,我将松开由2索引的信息,但在这种情况下无关紧要。问题并非微不足道,因为我不知道张量的维数。但至少它大于或等于2.第一个代码写在下面:

th> x = torch.Tensor(2, 4, 4):fill(1)
th> y = x[1]
th> z = torch.Tensor()
th> z[1] = y -- bad argument #1 to '?' (empty tensor at /home/ubuntu/torch/pkg/torch/generic/Tensor.c:684)

你有什么想法怎么做?

非常感谢提前

2 个答案:

答案 0 :(得分:2)

  

我想减少第一维的维度

如果减少你的意思是narrow down那么你就可以这样做:

x = torch.Tensor(2, 4, 4)
x[1]:fill(0)
x[2]:fill(1)

-- this creates tensors of size 1x4x4
-- the first dimension is narrowed, one index at a time
a = x:narrow(1, 1, 1)
b = x:narrow(1, 2, 1)

这给出了:

> print(a)
(1,.,.) = 
  0  0  0  0
  0  0  0  0
  0  0  0  0
  0  0  0  0
[torch.DoubleTensor of size 1x4x4]

> print(b)
(1,.,.) = 
  1  1  1  1
  1  1  1  1
  1  1  1  1
  1  1  1  1
[torch.DoubleTensor of size 1x4x4]

答案 1 :(得分:1)

此代码可满足您的需求:

y = x[{{1, 1}, {}, {}}]

未知数量的维度?没问题,您不必全部指定:

y = x[{{1, 1}}]

(1,.,.) = 
  1  1  1  1
  1  1  1  1
  1  1  1  1
  1  1  1  1
[torch.DoubleTensor of size 1x4x4]
相关问题