How can you compute one dot product for each matching row pair?
einsum uses index labels to align dimensions. Labels omitted from an explicit output are summed over.
numpy.einsum in practice
The expression ij,ij->i retains the row label and sums over features. Two corresponding pairs yield two scores, avoiding a full cross-row similarity matrix.
import numpy as np
np.einsum('ij,ij->i',[[1,2],[3,4]],[[2,1],[0,2]])Result [4, 8]
中文
如何一次计算每对对应向量的内积?
einsum 用重复下标对齐维度,显式输出中省略的下标被求和。
numpy.einsum 算例
ij,ij->i 保留行号 i、合并特征 j。两对向量只生成两个内积,避免产生所有行对行的相似度矩阵。
import numpy as np
np.einsum('ij,ij->i',[[1,2],[3,4]],[[2,1],[0,2]])结果 [4, 8]