引入random函数来实现随机取值进行梯度作业
x_data = [1.0,2.0,3.0]
y_data = [2.0,4.0,6.0]
w = 1
def forward(x):
return x*w
def loss(xs,ys):
y_pred = forward(xs)
loss = (y_pred-ys)**2
return loss
def gradient(xs,ys):
y_pred = forward(xs)
return 2*xs*(y_pred-ys)
epoch_list = []
loss_list = []
for epoch in range(100):
rand = random.randint(0,2)
loss_val = loss(x_data[rand],y_data[rand])
grad_val = gradient(x_data[rand],y_data[rand])
w = w-0.01*grad_val
print('epoch=',epoch,'w=',w,'loss=',loss_val)
epoch_list.append(epoch)
loss_list.append(loss_val)
plt.plot(epoch_list,loss_list)
plt.xlabel('epoch')
plt.ylabel('loss')
plt.show()
最后的收敛图像如上图所示