基于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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值