目录
假设我们的基础模型就是y = wx+b,其中w和b均为参数,我们使用y = 3x+0.8来构造数据x、y,所以最后通过模型应该能够得出w和b应该分别接近3和0.8
1.准备数据
2.计算预测值
3.计算损失,把参数的梯度置为0,进行反向传播
4.更新参数
import torch
import matplotlib.pyplot as plt
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
learning_rate = 0.01
# 1. 准备数据
x = torch.rand([500, 1])
y_true = 3 * x + 0.8
# 2. 设计模型
w = torch.rand([1, 1], requires_grad=True)
b = torch.tensor(1, requires_grad=True, dtype=torch.float32)
# 4. 反向传播
for i in range(6000):
y_predict = torch.matmul(x, w) + b
# 3. 计算 loss
loss = (y_true - y_predict).pow(2).mean()
if w.grad is not None:
w.grad.data.zero_()
if b.grad is not None:
b.grad.data.zero_()
loss.backward()
w.data = w.data - learning_rate * w.grad
b.data = b.data - learning_rate * b.grad
print(b.data, w.data)
plt.figure(figsize=(20, 8))
plt.scatter(x.numpy().reshape(-1), y_true.numpy().re

本文介绍了如何在PyTorch中实现线性回归,包括创建nn.Module子类、定义模型、使用优化器如SGD以及选择损失函数如MSELoss。通过一个简单的y=3x+0.8的数据集,展示了训练过程和模型评估。
最低0.47元/天 解锁文章
5万+

被折叠的 条评论
为什么被折叠?



