【动手学深度学习】part8-线性规划

依据《动手学深度学习》理解并复现“线性规划”章节代码


一、背景

  • 利用线性规划模型进行拟合,解决预测问题。
  • 在这章的学习过程中,能够很好地理解SGD优化算法的实现过程,这也是深度学习最经典最常用的优化算法。
  • 并且能够建立深度学习的一个使用框架,即:
    ①构建模型(设置网络层数等)
    ②构建损失函数(MSE均方误差等)
    ③设置超参数(学习率learning_rate、批量大小batch_size、迭代次数num_epoch等)
    ④迭代优化(SGD等)

(个人理解:数学本质上就是一个优化问题,目标为最小化损失函数)

二、流程

  1. 前向传播:net(X, w, b)计算模型的预测输出。
  2. 计算损失:loss()计算预测输出与真实标签之间的均方误差损失。
  3. 反向传播:调用 .backward() 计算梯度。
  4. 更新参数:使用随机梯度下降(SGD)更新参数。with torch.no_grad()
    用于临时禁用梯度计算,因为参数更新不需要计算梯度。
  5. 清零梯度:在每次迭代结束后,.grad.zero_()清零参数的梯度,以便在下一次迭代中重新计算梯度。
  6. 打印损失:每1个epoch打印一次损失值,以便观察训练过程。

三、代码版本-v1(从零开始)

  • 基于上述流程的代码复现及注释
import random
import torch
from d2l import torch as d2l

def synthetic_data(w, b, num_examples):  
    """生成 y = Xw + b + 噪声。"""
    X = torch.normal(0, 1, (num_examples, len(w))) #均值为0,方差为1的随机数
    y = torch.matmul(X, w) + b
    y += torch.normal(0, 0.01, y.shape) #随机噪声
    return X, y.reshape(-1, 1)

#自定义真实w,b
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = synthetic_data(true_w, true_b, 1000)
print('features:', features[0], '\nlabel:', labels[0])

#绘制生成的真值数据
d2l.set_figsize()
d2l.plt.scatter(features[:, 1].detach().numpy(),
                labels.detach().numpy(), 1);
d2l.plt.show()

#从真值数据中随机采样batch_size个数据
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):
        batch_indices = torch.tensor(indices[i:min(i +
                                                   batch_size, num_examples)])
        yield features[batch_indices], labels[batch_indices]

batch_size = 10

#初始化w,b
w = torch.normal(0, 0.01, size=(2, 1), requires_grad=True)  #requires_grad=True表示要计算梯度
b = torch.zeros(1, requires_grad=True)

def linreg(X, w, b):  
    """线性回归模型。"""
    return torch.matmul(X, w) + b

def squared_loss(y_hat, y):  
    """MSE均方损失。"""
    return (y_hat - y.reshape(y_hat.shape))**2 / 2

def sgd(params, lr, batch_size):  
    """SGD小批量随机梯度下降。"""
    with torch.no_grad():
        '''with torch.no_grad() 用于临时禁用梯度计算,因为参数更新不需要计算梯度。'''
        for param in params:
            param -= lr * param.grad / batch_size   #param.grad取对应参数的梯度
            '''(5)清零梯度:在每次迭代结束后,清零参数的梯度,以便在下一次迭代中重新计算梯度。'''
            param.grad.zero_()  #手动把梯度设置为0,以免下次计算梯度与上一次更新相关
            
lr = 0.03
num_epochs = 3  #整个数据扫三遍
net = linreg
loss = squared_loss

for epoch in range(num_epochs):
    for X, y in data_iter(batch_size, features, labels):
        '''(1)前向传播:net(X, w, b)计算模型的预测输出。'''
        '''(2)计算损失:loss()计算预测输出与真实标签之间的均方误差损失。'''
        l = loss(net(X, w, b), y)
        '''(3)反向传播:调用 .backward() 计算梯度。'''
        l.sum().backward()  #backward是对函数里所有required_grad=True的参数都求了梯度
        '''(4)更新参数:使用随机梯度下降(SGD)更新参数。'''
        sgd([w, b], lr, batch_size)
    with torch.no_grad():
        train_l = loss(net(features, w, b), labels)
        print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')

print(f'w的估计误差: {true_w - w.reshape(true_w.shape)}')
print(f'b的估计误差: {true_b - b}')

四、关于SGD中计算梯度的说明

  • 以一个简单的例子说明
'''
示例: 线性回归模型 y = wx + b
损失函数:1/2*((y - y')^2)
优化目标:min(1/2*(y - y')^2)
计算梯度:gead_w = x(wx + b - y), grad_b = (wx + b - y)
'''

上述例子中,计算梯度的过程相当于分别对w和b求偏导。

  • 代码中的解释

上述代码中,w为2个元素,即w=[w1,w2],计算梯度时相当于要分别对w1和w2求偏导。
并且反向传播时运用的是“l.sum().backward()”去计算梯度,以w1为例,可以理解为:
在这里插入图片描述
后续求w1偏导的过程基于链式求导法则可以得出。

五、代码版本-v2

  • 这个版本直接借用torch.nn库去调用相关函数进行线性拟合,流程一样
import numpy as np
import torch
from torch.utils import data
from d2l import torch as d2l
from torch import nn

true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = d2l.synthetic_data(true_w, true_b, 1000)

def load_array(data_arrays, batch_size, is_train=True):  
    """构造一个PyTorch数据迭代器。"""
    dataset = data.TensorDataset(*data_arrays)
    return data.DataLoader(dataset, batch_size, shuffle=is_train)

batch_size = 10
data_iter = load_array((features, labels), batch_size)

#随机选取batch_size个x,y
next(iter(data_iter))

net = nn.Sequential(nn.Linear(2, 1))    #nn.Linear(2, 1)代表线性层,输入维度是2,输出维度是1

#初始化一个w、b的值
net[0].weight.data.normal_(0, 0.01)
net[0].bias.data.fill_(0)

#均方误差的函数
loss = nn.MSELoss()

#SGD的函数
trainer = torch.optim.SGD(net.parameters(), lr=0.03)

num_epochs = 3
for epoch in range(num_epochs):
    for X, y in data_iter:
        l = loss(net(X), y)
        trainer.zero_grad()
        l.backward()
        trainer.step()
    l = loss(net(features), labels)
    print(f'epoch {epoch + 1}, loss {l:f}')
    
w = net[0].weight.data
print('w的估计误差:', true_w - w.reshape(true_w.shape))
b = net[0].bias.data
print('b的估计误差:', true_b - b)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值