python - 计算 numpy.ndarray 内部乘法的有效方法

标签 python performance numpy matrix multidimensional-array

我有两个形状相同的矩阵 a 和 b:

a = np.ndarray(shape=(3, 2), dtype=int)
b = np.ndarray(shape=(3, 2), dtype=int)

我想要它们的内部乘法,例如:

    1 2
a = 4 5
    7 8

    9 8
b = 6 5
    3 2

我希望结果是这个 1x2 ndarray:

[1x9+4x6+7x3   2x8+5x5+8x2]

这就像我们正在计算两个矩阵的列的标量点积。

我现在正在做的是:

np.diag(np.dot(np.transpose(a), b))

但它效率不高,而且它正在计算许多我不需要的其他东西。

我的矩阵比这些大得多,因此找到更有效的解决方案很重要。

最佳答案

您可以先进行简单的乘法,然后对 axis=0 求和:

>>> a = np.array([[1, 2], [4, 5], [7, 8]])
>>> b = np.array([[9, 8], [6, 5], [3, 2]])
>>> (a * b).sum(axis=0)
array([54, 57])

关于python - 计算 numpy.ndarray 内部乘法的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26293142/

相关文章:

python - 使用 asrtoolkit 的 wer 函数但需要帮助降低字符错误率

python - 斯坦福大学对 Python NLTK 的普遍依赖

python - Scikit-learn:覆盖分类器中的类方法

python - 根据元组将值插入像素

python - 从 Numpy 数组 : How do I specify the index column and column headers? 创建 Pandas DataFrame

python - 从零开始绘制 Y 条,而不是在列表中较小的值处

android - 多重通知--android

sql - 希望优化此查询

c++ - 使用 -O3 编译时将函数标记为内联?

python - 用于收集 numpy 数组的高效查找表