【发布时间】:2017-05-04 12:57:36
【问题描述】:
我有一个向量 并希望制作另一个相同长度的向量,其第 k 个分量是
问题是:我们如何将其矢量化以提高速度? NumPy vectorize() 实际上是一个for循环,所以不算。
维德拉克指出“There is no way to apply a pure Python function to every element of a NumPy array without calling it that many times”。由于我使用的是 NumPy 函数而不是“纯 Python”函数,因此我认为可以进行矢量化,但我不知道如何。
import numpy as np
from scipy.integrate import quad
ws = 2 * np.random.random(10) - 1
n = len(ws)
integrals = np.empty(n)
def f(x, w):
if w < 0: return np.abs(x * w)
else: return np.exp(x) * w
def temp(x): return np.array([f(x, w) for w in ws]).sum()
def integrand(x, w): return f(x, w) * np.log(temp(x))
## Python for loop
for k in range(n):
integrals[k] = quad(integrand, -1, 1, args = ws[k])[0]
## NumPy vectorize
integrals = np.vectorize(quad)(integrand, -1, 1, args = ws)[0]
顺便说一句,Cython for 循环是否总是比 NumPy 向量化更快?
【问题讨论】:
-
另一种可能的加速,你没有要求,但是,值得一提的是与 openmp 的并行化。
-
@Dschoni 是的。 f(x, w) 在我的代码中定义。
-
不,我的意思是 F(x,w) 如 F'=f
-
只是问一下,因为如果您不必在数值上而是在分析上进行整合,那么事情会更快。
标签: numpy vectorization quad