对堆栈的连续调用抛出RuntimeError:堆栈期望每个张量大小相等

2024-04-27 19:52:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我认为{}和{}都不能完全满足我的要求

最初,我定义了一个空张量。然后我想在它上面加上一个一维张量多次

x = torch.tensor([]).type(torch.DoubleTensor)
y = torch.tensor([ 0.3981,  0.6952, -1.2320]).type(torch.DoubleTensor)
x = torch.stack([x,y])

这将抛出一个错误:

RuntimeError: stack expects each tensor to be equal size, but got [0] at entry 0 and [3] at entry 1

因此,我必须将x初始化为torch.tensor([0,0,0])(但这可以避免吗?)

x = torch.tensor([0,0,0]).type(torch.DoubleTensor)
y = torch.tensor([ 0.3981,  0.6952, -1.2320]).type(torch.DoubleTensor)
x = torch.stack([x,y])  # this is okay
x = torch.stack([x,y])  # <--- this got error again

但是当我第二次运行x = torch.stack([x,y])时,我得到了以下错误:

RuntimeError: stack expects each tensor to be equal size, but got [2, 3] at entry 0 and [3] at entry 1

我想要实现的是能够多次附加1d张量(每次添加的1d张量不同,为了简单起见,这里我使用相同的张量)**:

tensor([[ 0.3981,  0.6952, -1.2320],
        [ 0.3981,  0.6952, -1.2320],
        [ 0.3981,  0.6952, -1.2320],
        [ 0.3981,  0.6952, -1.2320],
        ...
        [ 0.3981,  0.6952, -1.2320]], dtype=torch.float64)

如何做到这一点


Tags: tostacktype错误torchequalbeat
1条回答
网友
1楼 · 发布于 2024-04-27 19:52:22

从torch.cat的文档中可以看出,“所有张量必须具有相同的形状(连接维度除外)或为空”。因此,最简单的解决方案是向要添加的张量再添加一个维度(大小为1)。然后,您将得到大小为(n,任意)和(1,任意)的张量,它们将沿第0维连接,满足torch.cat的要求

代码:

x = torch.empty(size=(0,3))
y = torch.tensor([ 0.3981,  0.6952, -1.2320])
for n in range(5):
    y1 = y.unsqueeze(dim=0) # same as y but with shape (1,3)
    x = torch.cat([x,y1], dim=0)
print(x)

输出:

tensor([[ 0.3981,  0.6952, -1.2320],
        [ 0.3981,  0.6952, -1.2320],
        [ 0.3981,  0.6952, -1.2320],
        [ 0.3981,  0.6952, -1.2320],
        [ 0.3981,  0.6952, -1.2320]])

相关问题 更多 >