[英]Appending zero rows to a 2D Tensor in PyTorch
假设我有一个形状为(n,m)
的张量 2D 张量x
。 如何通过指定零行在结果张量中的位置索引,在x
中附加零行来扩展张量的第一维? 举个具体的例子:
x = torch.tensor([[1,1,1],
[2,2,2],
[3,3,3],
[4,4,4]])
我想要 append 2 零行,以便它们的行索引在结果张量中分别为 1,3? 即在示例中,结果将是
X = torch.tensor([1,1,1],
[0,0,0],
[2,2,2],
[0,0,0],
[3,3,3],
[4,4,4]])
我尝试使用F.pad
和reshape
。
您可以使用torch.cat
:
def insert_zeros(x, all_j):
zeros_ = torch.zeros_like(x[:1])
pieces = []
i = 0
for j in all_j + [len(x)]:
pieces.extend([x[i:j],
zeros_])
i = j
return torch.cat(pieces[:-1],
dim=0 )
# insert_zeros(x, [1,2])
# tensor([[1, 1, 1],
# [0, 0, 0],
# [2, 2, 2],
# [0, 0, 0],
# [3, 3, 3],
# [4, 4, 4]])
此代码与反向传播兼容,因为张量未就地修改。
您可以使用torch.tensor.index_add_
。
import torch
zero_index = [1, 3]
size = (6, 3)
x = torch.tensor([[1,1,1],
[2,2,2],
[3,3,3],
[4,4,4]])
t = torch.zeros(size, dtype=torch.int64)
index = torch.tensor([i for i in range(size[0]) if i not in zero_index])
# index -> tensor([0, 2, 4, 5])
t.index_add_(0, index, x)
print(t)
Output:
tensor([[1, 1, 1],
[0, 0, 0],
[2, 2, 2],
[0, 0, 0],
[3, 3, 3],
[4, 4, 4]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.