我有一个张量 t
1 2
3 4
5 6
7 8
我也想成功
0 0 0 0
0 1 2 0
0 3 4 0
0 5 6 0
0 7 8 0
0 0 0 0
我尝试使用 new=torch.tensor([0.0.0.0.]) 张量堆叠四次,但这不起作用。
t = torch.arange(8).reshape(1,4,2).float()
print(t)
new=torch.tensor([[0., 0., 0.,0.]])
print(new)
r = torch.stack([t,new]) # invalid argument 0: Tensors must have same number of dimensions: got 4 and 3
new=torch.tensor([[[0., 0., 0.,0.]]])
print(new)
r = torch.stack([t,new]) # invalid argument 0: Sizes of tensors must match except in dimension 0.
我也尝试过cat,但也不起作用。
最佳答案
最好先初始化所需形状的数组,然后在适当的索引处添加数据。
import torch
t = torch.arange(8).reshape(1,4,2).float()
x = torch.zeros((1, t.shape[1]+2, t.shape[2]+2))
x[:, 1:-1, 1:-1] = t
print(x)
另一方面,如果您只想用零填充张量(而不仅仅是在某处添加额外的零),您可以使用torch.nn.function.pad
:
import torch
t = torch.arange(8).reshape(1, 4, 2).float()
x = torch.nn.functional.pad(t, (1, 1, 1, 1))
print(x)
关于python - 在两个维度上将零填充到张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58007525/