线性回归
训练模型
建立自变量为w和b的损失函数来刻画模型的结果与真实结果之间的距离
训练线性回归模型实际上是要找到参数w和b使得loss尽可能小(但不是越小越好,过小可能会造成过拟合问题)。
在数学领域,可以使用求极小值或最小值的方法来得到使得loss尽可能小的w和b
在机器学习中,使用梯度下降的方法来寻找使得loss尽可能小的w和b
梯度下降
代码:
import numpy as np
import matplotlib.pyplot as plt
#使用梯度下降的方法拟合线性模型(寻找w和b)
x_data=np.array([338.,333.,328.,207.,226.,25.,179.,60.,208.,606.])
y_data=np.array([640.,633.,619.,393.,428.,27.,193.,66.,226.,1591.])
#Model : ydata = b + w * xdata
#initial b and w
b=-120
w=-4
#learning rate(Adagra)
lr=1
lr_b=0
lr_w=0
iteration=100000
b_history=[b]
w_history=[w]
#Iterations
for i in range(iteration):
b_grad=np.sum(-2.0*(y_data-b-w*x_data)*1.0)
print(i,b_grad)
w_grad=np.sum(-2.0*(y_data-b-w*x_data)*x_data)
lr_b = lr_b + b_grad ** 2
lr_w = lr_w + w_grad ** 2
#update parameters
b=b-lr/np.sqrt(lr_b)*b_grad
# print('b',b)
w=w-lr/np.sqrt(lr_w)*w_grad
# print('w',w)
#store parameters for plotting
b_history.append(b)
w_history.append(w)
print(b_history)
#plot the figure
# plt.contourf(x,y,Z,)