当前位置:   article > 正文

pytorch实现线性回归_用pytorch实现线性回归

用pytorch实现线性回归

转大佬笔记

 

代码:

  1. # -*- coding: utf-8 -*-
  2. # @Time : 2023-07-14 14:57
  3. # @Author : yuer
  4. # @FileName: exercise05.py
  5. # @Software: PyCharm
  6. import matplotlib.pyplot as plt
  7. import torch
  8. # x,y是3行1列的矩阵,所以在[]中要分为3个[]
  9. x_data = torch.tensor([[1.0], [2.0], [3.0]])
  10. y_data = torch.tensor([[2.0], [4.0], [6.0]])
  11. class LinearModel(torch.nn.Module):
  12. def __init__(self):
  13. super(LinearModel, self).__init__()
  14. self.linear = torch.nn.Linear(1, 1)
  15. # 1,1分别代表x,y的维度(列数)
  16. def forward(self, x):
  17. y_pred = self.linear(x)
  18. return y_pred
  19. model = LinearModel()
  20. criterion = torch.nn.MSELoss(True) # 计算loss
  21. optimizer = torch.optim.Rprop(model.parameters(), lr=0.01) # 计算最优w,b
  22. epoch_list = []
  23. loss_list = []
  24. for epoch in range(100):
  25. y_pred = model(x_data)
  26. loss = criterion(y_pred, y_data)
  27. print(epoch, loss.item())
  28. epoch_list.append(epoch)
  29. loss_list.append(loss.item())
  30. optimizer.zero_grad() # 清空梯度
  31. loss.backward() # 反馈算梯度并更新
  32. optimizer.step() # 更新w,b的值
  33. print('w=', model.linear.weight.item())
  34. print('b=', model.linear.bias.item())
  35. x_test = torch.tensor([[4.0]])
  36. y_test = model(x_test)
  37. print('y_pred=', y_test)
  38. plt.plot(epoch_list, loss_list)
  39. plt.show()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/103716?site
推荐阅读
相关标签
  

闽ICP备14008679号