假设我有两个具有相同批量维度(即相同行数)的二维张量。
import numpy as np
# Both t1 and t2 have shape (2, 3)
t1 = np.array([[1.0, 2.0, 3.0], [10.0, 11.0, 12.0]])
# array([[ 1., 2., 3.],
# [10., 11., 12.]])
t2 = np.array([[21.0, 22.0, 23.0], [30.0, 31.0, 32.0]])
# array([[21., 22., 23.],
# [30., 31., 32.]])
如何计算两个张量行之间的点积?具体来说,我想最终得到所需的 (2, 1) 张量结果:
desired_result = np.array([np.dot(t1[0], t2[0]), np.dot(t1[1], t2[1])])
# array([ 134., 1025.])
我已经尝试过:
np.dot(t1, t2)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "<__array_function__ internals>", line 5, in dot
# ValueError: shapes (2,3) and (2,3) not aligned: 3 (dim 1) != 2 (dim 0)
np.tensordot(t1, t2)
# array(1159.)
感谢您的帮助。
最佳答案
由于 t1
和 t2
都是二维数组,numpy.dot
会 matrix multiplication 。对于您的情况,您可以将两个数组按元素相乘,然后对行求和:
(t1 * t2).sum(axis=1)
# [ 134. 1025.]
关于python - 具有相同批量维度的两个矩阵行之间的点积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67171060/