python计算a中各元素与b逐项乘积的累加和,如何在python(numpy)中更快地计算每行两个矩阵A和B的外积?...

Let say we have two matrices A and B.

A has the shape (r, k) and B has the shape (r, l).

Now I want to calculate the np.outer product of these two matrices per rows. After the outer product I then want to sum all values in axis 0. So my result matrix should have the shape (k, l).

E.g.:

Form of A is (4, 2), of B is (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.]])

I'm asking my self, is there a better or faster solution? Because when I have e.g. two matrices with more than 10.000 rows this takes some time.

Only using the np.outer function is not the solution, because np.outer(A, B) will give me a matrix with shape (8, 12) (this is not what I want).

Need this for neural networks backpropagation.

解决方案

You could literally transfer the iterators as string notation to np.einsum -

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

Or with matrix-multiplication using np.dot -

A.T.dot(B)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值