Pytorch手动实现线性回归

简述

使用Pytorch来实现简单的线性回归,即, y = w x + b y=wx + b y=wx+b
在这个任务中,我们有着features:x 和 labels: y;想要得到号的参数w和b
我们设置正式的 w = [ 3 , 4 ] , b = 10 w=[3,4], b=10 w=[3,4],b=10
由于真实的数据是会有噪声的,所以最后再加上一个噪声标签c,且服从期望=0,方差=0.01的正态分布.
数据集的大小为1000.

生成数据集

  • feature是2维的
  • 数据集大小为1000
num_inputs = 2
num_example = 1000
true_w = [3, 4]
true_b = 5
features = torch.randn(num_example, num_inputs, dtype=torch.float32)
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
labels += torch.tensor(np.random.normal(0, 0.01, size = labels.size()), dtype = torch.float32)

数据集的读取

由于后边的优化函数会使用到批量随机下降的方法,所以这里读取数据的时候需要根据batch_size来读取

# 本函数已保存在d2lzh包中方便以后使用
def data_iter(batch_size, features, labels):
    num_examples = len(features)
    indices = list(range(num_examples))
    random.shuffle(indices)  # 样本的读取顺序是随机的
    for i in range(0, num_examples, batch_size):
        j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) # 最后一次可能不足一个batch
        yield  features.index_select(0, j), labels.index_select(0, j)

知识点

list(xxx):把xxx转化为列表变量
shuffle(indices): 打乱indices中元素的位置
yield:请看前面的博客,相当于return 与 生成器.

初始化模型参数

  • 设初始的w是一个符合均值为2,方差为3正态分布的随机变量
  • 初始的b为0
  • 由于需要对w和b求梯度,所以需要设置required_grad=True
# 初始化模型参数
'''
w: 均值为2,标准差为3的正态随机数
b = 0
'''
w = torch.tensor(np.random.normal(2, 3, (num_inputs, 1)), dtype = torch.float32)
b = torch.zeros(1, dtype=torch.float32)
'''
需要对w,b求梯度,所以需要将requires_grad设置为True
'''
w.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)

定义模型

'''定义线性回归的模型'''
def linreg(X, w, b):
    return torch.mm(X, w) + b

定义loss函数

这里使用平方损失函数来作为loss

'''定义线性回归的损失函数'''
def squared_loss(y_hat, y):
    return (y_hat - y.view(y_hat.size())) ** 2 / 2

定义优化算法

小批量随机梯度下降算法。它通过不断迭代模型参数来优化损失函数。这里自动求梯度模块计算得来的梯度是一个批量样本的梯度和。我们将它除以批量大小来得到平均值。

'''线性回归的优化算法 —— 小批量随机梯度下降法'''
def sgd(params, lr, batch_size):
    for param in params:
        param.data -= lr * param.grad / batch_size #这里使用的是param.data

模型训练

  • 在训练中,我们将多次迭代模型参数.每次迭代中,我们根据当前读取的小批量数据样本(特征X和标签y),通过反向传播函数backward计算小批量随机梯度,并调用sgd函数来进行优化模型参数.由于loss并不是一个参数,所以我们需要调用l.sum()对其求和得到标量,这样就可以使用l.backward得到该参数的梯度,最后每次求其梯度之后,需要对模型参数的梯度清零.
  • 在每一个迭代周期(epoch)中,我们需要完整遍历一篇data_iter函数,对数据集中的样本都遍历一遍,这里的lr与num_epochs都是超参数,分别代表学习率与迭代周期次数.

# 训练模型
lr = 0.03  #学习率
num_epochs = 3 # 迭代周期数
net = linreg   # 模型
loss = squared_loss # 损失函数
batch_size = 10 #设置每次批量的大小

for epoch in range(num_epochs):     #训练模型一共需要num_epochs个迭代周期
    # 在每一个迭代周期中,会使用训练数据集中所有样本一次(假设样本数据能够背批量大小整除)
    # X和y分别是小批量样本的特征和标签
    for X, y in data_iter(batch_size, features, labels):
        l = loss(net(X, w, b), y).sum()   #l是关于小批量X和y的损失
        l.backward()  # 小批量的损失对模型参数求梯度
        sgd([w,b], lr, batch_size)

        # 对梯度清零
        w.grad.data.zero_()
        b.grad.data.zero_()
    train_l = loss(net(features, w, b), labels)
    print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))

训练结果

通过输出最终的w和b可以看到与真实设置的w,b的差距

print(true_w, '\n', w)
print(true_b, '\n', b)

在这里插入图片描述

整体代码

d2lzh_pytorch.py

import random
from IPython import display
import matplotlib.pyplot as plt
import torch


def use_svg_display():
    # 用矢量图显示
    display.set_matplotlib_formats('svg')

def set_figsize(figsize=(3.5, 2.5)):
    use_svg_display()
    # 设置图的尺寸
    plt.rcParams['figure.figsize'] = figsize

'''给定batch_size, feature, labels,做数据的打乱并生成指定大小的数据集'''
def data_iter(batch_size, features, labels):
    num_examples = len(features)
    indices = list(range(num_examples))
    random.shuffle(indices)
    for i in range(0, num_examples, batch_size): #(start, staop, step)
        j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) #最后一次可能没有一个batch
        yield features.index_select(0, j), labels.index_select(0, j)

'''定义线性回归的模型'''
def linreg(X, w, b):
    return torch.mm(X, w) + b

'''定义线性回归的损失函数'''
def squared_loss(y_hat, y):
    return (y_hat - y.view(y_hat.size())) ** 2 / 2

'''线性回归的优化算法 —— 小批量随机梯度下降法'''
def sgd(params, lr, batch_size):
    for param in params:
        param.data -= lr * param.grad / batch_size #这里使用的是param.data

main.py

import torch
from IPython import display
from matplotlib import pyplot as plt
import numpy as np
import random
import sys
sys.path.append("..")
from d2lzh_pytorch import *


# 生成数据集
'''
数据集的样本数: 1000
输入特征数: 2
权重w: = [2, -3.4]
偏置b: = 4.2
一个随机噪音项e,服从均值为0, 标准差为0.01的正态分布
'''
num_inputs = 2
num_example = 1000
true_w = [3, 4]
true_b = 5
features = torch.randn(num_example, num_inputs, dtype=torch.float32)
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
labels += torch.tensor(np.random.normal(0, 0.01, size = labels.size()), dtype = torch.float32)

# 初始化模型参数
'''
w: 均值为2,标准差为3的正态随机数
b = 0
'''
w = torch.tensor(np.random.normal(2, 3, (num_inputs, 1)), dtype = torch.float32)
b = torch.zeros(1, dtype=torch.float32)
'''
需要对w,b求梯度,所以需要将requires_grad设置为True
'''
w.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)


# 训练模型
lr = 0.03  #学习率
num_epochs = 3 # 迭代周期数
net = linreg   # 模型
loss = squared_loss # 损失函数
batch_size = 10 #设置每次批量的大小

for epoch in range(num_epochs):     #训练模型一共需要num_epochs个迭代周期
    # 在每一个迭代周期中,会使用训练数据集中所有样本一次(假设样本数据能够背批量大小整除)
    # X和y分别是小批量样本的特征和标签
    for X, y in data_iter(batch_size, features, labels):
        l = loss(net(X, w, b), y).sum()   #l是关于小批量X和y的损失
        l.backward()  # 小批量的损失对模型参数求梯度
        sgd([w,b], lr, batch_size)

        # 对梯度清零
        w.grad.data.zero_()
        b.grad.data.zero_()
    train_l = loss(net(features, w, b), labels)
    print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))

print(true_w, '\n', w)
print(true_b, '\n', b)




  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值