1. 实现线性回归
用基础模型 y = wx + b
步骤: 1. 准备数据
2. 计算预测值
3. 计算损失,把参数的梯度置为0,进行反向传播
4. 更新参数
import torch
import numpy as np
from matplotlib import pyplot as plt
learning_rate = 0.01
# 1. 准备数据 y = 3x + 0.8,准备参数
x = torch.rand([500,1]) # 返回50个服从均匀分布的初始化后的tenosr
y_true = 3*x + 0.8
# 2. 通过模型计算y_predict
w = torch.rand([1,1], requires_grad=True)
b = torch.tensor(0, requires_grad=True,dtype=torch.float32)
#4. 通过循环,反向传播,更新参数
for i in range(2000):
# 3. 计算loss
# torch.matmul() 是tensor的乘法
y_predict = torch.matmul(x, w) + b
# 损失值= (预测值-实际值的平方)的均值
loss = (y_true - y_predict).pow(2).mean()
# 判断w和b是否使用过,如果使用过则就地重置
if w.grad is not None:
w.grad.data.zero_()
if b.grad is not None:
b.grad.data.zero_()
# 反向传播 反向传播之后就可以获取到w.gr