【Pytorch深度学习实战】(2)线性回归(Linear Regression)

🔎大家好,我是Sonhhxg_柒,希望你看完之后,能对你有所帮助,不足请指正!共同学习交流🔎

📝个人主页-Sonhhxg_柒的博客_CSDN博客 📃

🎁欢迎各位→点赞👍 + 收藏⭐️ + 留言📝​

📣系列专栏 - 机器学习【ML】 自然语言处理【NLP】  深度学习【DL】

 🖍foreword

✔说明⇢本人讲解主要包括Python、机器学习(ML)、深度学习(DL)、自然语言处理(NLP)等内容。

如果你对这个系列感兴趣的话,可以关注订阅哟👋

线性回归代码实现


 
 
  1. import torch
  2. import torch.nn as nn
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. # 超参数
  6. input_ size = 1
  7. output_ size = 1
  8. num_epochs = 60
  9. learning_rate = 0.001
  10. # 数据集
  11. x_train = np.array([[ 3.3], [ 4.4], [ 5.5], [ 6.71], [ 6.93], [ 4.168],
  12. [ 9.779], [ 6.182], [ 7.59], [ 2.167], [ 7.042],
  13. [ 10.791], [ 5.313], [ 7.997], [ 3.1]], dtype =np.float 32)
  14. y_train = np.array([[ 1.7], [ 2.76], [ 2.09], [ 3.19], [ 1.694], [ 1.573],
  15. [ 3.366], [ 2.596], [ 2.53], [ 1.221], [ 2.827],
  16. [ 3.465], [ 1.65], [ 2.904], [ 1.3]], dtype =np.float 32)
  17. # 线性回归模型
  18. model = nn.Linear( input_ size, output_ size)
  19. # 损失和优化器
  20. criterion = nn.MSELoss()
  21. optimizer = torch.optim.SGD(model.parameters(), lr =learning_rate)
  22. # 训练模型
  23. for epoch in range(num_epochs):
  24. # Convert numpy arrays to torch tensors
  25. inputs = torch. from_numpy(x_train)
  26. targets = torch. from_numpy(y_train)
  27. # 前向传播
  28. outputs = model(inputs)
  29. loss = criterion(outputs, targets)
  30. # 向后优化
  31. optimizer. zero_grad()
  32. loss.backward()
  33. optimizer.step()
  34. if (epoch + 1) % 5 = = 0:
  35. print ( 'Epoch [{}/{}], Loss: {:.4f}'. format(epoch + 1, num_epochs, loss.item()))
  36. # 绘制图形
  37. predicted = model(torch. from_numpy(x_train)).detach().numpy()
  38. plt.plot(x_train, y_train, 'ro', label = 'Original data')
  39. plt.plot(x_train, predicted, label = 'Fitted line')
  40. plt.legend()
  41. plt.show()
  42. # 保存模型
  43. torch.save(model.state_dict(), 'model.ckpt')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值