How to vectorize this python code to make it more efficient? (in speed)

I am trying to conduct vector code of my code using numpy modules, the source code is as follows:

m = [M[i,:9].dot(N[:9,i]) for i in xrange(9)]

and I improved the code as:

m = np.diagonal(M[:9,:9].dot(N[:9,:9]))  

but this will lead to some unnecessary calculations (especially when the index is much larger than 9). What can I do to improve efficiency?

Edit: Basically, I intend to do this to calculate the diagonal elements of the point product of two matrices M and N.

+4
source share
2 answers

np.einsum, M, N, / . , einsum, :

m = np.einsum('ij,ji->i',M[:,:9],N[:9,:])
+6

, , , :

  • , , . M N , M N ..

  • , N, M N T , . . :

    Nprime = np.transpose(N[:,:9])
    product = np.multiply(M[:9,:], Nprime)
    result = np.sum(product, axis=1)
    

    :

    result = (M[:,:9] * (N[:9,:].T)).sum(1)
    

( 3 9):

import numpy as np

>>> M = np.array(
    [[1, 2, 3],
     [6, 5, 4],
     [8, 7, 9]])

>>> N = np.array(
    [[0, 9, 7],
     [2, 4, 5],
     [6, 8, 1]])

>>> M.dot(N)
array([[22,  41,  20],
       [34, 106,  71],
       [68, 172, 100]])

>>> np.diagonal(M.dot(N))
array([22, 106, 100])
# ^ The reference answer

>>> Nprime = np.transpose(N)
array([[0, 2, 6],
       [9, 4, 8],
       [7, 5, 1]])

>>> product = np.multiply(M, Nprime)
array([[ 0,  4, 18],
       [54, 20, 32],
       [56, 35,  9]])

>>> result = np.sum(product, axis=1)
array([22, 106, 100])
+4

Source: https://habr.com/ru/post/1648189/


All Articles