【问题标题】:How do I call a list of numpy functions without a for loop?如何在没有 for 循环的情况下调用 numpy 函数列表?
【发布时间】:2019-10-10 13:34:51
【问题描述】:

我正在进行数据分析,其中涉及最小化一组点和一组相应的正交函数之间的最小二乘误差。换句话说,我正在获取一组 y 值和一组函数,并尝试将 x 值归零,以使所有函数最接近其对应的 y 值。一切都在“data_set”类中完成。我要比较的函数都存储在一个列表中,并且我使用类方法来计算所有函数的总 lsq-error:

self.fits = [np.poly1d(np.polyfit(self.x_data, self.y_data[n],10)) for n in range(self.num_points)]

def error(self, x, y_set):
    arr = [(y_set[n] - self.fits[n](x))**2 for n in range(self.num_points)]
    return np.sum(arr)

当我的时间比数据多得多时,这很好,但现在我正在获取数千个 x 值,每个都有一千个 y 值,而 for 循环的速度慢得令人无法接受。我一直在尝试使用np.vectorize:

#global scope
def func(f,x):
    return f(x)
vfunc = np.vectorize(func, excluded=['x'])
…
…
#within data_set class
    def error(self, x, y_set):
        arr = (y_set - vfunc(self.fits, x))**2
        return np.sum(arr)

只要n 有效,func(self.fits[n], x) 就可以正常工作,据我所知,docsvfunc(self.fits, x) 应该相当于

[self.fits[n](x) for n in range(self.num_points)]

但它会抛出:

ValueError: cannot copy sequence with size 10 to array axis with dimension 11

10 是多项式拟合的次数,11 是(根据定义)其中的项数,但我不知道它们为什么会出现在这里。如果我更改配合顺序,错误消息会反映更改。似乎np.vectorizeself.fits 的每个元素作为一个列表而不是np.poly1d 函数。

无论如何,如果有人可以帮助我更好地理解np.vectorize,或者提出另一种消除该循环的方法,那就太好了。

【问题讨论】:

  • np.vectorize 不会让事情变得更快。如果我记得早期的 SO,它的 excluded=['x'] 仅在 x 是关键字参数时才有效。所以它不仅比普通迭代慢,而且更难正确使用。仅当您针对另一个输入参数广播一个输入参数时,它才有用。

标签: python-3.x numpy vectorization


【解决方案1】:

由于所讨论的函数都具有非常相似的结构,一旦我们提取了 poly 系数,我们就可以“手动”进行矢量化。其实这个函数就是一个很简单的单行函数,下面eval_many

import numpy as np

def poly_vec(list_of_polys):
    O = max(p.order for p in list_of_polys)+1
    C = np.zeros((len(list_of_polys), O))
    for p, c in zip(list_of_polys, C):
        c[len(c)-p.order-1:] = p.coeffs
    return C

def eval_many(x,C):
    return C@np.vander(x,11).T

# make example
list_of_polys = [np.poly1d(v) for v in np.random.random((1000,11))]
x = np.random.random((2000,))

# put all coeffs in one master matrix
C = poly_vec(list_of_polys)

# test
assert np.allclose(eval_many(x,C), [p(x) for p in list_of_polys])

from timeit import timeit

print('vectorized', timeit(lambda: eval_many(x,C), number=100)*10)
print('loopy     ', timeit(lambda: [p(x) for p in list_of_polys], number=10)*100)

示例运行:

vectorized 6.817315469961613
loopy      56.35076989419758

【讨论】:

    猜你喜欢
    • 2021-01-29
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    相关资源
    最近更新 更多