我正在尝试使用PyTorch生成矢量矩阵外积(张量)。假设向量v的大小为p且矩阵M的大小为qXr,则乘积的结果应为pXqXr。
例:
#…
如果[batch_size,z,x,y]是目标矩阵的形状,另一种解决方案是在每个位置构建具有适当元素的这种形状的两个矩阵,然后应用元素乘法。它适用于一批矢量:
# input matrices batch_size = 2 x1 = torch.Tensor([0,1]) x2 = torch.Tensor([[0,1,2], [3,4,5]]) x1 = x1.unsqueeze(0).repeat((batch_size, 1)) x2 = x2.unsqueeze(0).repeat((batch_size, 1, 1)) # dimensions b = x1.shape[0] z = x1.shape[1] x = x2.shape[1] y = x2.shape[2] # solution mat1 = x1.reshape(b, z, 1, 1).repeat(1, 1, x, y) mat2 = x2.reshape(b,1,x,y).repeat(1, z, 1, 1) mat1*mat2
您可以使用 einsum
torch.einsum('bp, bqr->bpqr', v, M) #batch version (v.shape=(b,p) M.shape=(b,q,r)) torch.einsum('p, qr->pqr', v, M) #non batch version
我能用以下代码完成它。
单向量和矩阵
v = torch.arange(3) M = torch.arange(8).view(2, 4) # v: tensor([0, 1, 2]) # M: tensor([[0, 1, 2, 3], # [4, 5, 6, 7]]) torch.mm(v.unsqueeze(1), M.view(1, 2*4)).view(3,2,4) tensor([[[ 0, 0, 0, 0], [ 0, 0, 0, 0]], [[ 0, 1, 2, 3], [ 4, 5, 6, 7]], [[ 0, 2, 4, 6], [ 8, 10, 12, 14]]])
对于一批矢量和矩阵,可以使用它轻松扩展 torch.bmm 。
torch.bmm
v = torch.arange(batch_size*2).view(batch_size, 2) M = torch.arange(batch_size*3*4).view(batch_size, 3, 4) torch.bmm(v.unsqueeze(2), M.view(-1, 1, 3*4)).view(-1, 2, 3, 4)