NumPy adds output from np.dot or np.multiply to an existing array

You NumPycan specify an argument np.dotand np.multiply, called outso that they do not create a new array when returning the result. However, in my use case, I need to calculate the following:

  • c = c + np.dot(a, b) # where a and b are matrices of shape n x m, and m x p
  • c = c + np.multiply(a, b) # where a and b are matrices of equal shape n x m

Is there a way to do this without creating a new array every time? For example, something like this:

  • np.dot(a, b, add_to=c)
  • np.multiply(a, b, add_to=c)
+4
source share
1 answer

It seems like the perfect setup for using blas supported wrappers scipy.linalg.blasthat support matrix multipliers stacked in an existing array.

, dot sgemm (single-precision)/dgemm (double-precision), :

from scipy.linalg.blas import dgemm, sgemm

dgemm(alpha=1.0, a=a, b=b, c=c, beta=1.0)

C = alpha*(a x b) + beta*C.

*:

x:

-

1) :

In [549]: a = np.random.randint(0,9,(3,4))
     ...: b = np.random.randint(0,9,(4,5))
     ...: c = np.random.randint(0,9,(3,5))
     ...: 

In [550]: c
Out[550]: 
array([[2, 4, 7, 6, 1],
       [8, 7, 2, 1, 7],
       [4, 3, 5, 4, 4]])

2) :

In [551]: c_copy1 = c.copy()

3) np.dot :

In [552]: c = c + np.dot(a, b)

In [553]: c
Out[553]: 
array([[88, 94, 75, 66, 93],
       [55, 51, 55, 38, 65],
       [61, 51, 25, 45, 68]])

3) dgemm -

In [554]: dgemm(alpha=1.0, a=a, b=b, c=c_copy1, beta=1.0)
Out[554]: 
array([[ 88.,  94.,  75.,  66.,  93.],
       [ 55.,  51.,  55.,  38.,  65.],
       [ 61.,  51.,  25.,  45.,  68.]])

, , .


saxpy/daxpy . this other post.

+4

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


All Articles