首页 > 解决方案 > 使用 numpy 获得两个 ND(3-D)矩阵的点积的正确方法是什么?

问题描述

我想沿着批处理维度获得两个数组的点积。np.dot给出了一个超级奇怪的结果。假设我有一批大小为 2 的批次。那么获得结果的正确方法是什么?

X = np.random.randn(2,3,4)
X_t = np.transpose(X,axes=[0,2,1]) # shape now is [2,4,3]
np.matmul(X,X_t) # shape is [2,3,3]
np.dot(X,X_t) # shape is [2,3,2,3] SUPER Weird
np.einsum('ijk,ikl->ijl',X,X_t) # Dimension as [2,3,3] Same as Matmul()

对于这样的条件,矩阵乘法的正确方法是什么?

标签: pythonnumpymath

解决方案


使用@运算符。它减少了第一(0)维。

Matmul对于其他暗淡。

import numpy as np

x = np.random.randn(2, 3, 4)
x_t = np.transpose(x, axes=[0, 2, 1])  # shape now is [2,4,3]

wrong = np.dot(x, x_t)  # shape is [2,3,2,3] SUPER Weird
res = x @ x_t

print(res.shape)
print(wrong.shape)

出去:

(2, 3, 3)
(2, 3, 2, 3)

推荐阅读