我正在关注quant-econ教程。我正在尝试使用矢量化 numpy 方法实现经验累积概率函数的练习。
以下是问题的正确解决方案:
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__
并且它可以工作,而我的方法却出错了?