PyTorch:逐行点积

Jac*_*lph 3 python dot-product pytorch tensor

假设我有两个张量:

a = torch.randn(10, 1000, 1, 4)
b = torch.randn(10, 1000, 6, 4)
Run Code Online (Sandbox Code Playgroud)

其中第三个索引是向量的索引。

我想取每个向量之间的点积b相对于in中的向量a

为了说明,这就是我的意思:

dots = torch.Tensor(10, 1000, 6, 1)
for b in range(10):
     for c in range(1000):
           for v in range(6):
            dots[b,c,v] = torch.dot(b[b,c,v], a[b,c,0]) 
Run Code Online (Sandbox Code Playgroud)

我将如何使用火炬功能实现这一目标?

小智 6

a = torch.randn(10, 1000, 1, 4)
b = torch.randn(10, 1000, 6, 4)

c = torch.sum(a * b, dim=-1)

print(c.shape)
Run Code Online (Sandbox Code Playgroud)

torch.Size([10, 1000, 6])

c = c.unsqueeze(-1)
print(c.shape)
Run Code Online (Sandbox Code Playgroud)

torch.Size([10, 1000, 6, 1])