zoukankan      html  css  js  c++  java
  • Pytorch:通过pytorch实现线性回归

    线性回归

    Linear Regression

    线性回归是分析一个变量与另外一个(多个)变量之间关系的方法

    因变量:y     自变量:x     关系:线性  y=wx+b       分析:求解w,b

    求解步骤:

    1. 确定模型

    2. 选择损失函数

    3.求解梯度并更新w,b

    此题:

    1. model:y=wx+b

    2. MSE: 

    3.  w = w - LR*w.grad

         b = b - LR*w.grad

    下为代码实现

    import torch
    import matplotlib.pyplot as plt
    torch.manual_seed(10)
    
    lr = 0.05  # 学习率 
    
    # 创建训练数据
    x = torch.rand(20, 1) * 10  # x data (tensor), shape=(20, 1)
    y = 2*x + (5 + torch.randn(20, 1))  # y data (tensor), shape=(20, 1)
    
    # 构建线性回归参数
    w = torch.randn((1), requires_grad=True)
    b = torch.zeros((1), requires_grad=True)
    
    for iteration in range(1000):
    
        # 前向传播
        wx = torch.mul(w, x)
        y_pred = torch.add(wx, b)
    
        # 计算 MSE loss
        loss = (0.5 * (y - y_pred) ** 2).mean()
    
        # 反向传播
        loss.backward()
    
        # 更新参数
        b.data.sub_(lr * b.grad)
        w.data.sub_(lr * w.grad)
    
        # 清零张量的梯度   
        w.grad.zero_()
        b.grad.zero_()
    
        # 绘图
        if iteration % 20 == 0:
    
            plt.scatter(x.data.numpy(), y.data.numpy())
            plt.plot(x.data.numpy(), y_pred.data.numpy(), 'r-', lw=5)
            plt.text(2, 20, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color':  'red'})
            plt.xlim(1.5, 10)
            plt.ylim(8, 28)
            plt.title("Iteration: {}
    w: {} b: {}".format(iteration, w.data.numpy(), b.data.numpy()))
            plt.pause(0.5)
    
            if loss.data.numpy() < 1:
                break

    可以看到,最终损失函数停留在0.9左右的地方,对曲线比较拟合

  • 相关阅读:
    玩转持续化集成之Jenkins
    常用的免费移动应用测试框架推荐
    没有学过功夫能否练神功
    Android APP性能测试(下)
    Android APP性能测试(上)
    python-mongodb简单封装
    python使用协程完成批量模拟支付
    python多进程完成模拟支付
    python多线程完成模拟支付请求
    python-自动登录禅道
  • 原文地址:https://www.cnblogs.com/SakuraYuki/p/13341449.html
Copyright © 2011-2022 走看看