(Python)如何在不执行A * B的情况下获得对角线(A * B)? [英] (Python) How to get diagonal(A*B) without having to perform A*B?

查看:79
本文介绍了(Python)如何在不执行A * B的情况下获得对角线(A * B)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有两个矩阵AB,并且让矩阵CA*B(矩阵乘法不是元素方式的).我们希望仅获取C的对角线条目,可以通过np.diagonal(C)完成.但是,这会导致不必要的时间开销,因为即使我们只需要将A中每一行与具有相同"id"的B列(即第1行)相乘,我们就将A与B相乘. A的第1列为BA的第2列为B的第2列,依此类推:构成C的对角线的乘法.有没有办法使用Numpy有效地实现这一目标?我想避免使用循环来控制哪一行乘以哪一列,而是希望使用内置的numpy方法来执行这种操作以优化性能.

Let's say we have two matrices A and B and let matrix C be A*B (matrix multiplication not element-wise). We wish to get only the diagonal entries of C, which can be done via np.diagonal(C). However, this causes unnecessary time overhead, because we are multiplying A with B even though we only need the the multiplications of each row in A with the column of B that has the same 'id', that is row 1 of A with column 1 of B, row 2 of A with column 2 of B and so on: the multiplications that form the diagonal of C. Is there a way to efficiently achieve that using Numpy? I want to avoid using loops to control which row is multiplied with which column, instead, I wish for a built-in numpy method that does this kind of operation to optimize performance.

先谢谢了.

推荐答案

我可能在这里使用einsum:

>>> a = np.random.randint(0, 10, (3,3))
>>> b = np.random.randint(0, 10, (3,3))
>>> a
array([[9, 2, 8],
       [5, 4, 0],
       [8, 0, 6]])
>>> b
array([[5, 5, 0],
       [3, 5, 5],
       [9, 4, 3]])
>>> a.dot(b)
array([[123,  87,  34],
       [ 37,  45,  20],
       [ 94,  64,  18]])
>>> np.diagonal(a.dot(b))
array([123,  45,  18])
>>> np.einsum('ij,ji->i', a,b)
array([123,  45,  18])

对于较大的数组,它比直接进行乘法要快得多:

For larger arrays, it'll be much faster than doing the multiplication directly:

>>> a = np.random.randint(0, 10, (1000,1000))
>>> b = np.random.randint(0, 10, (1000,1000))
>>> %timeit np.diagonal(a.dot(b))
1 loops, best of 3: 7.04 s per loop
>>> %timeit np.einsum('ij,ji->i', a, b)
100 loops, best of 3: 7.49 ms per loop

[注意:起初我是做元素级版本ii,ii->i,而不是矩阵乘法.相同的einsum技巧起作用.]

[Note: originally I'd done the elementwise version, ii,ii->i, instead of matrix multiplication. The same einsum tricks work.]

这篇关于(Python)如何在不执行A * B的情况下获得对角线(A * B)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆