Numpy 一次只支持一项操作。话虽如此,有几种解决方法。
就地运营
最简单的解决方案是通过以下方式使用就地操作+=
and *=
import numpy as np
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)