代码:
# -*- coding: utf-8 -*-
# @Time : 2023-07-14 14:57
# @Author : yuer
# @FileName: exercise05.py
# @Software: PyCharm
import matplotlib.pyplot as plt
import torch
# x,y是3行1列的矩阵,所以在[]中要分为3个[]
x_data = torch.tensor([[1.0], [2.0], [3.0]])
y_data = torch.tensor([[2.0], [4.0], [6.0]])
class LinearModel(torch.nn.Module):
def __init__(self):
super(LinearModel, self).__init__()
self.linear = torch.nn.Linear(1, 1)
# 1,1分别代表x,y的维度(列数)
def forward(self, x):
y_pred = self.linear(x)
return y_pred
model = LinearModel()
criterion = torch.nn.MSELoss(True) # 计算loss
optimizer = torch.optim.Rprop(model.parameters(), lr=0.01) # 计算最优w,b
epoch_list = []
loss_list = []
for epoch in range(100):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
print(epoch, loss.item())
epoch_list.append(epoch)
loss_list.append(loss.item())
optimizer.zero_grad() # 清空梯度
loss.backward() # 反馈算梯度并更新
optimizer.step() # 更新w,b的值
print('w=', model.linear.weight.item())
print('b=', model.linear.bias.item())
x_test = torch.tensor([[4.0]])
y_test = model(x_test)
print('y_pred=', y_test)
plt.plot(epoch_list, loss_list)
plt.show()