最近在学深度学习的知识,先写一些比较简单的模型,这是我写的第一个利用梯度下降求线性拟合的模型
数学表达式:
\begin{equation}
Y=w*x \text{,}
\end{equation}
import matplotlib.pyplot as plt
x_data=[1.0,2.0,3.0]
y_data=[2.0,4.0,6.0]
w=1.0
loss_list=[]
epoch_list=[]
w_list=[]
def predict(x):
return w*x
def loss(x,y):
l=0.0
for xs,ys in zip(x,y):
l+=(predict(xs)-ys)**2
l/=len(x)
return l
def gradient(x, y):
grad=0.0
for xs,ys in zip(x_data,y_data):
grad+=2 * (w * xs - ys) * xs
grad/=len(x)
return grad
for epoch in range(50):
l_loss=loss(x_data,y_data)
w=w-0.01*gradient(x_data,y_data)
epoch_list.append(epoch)
loss_list.append(l_loss)
w_list.append(w)
print(w_list)
plt.plot(epoch_list,loss_list)
plt.plot(epoch_list,w_list)
plt.title("The first model of Yu Zhang!")
plt.xlabel("epoch")
plt.ylabel("loss")
plt.show()
运行结果展示: