一元线性回归模型很简单
y1=ax+b+ε,y1为实际值,ε为正态的误差。
y2=ax+b,y2为预测值。
ε=y1-y2。
def model(a,b,x):
x is vector,a and b are the common number.
return a*x+b
这里将整组数据的预测结果方差作为损失函数。
J(a,b)=sum((y1-y2)^2)/n
def cost(a,b,x,y):
# x is argu, y is actual result.
n=len(x)
return np.square(y-ax-b).sum()/n
优化函数则进行使损失函数,即方差最小的方向进行搜索
a=a-theta(∂J/∂a)
b=b-theta*(∂J/∂b)
这里的解释就是,江苏小学五年级辅导对影响因素a或b求损失函数J的偏导,如果损失函数随着a或b增大而增大,我们就需要反方向搜索,使得损失函数变小。
对于偏导的求取则看的别人的推导公式
theta为搜索步长,影响速度和精度(我猜的,实际没有验证)
def optimize(a,b,x,y):
theta = 1e-1 # settle the step as 0.1
n=len(x)
y_hat = model(a,b,x)
# compute forecast values