Advertisement

PyTorch框架下的线性回归模型手写实现

阅读量:

一、概述
构建以线性回归模型为基础的神经网络结构,通过编写代码的方式详细说明其搭建流程,并最终提供完整的代码内容及相应的运行结果
二、搭建步骤
1、创建数据集

复制代码
    #生成数据集
    num_input=3
    num_examples=1000
    features=torch.Tensor(np.random.normal(0,1,(num_input,num_examples)))
    true_w=torch.Tensor([[3.4,-5,2.5]])
    true_b=torch.Tensor([[4.2]])
    labels=torch.mm(true_w,features)+true_b
    
    
      
      
      
      
      
      
      
    

2、在对随机梯度下降法进行定义之前,需先设定一个函数,用以完成从训练数据集中随机抽取小批量样本的操作。

复制代码
    #筛选小批量数据集
    def Data_Iter(Features,Labels,Batch_Size):
    length=Features.shape[1]
    index=list(range(length))
    random.shuffle(index)
    for i in range(0,length,Batch_Size):
        j=torch.LongTensor(index[i:min(i+Batch_Size,length)])
        yield Features[0,j],Features[1,j],Features[2,j],labels[0,j]
    
    
      
      
      
      
      
      
      
      
    

3、构建线性回归模型

复制代码
    #定义线性回归神经网络
    def Linear_Regression(Weight,Bias,X):
    return torch.mm(Weight,X)+Bias
    
    
      
      
      
    

4、确立损失函数的定义

复制代码
    #定义损失函数
    def Loss_Function(Y_hat,Y,Batch_Size):
    return ((Y_hat-Y)**2).sum()/Batch_Size
    
    
      
      
      
    

5、阐述随机梯度下降法的定义

复制代码
    #定义随机梯度下降算法
    def SGD(Params,lr):
    for Param in Params:
        Param.data-=lr*Param.grad
    
    
      
      
      
      
    

6、设定训练初始参数

复制代码
    num_epoches=3
    w=torch.tensor([[1,1,1]],dtype=torch.float32,requires_grad=True)
    b=torch.tensor(np.array([1]),dtype=torch.float32,requires_grad=True)
    lr=0.03
    batch_size=10
    
    
      
      
      
      
      
    

7、启动训练过程

复制代码
    #开始训练
    for epoch in range(num_epoches):   
    for x1,x2,x3,y in Data_Iter(features, labels, batch_size):
        x=torch.stack([x1,x2,x3],dim=0)
        y_hat=Linear_Regression(w,b,x)
        #计算损失函数
        L=Loss_Function(y_hat,y,batch_size)
        #计算梯度
        L.backward()
        #更新权值及偏置
        SGD([w,b],lr)
        #梯度清零
        w.grad.data.zero_()
        b.grad.data.zero_()
    train_l=Loss_Function(Linear_Regression(w,b,features),labels,num_examples)
    print('epoch %d, loss %f' % (epoch+1,train_l))
    #验证训练结果
    print(w,'\n',b)
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    

三、所有源代码

复制代码
    import torch
    from IPython import display
    from matplotlib import pyplot as plt
    import numpy as np
    import random
    #生成数据集
    num_input=3
    num_examples=1000
    features=torch.Tensor(np.random.normal(0,1,(num_input,num_examples)))
    true_w=torch.Tensor([[3.4,-5,2.5]])
    true_b=torch.Tensor([[4.2]])
    labels=torch.mm(true_w,features)+true_b
    #筛选小批量数据集
    def Data_Iter(Features,Labels,Batch_Size):
    length=Features.shape[1]
    index=list(range(length))
    random.shuffle(index)
    for i in range(0,length,Batch_Size):
        j=torch.LongTensor(index[i:min(i+Batch_Size,length)])
        yield Features[0,j],Features[1,j],Features[2,j],labels[0,j]
    #定义线性回归神经网络
    def Linear_Regression(Weight,Bias,X):
    return torch.mm(Weight,X)+Bias
    #定义损失函数
    def Loss_Function(Y_hat,Y,Batch_Size):
    return ((Y_hat-Y)**2).sum()/Batch_Size
    #定义随机梯度下降算法
    def SGD(Params,lr):
    for Param in Params:
        Param.data-=lr*Param.grad
    #初始化训练参数
    num_epoches=3
    w=torch.tensor([[1,1,1]],dtype=torch.float32,requires_grad=True)
    b=torch.tensor(np.array([1]),dtype=torch.float32,requires_grad=True)
    lr=0.03
    batch_size=10
    #开始训练
    for epoch in range(num_epoches):   
    for x1,x2,x3,y in Data_Iter(features, labels, batch_size):
        x=torch.stack([x1,x2,x3],dim=0)
        y_hat=Linear_Regression(w,b,x)
        #计算损失函数
        L=Loss_Function(y_hat,y,batch_size)
        #计算梯度
        L.backward()
        #更新权值及偏置
        SGD([w,b],lr)
        #梯度清零
        w.grad.data.zero_()
        b.grad.data.zero_()
    train_l=Loss_Function(Linear_Regression(w,b,features),labels,num_examples)
    print('epoch %d, loss %f' % (epoch+1,train_l))
    print(w,'\n',b)
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    

四、运行结果展示

在这里插入图片描述

全部评论 (0)

还没有任何评论哟~