pytorch完成线性回归
基础模型是y = wx+b 其中w和b均为参数,使用 y = 3x + 0.8 来构造数据x,y 最后通过模型应该能得出w和b 的值接近3和0.8
import torch
import matplotlib.pyplot as plt
from numpy import *
learning_rate = 0.01
# 1.准备数据
# y = 3x + 0.8 只有一个x是一维
# 基础模型是y = wx+b 其中w b均为参数,使用 y = 3x + 0.8 来构造数据x,y 最后通过模型应该能得出w b 的值接近3 0.8
# 构造一个500行 1列的数据 rand() 0-1
x = torch.rand([500,1])
y_true = x*3 + 0.8 # x 与 y 都是 500行 1列
# 2.通过模型计算y_predict
# requires_grad=True表示会记录该tensor的计算过程,默认是False
w = torch.rand([1,1],requires_grad=True) # [1,1]是因为x[500,1]与[1,1]相乘是[500,1]
b = torch.tensor(0,requires_grad=True,dtype=torch.float32) # b全为0
# 4.通过循环,反向传播,更新参数
for i in range(2000):
# 3.计算损失值
y_predict = torch.matmul(x, w) + b # matmul()矩阵乘法
loss = (y_true - y_predict).pow(2).mean()
# 先判断w是不是一个数 即不为None
if w.grad is not None :
# 是一个数
w.data.zero_() # 将w _ 就地修改为0 归零操作 每次反向传播前将梯度置0
if b.grad is not None:
b.data.zero_()
loss.backward() # 反向传播
w.data = w.data - learning_rate * w.grad
b.data = b.data - learning_rate * b.grad
if i % 50 == 0 :
print("w,b,loss",w.item(),b.item(),loss.item()) # 通过item获得w和b的值
# 设置大小
plt.figure(figsize=(20,8))
# 散点图
plt.scatter(x.numpy().reshape(-1),y_true.numpy().reshape(-1))
# 直线
y_predict = torch.matmul(x, w) + b
plt.plot(x.numpy().reshape(-1),y_predict.detach().numpy().reshape(-1),c = 'r')
plt.show()

