我完全卡住了。以为我已经理解了课程,猜测我错了:/无论如何,我的代码看起来像这样:
class LinearRegression:
def __init__(self, x, y, full = 0):
self.full = full
self.x = x
self.y = y
def __call__(self):
squared_sum_x = (sum(self.x))**2
n = len(self.x)
xx = sum([item**2 for item in self.x])
xy = sum([xi*yi for xi, yi in zip(self.x,self.y)])
a = 1.0*((n*xy -(sum(self.y)*sum(self.x)))/(n*xx - squared_sum_x))
b = (sum(self.y) - a*sum(self.x))/n
if self.full == 0:
return (a,b)
elif self.full == 1:
squared_sum_y = (sum(self.y))**2
yy = sum([item**2 for item in self.y])
R = float((n*xy -(sum(self.y)*sum(self.x)))/(((n*xx - squared_sum_x)*(n*yy - squared_sum_y))**0.5))
S_a = (1/(n-2))*((yy-(a*xy)-(b*sum(self.y)))/(xx-(n*xx)))
S_b = S_a * (n*xx)
return (a, b, R, S_a, S_b)
else:
return "full parameter must be 0, 1 or empty"
lr = LinearRegression(range(10),range(10,30,2),0)
lr()
我收到了以下错误:
AttributeError: LinearRegression instance has no __call__ method
问题是:为什么?因为我花了几个小时分析这段代码,完全不知道错误是什么......
答案 0 :(得分:2)
我认为问题出在你的缩进中。你实际上并没有在你的班级中包含这些方法,因为你的缩进是将它们放在"外面"。试试这个:
class LinearRegression:
def __init__(self, x, y, full = 0):
self.full = full
self.x = x
self.y = y
def __call__(self):
squared_sum_x = (sum(self.x))**2
n = len(self.x)
xx = sum([item**2 for item in self.x])
xy = sum([xi*yi for xi, yi in zip(self.x,self.y)])
a = 1.0*((n*xy -(sum(self.y)*sum(self.x)))/(n*xx - squared_sum_x))
b = (sum(self.y) - a*sum(self.x))/n
if self.full == 0:
return (a,b)
elif self.full == 1:
squared_sum_y = (sum(self.y))**2
yy = sum([item**2 for item in self.y])
R = float((n*xy -(sum(self.y)*sum(self.x)))/(((n*xx - squared_sum_x)*(n*yy - squared_sum_y))**0.5))
S_a = (1/(n-2))*((yy-(a*xy)-(b*sum(self.y)))/(xx-(n*xx)))
S_b = S_a * (n*xx)
return (a, b, R, S_a, S_b)
else:
return "full parameter must be 0, 1 or empty"
这种方法将是"内部"你的班级,而不是独立定义的职能。