我有2个张量
a = torch.tensor([1,2])
b = torch.tensor([[[10,20],
[30,40]],
[[1,2],
[3,4]]])
我想将它们结合起来
a ? b = tensor([[[10,20],
[30,40]],
[[ 2, 4],
[ 6, 8]]])
(然后在第0维上求和,最后我要进行加权求和)
我尝试过:
""" no idea how to interpret that """
a @ b
tensor([[ 70, 100],
[ 7, 10]])
b @ a
tensor([[ 50, 110],
[ 5, 11]])
for i in range(b.size()[0]): # works but I don't think this will work with autograd
b[i] *= a[i]
a * b # multiplies right side by 2
tensor([[[10, 40],
[30, 80]],
[[ 1, 4],
[ 3, 8]]])
a.unsqueeze(1) # multiplies bottom side by 2
tensor([[[10, 20],
[60, 80]],
[[ 1, 2],
[ 6, 8]]])
a.unsqueeze(2) * b # dimension out of range
答案 0 :(得分:2)
这应该有效c = a.unsqueeze(1).unsqueeze(1) * b
答案 1 :(得分:1)
您还可以尝试以下代码:
a = torch.tensor([1,2])
b = torch.tensor([[[10,20],
[30,40]],
[[1,2],
[3,4]]])
print((a.view(-1, 1)*torch.flatten(b, 1)).view(b.shape))
输出:
tensor([[[10, 20],
[30, 40]],
[[ 2, 4],
[ 6, 8]]])
在这里,我们基本上正在执行以下步骤:
a
重塑为大小为[a.shape[0],1]
的二维张量,即上述情况下的[2, 1]
。torch.flatten()
从第一个维度(即b
)开始使张量start_dim=1
变平。在此,默认为end_dim=-1
。结果大小为[2, 4]
。b
相同的形状,即[2, 2, 2]
。答案 2 :(得分:0)
有趣的是-我尝试了几种不同的广播技巧,但没有看到任何明显的胜利,所以简单的版本:
b[0] *= a[0]
b[1] *= a[1]
c = b