将具有不同长度的 2D 张量列表转换为一个 3D 张量
Turning list of 2D tensors with different length to one 3D tensor
我有一个包含 3 个张量的列表,其形状为:(8, 2), (8, 4), (8, 6)
我想把这个列表变成这个形状:(8, 3, x)
我该怎么做?我知道我需要使用 torch.cat
、torch.stack
和 torch.transpose
的某种组合,但我想不通。
提前致谢!
如你所说,需要用torch.cat
,还要用torch.reshape
。假设如下:
a = torch.rand(8,2)
b = torch.rand(8,4)
c = torch.rand(8,6)
并假设确实可以将张量重塑为 (8,3,-1)
形状,其中 -1
代表需要的长度,那么:
d = torch.cat((a,b,c), dim=1)
e = torch.reshape(d, (8,3,-1))
我会解释的。因为第一维如果在 a,b,c
中不同,则连接必须沿着第一维,如变量 d
中所示。然后,您可以重塑张量,如 e
所示,其中 -1
代表“只要它需要”。
我有一个包含 3 个张量的列表,其形状为:(8, 2), (8, 4), (8, 6)
我想把这个列表变成这个形状:(8, 3, x)
我该怎么做?我知道我需要使用 torch.cat
、torch.stack
和 torch.transpose
的某种组合,但我想不通。
提前致谢!
如你所说,需要用torch.cat
,还要用torch.reshape
。假设如下:
a = torch.rand(8,2)
b = torch.rand(8,4)
c = torch.rand(8,6)
并假设确实可以将张量重塑为 (8,3,-1)
形状,其中 -1
代表需要的长度,那么:
d = torch.cat((a,b,c), dim=1)
e = torch.reshape(d, (8,3,-1))
我会解释的。因为第一维如果在 a,b,c
中不同,则连接必须沿着第一维,如变量 d
中所示。然后,您可以重塑张量,如 e
所示,其中 -1
代表“只要它需要”。