import matplotlib.pyplot as plt
import torch
##y = w1 * x^2 + w2 * x + b
#1. 数据导入,参数初值选取
x_data= [1.0,2.0,3.0]
y_data= [2.0,4.0,6.0]
w1= torch.Tensor([1.0]); w2= torch.Tensor([1.0]); b= torch.Tensor([1.0]);
#w1,w2,b=torch.Tensor([[1.0],[1.0],[1.0]])
w1.requires_grad = True; w2.requires_grad = True; b.requires_grad = True
#2. 定义函数
def forward(x):
return w1 * x * x + w2 * x + b
def loss(x,y):
y_pred = forward(x)
return (y_pred - y)**2
print('predict (before training)', 4, forward(4).item())
#3. 训练参数
epoch_list = []
loss_list = []
for epoch in range(15000):
All_Loss=0
for x, y in zip(x_data, y_data):
l= loss(x,y)
print('\t\tl:',l,'w1:',w1)
All_Loss+=l.item()
l.backward()
print('\t\tx, y:', x, y, 'w1_grad:',w1.grad.item(),'w2_grad:',w2.grad.item(),'b_grad:',b.grad.item(),)
w1.data = w1.data - 0.01 * w1.grad.data
w2.data = w2.data - 0.01 * w2.grad.data
b.data = b.data - 0.01 * b.grad.data
print('\t\tw1,w2,b:',w1.data.item(),w2.data.item(),b.data.item())
print('\t\t\tloss:',l.item())
w1.grad.data.zero_(); w2.grad.data.zero_(); b.grad.data.zero_();
print('\tprogress:', epoch, 'loss:',All_Loss)
epoch_list.append(epoch)
loss_list.append(All_Loss)
print()
print('predict (after training)','x, y:', 4, forward(4).item())
print('pred_Func:','y=',w1.data.item(),'x^2+',w2.data.item(),'x+',b.data.item())
#4. 绘图
#解决中文显示问题,不过最后标题还是没用中文,先码住
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.title(epoch_list[-1])
plt.plot(epoch_list[8000:], loss_list[8000:])
plt.ylabel('Loss')
plt.xlabel('epoch')
plt.show()
第五轮训练后,损失率明显下降很多。
为使观察更为直观,只选取训练一定次数后的数据绘制Loss-epoch图像。
progress: 14999
loss: 3.881723387166858e-09predict (after training) x, y: 4,8.0001220703125
pred_Func: y= 5.369417340261862e-05 x^2+ 1.9997600317001343 x+ 0.00022250268375501037
for x, y in zip(x_data, y_data):
print('\tw.data.item:',w.data.item())
l= loss(x,y)
l.backward()