Merge and add multiple times to avoid memory loss

Is it possible to multiply two ndarray A and B and add the result to C without creating a large intermediate array for A times B?

Numpy has a keyword parameter for the case C = A times B:

numpy.multiply(A, B, out=C)

What about the case C + = A times B?

+3
source share
2 answers

Numpy only supports operations one at a time. With that said, there are several workarounds.

Operations

The easiest solution is to use on-site operations with +=and*=

import numpy as np
import scipy

n = 100
b = 5.0

x = np.random.rand(n)
y = np.random.rand(n)

z = b * x
z += y

BLAS

BLAS . , , "AXPY",

y <- a * x + y

:

import scipy

axpy = scipy.linalg.blas.get_blas_funcs('axpy', arrays=(x, y))
axpy(x, y, n, b)

Numexpr

- , numexpr, :

import numexpr

z = numexpr.evaluate('b * x + y')

Theano

, theano. - :

import theano

x = theano.tensor.vector()         # declare variable
y = theano.tensor.vector()         # declare variable

out = b * x + y                    # build symbolic expression
f = theano.function([x, y], out)   # compile function

z = f(x, y)
+4

, NumPy , , , , , .

-1

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


All Articles