【问题标题】:How to calculate the outer product of two matrices A and B per rows faster in python (numpy)?如何在python(numpy)中更快地计算每行两个矩阵A和B的外积?
【发布时间】:2017-03-29 11:36:07
【问题描述】:

假设我们有两个矩阵 A 和 B。

A 的形状为 (r, k),B 的形状为 (r, l)。

现在我想计算这两个矩阵每行的 np.outer 乘积。在外积之后,我想对轴 0 中的所有值求和。所以我的结果矩阵应该具有 (k, l) 的形状。

例如: A的形式是(4, 2),B的形式是(4, 3)。

import numpy as np

A = np.array([[0, 7], [4, 1], [0, 2], [0, 5]])
B = np.array([[9, 7, 7], [6, 7, 5], [2, 7, 9], [6, 9, 7]])

# This is the first outer product for the first values of A and B
print(np.outer(A[0], B[0])) # This will give me 

# First possibility is to use list comprehension and then
sum1 = np.sum((np.outer(x, y) for x, y in zip(A, B)), axis=0)

# Second possibility would be to use the reduce function
sum2 = reduce(lambda sum, (x, y): sum+np.outer(x, y), zip(A, B), np.zeros((A.shape[1], B.shape[1])))

# result for sum1 or sum2 looks like this:
# array([[ 175.,  156.,  133.], [ 133.,  131.,  137.]])

我在问自己,有没有更好或更快的解决方案?因为当我有例如两个超过 10.000 行的矩阵,这需要一些时间。

仅使用 np.outer 函数不是解决方案,因为 np.outer(A, B) 会给我一个形状为 (8, 12) 的矩阵(这不是我想要的)。

神经网络反向传播需要这个。

【问题讨论】:

    标签: python-2.7 numpy matrix


    【解决方案1】:

    您可以将迭代器作为字符串表示法直接传输到np.einsum -

    np.einsum('rk,rl->kl',A,B)
    

    或使用np.dot 进行矩阵乘法 -

    A.T.dot(B)
    

    【讨论】:

      猜你喜欢
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 2012-02-07
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多