如果您只想用零填充张量(而不仅仅是在某处添加额外的零),则可以使用torch.nn.functional.pad
:
import torch
t = torch.arange(8).reshape(1, 4, 2).float()
x = torch.nn.functional.pad(t, (1, 1, 1, 1))# 左、右、上、下各填充‘’1‘’个0
print(x)
0 0 0 0
0 1 2 0
0 3 4 0
0 5 6 0
0 7 8 0
0 0 0 0
如果您只想用零填充张量(而不仅仅是在某处添加额外的零),则可以使用torch.nn.functional.pad
:
import torch
t = torch.arange(8).reshape(1, 4, 2).float()
x = torch.nn.functional.pad(t, (1, 1, 1, 1))# 左、右、上、下各填充‘’1‘’个0
print(x)
0 0 0 0
0 1 2 0
0 3 4 0
0 5 6 0
0 7 8 0
0 0 0 0