我认为{
最初,我定义了一个空张量。然后我想在它上面加上一个一维张量多次
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)
如何做到这一点
从torch.cat的文档中可以看出,“所有张量必须具有相同的形状(连接维度除外)或为空”。因此,最简单的解决方案是向要添加的张量再添加一个维度(大小为1)。然后,您将得到大小为(n,任意)和(1,任意)的张量,它们将沿第0维连接,满足torch.cat的要求
代码:
输出:
相关问题 更多 >
编程相关推荐