线性回归中出现错误:
TypeError Traceback (most recent call last)
<ipython-input-23-444c0fe3ed1c> in <module> 11 if __name__ == "__main__": 12 draw(x_train,y_train) ---> 13 w,b = fit(x_train,y_train) 14 print(w,b) 15 fit_line(w,b) TypeError: 报错的原因是函数返回值得数量不一致,查看函数返回值数量和调用函数时接收返回值的数量是不是一致,修改一致即可
错误源码如下:
def fit(x_train,y_train):
size = len(x_train)
numerator = 0
denominator = 0
for i in range(size):
numerator += (x_train[i] - np.mean(x_train))*(y_train[i] - np.mean(y_train))
denominator += (x_train[i] - np.mean(x_train))**2
w = numerator/denominator
b = np.mean(y_train) -w*np.mean(x_train)
。。。
if __name__ == "__main__":
draw(x_train,y_train)
w,b = fit(x_train,y_train)
print(w,b)
fit_line(w,b)
print(predict(15000,w,b))
解决方法:报错意思是函数返回值得数量不一致
修改代码:
def fit(x_train,y_train):
size = len(x_train)
numerator = 0
denominator = 0
for i in range(size):
numerator += (x_train[i] - np.mean(x_train))*(y_train[i] - np.mean(y_train))
denominator += (x_train[i] - np.mean(x_train))**2
w = numerator/denominator
b = np.mean(y_train) -w*np.mean(x_train)
##添加return返回即可解决
return w,b

