• 《深度学习框架PyTorch入门与实践》示例——用Variable实现线性回归


    《深度学习框架PyTorch入门与实践》第三章的一个示例,利用Variable实现线性回归。我将原书代码在pycharm中重写时有些运行错误,解决问题后可以运行。在代码中注释了解决方法。

    python代码如下:

    """第三章 Tensor和autograd"""
    import torch as t
    from torch.autograd import Variable as V
    from matplotlib import pyplot as plt
    from IPython import display
    
    t.manual_seed(1000)
    
    
    def get_fake_data(batch_size = 8):
        """产生随机数据:y=2*x+3"""
        x = t.rand(batch_size, 1) * 20
        y = x * 2 + (1 + t.randn(batch_size, 1)) * 3
        return x, y
    
    
    # 随机初始化参数
    w = V(t.rand(1, 1), requires_grad=True)
    b = V(t.zeros(1, 1), requires_grad=True)
    
    lr = 0.001
    
    for ii in range(8000):
        x, y = get_fake_data()
        x, y = V(x), V(y)
    
        # foward
        y_pred = x.mm(w) + b.expand_as(x)      # 把一个tensor变成和函数括号内一样形状的tensor,用法与expand()类似
        loss = 0.5 * (y_pred - y) ** 2
        loss = loss.sum()
    
        # backward
        loss.backward()
    
        # 更新参数
        w.data.sub_(lr * w.grad.data)         # 没找到sun_()功能介绍,推测相当于 -= 括号内的数值
        b.data.sub_(lr * b.grad.data)
    
        # 梯度清零
        w.grad.data.zero_()
        b.grad.data.zero_()
    
        if ii % 1000 == 0:
            # 画图
            display.clear_output(wait=True)
            x = t.arange(0, 20).float().view(-1, 1)             # 加上.float()转换数据格式,否则报错
            y = x.mm(w.data) + b.data.expand_as(x)
            plt.plot(x.numpy(), y.numpy())                      # 画预测值
    
            x2, y2 = get_fake_data(batch_size=20)
            plt.scatter(x2.numpy(), y2.numpy())                 # 画训练样本值
    
            plt.xlim(0, 20)
            plt.ylim(0, 41)
            plt.show()
            plt.pause(0.5)
    
    print(w.data.squeeze(), b.data.squeeze())                    # 不要写成.squeeze()[0]

    训练结果如下图所示:

  • 相关阅读:
    How many ways
    HDOj-1016 Prime Ring Problem
    DHU-1241 Oil Deposits
    Red and Black
    HDU-3790 最短路径问题
    vim/Gvim配置
    lintcode431- Connected Component in Undirected Graph- medium
    lintcode120- Word Ladder- medium
    lintcode531- Six Degrees- medium- microsoft
    lintcode624- Remove Substrings- medium
  • 原文地址:https://www.cnblogs.com/huangliu1111/p/14036468.html
Copyright © 2020-2023  润新知