执行线性回归以找到估计系数并为其绘制回归线,这给我带来了错误...无法对柔韧性类型执行归约。代码中有什么问题.... var应该在哪里定义!
import numpy as np
import matplotlib.pyplot as plt
x="GarageArea"
y="SalePrice"
def estimate_coef(x, y):
n = np.size(x)
m_x, m_y = np.mean(x), np.mean(y)
SS_xy = np.sum(y*x) - n*m_y*m_x
SS_xx = np.sum(x*x) - n*m_x*m_x
b_1 = SS_xy / SS_xx
b_0 = m_y - b_1*m_x
return(GarageArea)
def plot_regression_line(x, y, b):
plt.scatter(x, y, color = "m", marker = "o", s = 30)
y_pred = b[0] + b[1]*x
plt.plot(x, y_pred, color = "g")
plt.xlabel('x')
plt.ylabel('y')
plt.show()
# Visualize your results
b=estimate_coef(x,y)
plot_regression_line(GarageArea,GarageArea,b)
您尚未在代码中定义x
或y
,但尝试将它们传递给plot_regression_line
。不知道您是否假设当您将GarageArea
和SalePrice
传递给estimate_coef
函数时,该函数将它们本地映射到x
,y
,您以为您仍可以引用它们。但是,x
函数中的y
和estimate_coef
在该函数中是局部作用域,因此在其外部不存在,因此无法对其进行引用。
假设您打算将GarageArea
和SalePrice
的x
和y
传递给plot_regression_line
函数。
import numpy as np
import matplotlib.pyplot as plt
def estimate_coef(x, y):
n = np.size(x)
m_x, m_y = np.mean(x), np.mean(y)
SS_xy = np.sum(y*x) - n*m_y*m_x
SS_xx = np.sum(x*x) - n*m_x*m_x
b_1 = SS_xy / SS_xx
b_0 = m_y - b_1*m_x
return(b_0, b_1)
def plot_regression_line(x, y, b):
plt.scatter(x, y, color = "m", marker = "o", s = 30)
y_pred = b[0] + b[1]*x
plt.plot(x, y_pred, color = "g")
plt.xlabel('x')
plt.ylabel('y')
plt.show()
# Visualize your results
b=estimate_coef(GarageArea,SalePrice)
plot_regression_line(GarageArea,GarageArea,b)
这是假设您在代码中定义了x
和y
,但我可能是错的,因为您还使用了您发布的代码中未定义的GarageArea
和SalePrice
。如果这不能回答您的问题,那么您应该编辑问题并发布所得到的错误的堆栈跟踪。