添加两个火炬张量列表
Add two torch tensor list
我想把两个PyTorch张量加在一起,例如让
a = tensor([[1., 1., 2.],
[1., 1., 2.],
[1., 1., 2.],
[1., 1., 2.],
[1., 1., 2.],
[1., 1., 2.]])
b = tensor([[4., 5., 6., 7., 8., 9.],
[4., 5., 6., 7., 8., 9.],
[4., 5., 6., 7., 8., 9.],
[4., 5., 6., 7., 8., 9.],
[4., 5., 6., 7., 8., 9.],
[4., 5., 6., 7., 8., 9.]])
我希望生成的张量 c
为:
c = tensor([[5., 6., 8., 8., 9., 11.],
[5., 6., 8., 8., 9., 11.],
[5., 6., 8., 8., 9., 11.],
[5., 6., 8., 8., 9., 11.],
[5., 6., 8., 8., 9., 11.],
[5., 6., 8., 8., 9., 11.]])
注意:b.shape[1]
始终是 a.shape[1]
的倍数。
有没有比下面解决方案更好的方法?
fin = torch.Tensor()
for i in range(int(b.shape[1]/a.shape[1])):
target = b[:,batch*i:batch*(i+1)]
temp = torch.add(target, a)
fin = torch.cat([fin, temp], dim =1)
c = fin
您可以重复 a
的列以匹配 b
的形状与 torch.Tensor.repeat
,然后将生成的张量添加到 b
:
>>> b + a.repeat(1, b.size(1)//a.size(1))
tensor([[ 5., 6., 8., 8., 9., 11.],
[ 5., 6., 8., 8., 9., 11.],
[ 5., 6., 8., 8., 9., 11.],
[ 5., 6., 8., 8., 9., 11.],
[ 5., 6., 8., 8., 9., 11.],
[ 5., 6., 8., 8., 9., 11.]])
我想把两个PyTorch张量加在一起,例如让
a = tensor([[1., 1., 2.],
[1., 1., 2.],
[1., 1., 2.],
[1., 1., 2.],
[1., 1., 2.],
[1., 1., 2.]])
b = tensor([[4., 5., 6., 7., 8., 9.],
[4., 5., 6., 7., 8., 9.],
[4., 5., 6., 7., 8., 9.],
[4., 5., 6., 7., 8., 9.],
[4., 5., 6., 7., 8., 9.],
[4., 5., 6., 7., 8., 9.]])
我希望生成的张量 c
为:
c = tensor([[5., 6., 8., 8., 9., 11.],
[5., 6., 8., 8., 9., 11.],
[5., 6., 8., 8., 9., 11.],
[5., 6., 8., 8., 9., 11.],
[5., 6., 8., 8., 9., 11.],
[5., 6., 8., 8., 9., 11.]])
注意:b.shape[1]
始终是 a.shape[1]
的倍数。
有没有比下面解决方案更好的方法?
fin = torch.Tensor()
for i in range(int(b.shape[1]/a.shape[1])):
target = b[:,batch*i:batch*(i+1)]
temp = torch.add(target, a)
fin = torch.cat([fin, temp], dim =1)
c = fin
您可以重复 a
的列以匹配 b
的形状与 torch.Tensor.repeat
,然后将生成的张量添加到 b
:
>>> b + a.repeat(1, b.size(1)//a.size(1))
tensor([[ 5., 6., 8., 8., 9., 11.],
[ 5., 6., 8., 8., 9., 11.],
[ 5., 6., 8., 8., 9., 11.],
[ 5., 6., 8., 8., 9., 11.],
[ 5., 6., 8., 8., 9., 11.],
[ 5., 6., 8., 8., 9., 11.]])