• 李沐深度学习记录5:13.Dropout


    Dropout从零开始实现

    import torch
    from torch import nn
    from d2l import torch as d2l
    
    # 定义Dropout函数
    def dropout_layer(X, dropout):
        assert 0 <= dropout <= 1
        # 在本情况中,所有元素都被丢弃
        if dropout == 1:
            return torch.zeros_like(X)
        # 在本情况中,所有元素都被保留
        if dropout == 0:
            return X
        #torch.rand生成0-1之间的均匀分布随机数,将其值与dropout概率作比较,得到布尔类型结果由mask存储
        #布尔类型为0的则为随机丢弃置0的隐藏层单元,留下的则进行值的替换h-->h/(1-p)
        mask = (torch.rand(X.shape) > dropout).float()
        return mask * X / (1.0 - dropout)
    
    # 测试dropout函数
    # X= torch.arange(16, dtype = torch.float32).reshape((2, 8))
    # print(X)
    # print(dropout_layer(X, 0.))
    # print(dropout_layer(X, 0.5))
    # print(dropout_layer(X, 1.))
    
    #定义模型参数
    num_inputs, num_outputs, num_hiddens1, num_hiddens2 = 784, 10, 256, 256
    
    #定义模型
    dropout1, dropout2 = 0.2, 0.5
    
    class Net(nn.Module):  #写一个模型类继承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)))) #第一层全连接层加激活函数
            # 只有在训练模型时才使用dropout
            if self.training == True:
                # 在第一个全连接层之后添加一个dropout层
                H1 = dropout_layer(H1, dropout1)
            H2 = self.relu(self.lin2(H1))
            if self.training == True:
                # 在第二个全连接层之后添加一个dropout层
                H2 = dropout_layer(H2, dropout2)
            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)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67

    在这里插入图片描述

    Dropout简洁实现

    import torch
    from torch import nn
    from d2l import torch as d2l
    
    #定义模型参数
    num_inputs, num_outputs, num_hiddens1, num_hiddens2 = 784, 10, 256, 256
    
    #定义模型
    dropout1, dropout2 = 0.2, 0.5
    
    #定义模型
    net=nn.Sequential(nn.Flatten(),
                      nn.Linear(784,256),
                      nn.ReLU(),
                      #第一个全连接层之后添加一个Dropout层
                      nn.Dropout(dropout1),
                      nn.Linear(256,256),
                      nn.ReLU(),
                      #第二个全连接层之后添加一个Dropout层
                      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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    在这里插入图片描述

    #读取数据
    batch_size = 256
    train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
    
    #训练测试
    num_epochs,lr=10,0.5
    loss = nn.CrossEntropyLoss(reduction='none')
    trainer=torch.optim.SGD(net.parameters(),lr=lr)
    d2l.train_ch3(net,train_iter,test_iter,loss,num_epochs,trainer)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在这里插入图片描述

  • 相关阅读:
    NUWA论文阅读
    6-2 矩阵乘法函数(高教社,《Python编程基础及应用》习题4-11)
    深度学习模型训练总结:基于pytorch的训练参数调整
    《自然语言处理》第二次实验:机器翻译(Seq2Seq中英文翻译实验)
    微服务实战 02 Sentinel 入门
    【毕业设计】Stm32酒驾检查系统 - 单片机 嵌入式 物联网
    代码整洁之道
    如何将多模态数据融入到BERT架构中-多模态BERT的两类预训练任务
    【2020.09.01】 新学期,新气象
    Springboot 框架中加解密字段后存储数据库
  • 原文地址:https://blog.csdn.net/qq_46238275/article/details/133611123