深度学习笔记9:丢弃法

丢弃法

在这里插入图片描述

动机

一个好的模型需要对输入数据的扰动鲁棒性

  • 使用有噪音的数据等价于Tikhonov正则
  • 丢弃法:在层之间加入噪音

无偏差的加入噪音

  • x加入噪音得到x',我们希望E[x']=x

  • 丢弃法对每个元素进行如下扰动

    在这里插入图片描述

使用丢弃法

通常将丢弃法作用在隐藏全连接层的输出上(随机丢弃置0)

在这里插入图片描述

推理中的丢弃法

  • 正则项只在训练中使用:他们影响模型参数的更新
  • 在推理过程中,丢弃法直接返回输入 h=dropout(h)
    • 这样也能保证确定性的输出

总结

  • 丢弃法将一些输出项随机置为0来控制模型复杂度
  • 常作用在多层感知机的隐藏层输出上
  • 丢弃概率是控制模型复杂度的超参数

代码实现

Dropout

我们实现 dropout_layer 函数,该函数以dropout的概率丢弃张量输入X中的元素

import torch
from torch import nn
from d2l import torch as d2l

def dropout_layer(X, dropout):
    assert 0 <= dropout <= 1  #p大于0小于1 
    if dropout == 1: #p=1返回全0的张量
        return torch.zeros_like(X)
    if dropout == 0: #p=0返回X
        return X
    mask = (torch.Tensor(X.shape).uniform_(0, 1) > dropout).float()
    return mask * X / (1.0 - dropout)

测试dropout_layer函数

X = torch.arange(16, dtype=torch.float32).reshape((2, 8))
print(X)
print(dropout_layer(X, 0.)) #返回自己
print(dropout_layer(X, 0.5)) #p=0.5 随机置0
print(dropout_layer(X, 1.)) #变成0

结果:

tensor([[ 0., 1., 2., 3., 4., 5., 6., 7.],
[ 8., 9., 10., 11., 12., 13., 14., 15.]])
tensor([[ 0., 1., 2., 3., 4., 5., 6., 7.],
[ 8., 9., 10., 11., 12., 13., 14., 15.]])
tensor([[ 0., 2., 0., 0., 8., 10., 12., 14.],
[ 0., 18., 0., 22., 24., 0., 28., 30.]])
tensor([[0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0.]])

定义具有两个隐藏层的多层感知机,每个隐藏层包含256个单元

num_inputs, num_outputs, num_hiddens1, num_hiddens2 = 784, 10, 256, 256

dropout1, dropout2 = 0.2, 0.5

class Net(nn.Module):
    def __init__(self, num_inputs, num_outputs, num_hiddens1, num_hiddens2,
                 is_training=True): #是否在训练
        super(Net, self).__init__()
        self.num_inputs = num_inputs
        self.training = is_training
        self.lin1 = nn.Linear(num_inputs, num_hiddens1) #两个隐藏层-有三个线性层
        self.lin2 = nn.Linear(num_hiddens1, num_hiddens2)
        self.lin3 = nn.Linear(num_hiddens2, num_outputs)
        self.relu = nn.ReLU()

    def forward(self, X):
        H1 = self.relu(self.lin1(X.reshape((-1, self.num_inputs)))) #第一个隐藏层的输出
        if self.training == True: #如果在训练
            H1 = dropout_layer(H1, dropout1) #作用dropout
        H2 = self.relu(self.lin2(H1)) #把h1放到第二个隐藏层
        if self.training == True: #训练
            H2 = dropout_layer(H2, dropout2) #再做dropout
        out = self.lin3(H2) #输出层
        return out

net = Net(num_inputs, num_outputs, num_hiddens1, num_hiddens2)

训练和测试

num_epochs, lr, batch_size = 10, 0.5, 256
loss = nn.CrossEntropyLoss(reduction='none')
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
trainer = torch.optim.SGD(net.parameters(), lr=lr)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)

结果:

在这里插入图片描述

简洁实现

net = nn.Sequential(nn.Flatten(), nn.Linear(784, 256), nn.ReLU(),
                    nn.Dropout(dropout1), nn.Linear(256, 256), nn.ReLU(),
                    nn.Dropout(dropout2), nn.Linear(256, 10))

def init_weights(m):
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight, std=0.01)

net.apply(init_weights);

对模型进行训练和测试

trainer = torch.optim.SGD(net.parameters(), lr=lr)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)

结果:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值