python - 具有相同批量维度的两个矩阵行之间的点积

标签 python numpy

假设我有两个具有相同批量维度(即相同行数)的二维张量。

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.)

感谢您的帮助。

最佳答案

由于 t1t2 都是二维数组,numpy.dotmatrix multiplication 。对于您的情况,您可以将两个数组按元素相乘,然后对行求和:

(t1 * t2).sum(axis=1)
# [ 134. 1025.]

关于python - 具有相同批量维度的两个矩阵行之间的点积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67171060/

相关文章:

python - 从 pandas DataFrame 创建差异矩阵

python - 创建 numpy 二维索引数组的最快方法

python - 如何将 Chart.js 集成到 Django 中?

python - 更改 SSL 协议(protocol) Torndao 2.3/Python 2.6

python - 在Python中的同一个图上绘制数组列表?

python - Numpy 3d 数组删除每行的第一个条目

python - Numpy:创建 block 矩阵的函数

python - 如何在 matplotlib mplot3D 或类似文件中显示 3D 数组等值面的 3D 图?

python - 将两个窗口结果放入具有两个选项卡的窗口中

python - Numpy:从 3D 数组中减去 Numpy argmin