pytorch自实现线性回归和反向传播并画图

coding=utf-8

“”"
author:lei
function:
“”"

import torch
import matplotlib.pyplot as plt

learning_rate = 0.01

1、准备数据

y = 3x + 0.8

x = torch.rand((500, 1))
y_true = x*0.3 + 0.8

2、通过模型计算y_predict

w = torch.rand((1, 1), requires_grad=True)
b = torch.empty((1, 1), requires_grad=True)

4、通过循环,反向传播,更新参数

for i in range(5000):
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("w={}, b={}, loss={}".format(w.item(), b.item(), loss.item()))

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))
plt.show()

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值