如何向量化`__call__`方法

时间:2013-11-14 23:54:27

标签: python vector numpy

我正在关注quant-econ教程。我正在尝试使用矢量化numpy方法实现Empirical Cumulative Probability Funcion的练习。

以下是问题的正确解决方案:

class ecdf:

    def __init__(self, observations):
        self.observations = np.asarray(observations)

    def __call__(self, x): 
        return np.mean(self.observations <= x)

    def plot(self, a=None, b=None): 

        # === choose reasonable interval if [a, b] not specified === #
        if not a:
            a = self.observations.min() - self.observations.std()
        if not b:
            b = self.observations.max() + self.observations.std()

        # === generate plot === #
        x_vals = np.linspace(a, b, num=100)
        f = np.vectorize(self.__call__)
        plt.plot(x_vals, f(x_vals))
        plt.show()

但我尝试这样做:

class ecdf(object):

    def __init__(self, observations):
        self.observations = np.asarray(observations)
        self.__call__ = np.vectorize(self.__call__)

    def __call__(self, x):
        return np.mean(self.observations <= x)

这样,__call__方法被向量化,并且可以使用数组调用实例,并返回该数组的累积概率数组。但是,当我这样尝试时:

p = ecdf(uniform(0,1,500))
p([0.2, 0.3])

我收到此错误:

Traceback (most recent call last):

  File "<ipython-input-34-6a77f18aa54e>", line 1, in <module>
    p([0.2, 0.3])

  File "D:/Users/y_arabaci-ug/Desktop/quant-econ/programs/numpy_exercises.py", line 50, in __call__
    return np.mean(self.observations <= x)

ValueError: operands could not be broadcast together with shapes (500) (2)

我的问题是,为什么作者可以对self.__call__进行矢量化并且它有效,而我的方法会出错?

1 个答案:

答案 0 :(得分:1)

您不能这样做,因为__call__必须是类ecdf的属性,而不是实例。这是我的解决方案:

class ecdf(object):

    def __init__(self, observations):
        self.observations = np.asarray(observations)
        self._v_calc = np.vectorize(self._calc)

    def _calc(self, x):
        return np.mean(self.observations <= x)

    def __call__(self, x):
        return self._v_calc(x)