【问题标题】:Implement dropout to fully connected layer in PyTorch在 PyTorch 中实现完全连接层的 dropout
【发布时间】:2019-08-05 01:15:29
【问题描述】:

如何在 Pytorch 中对以下全连接网络应用 dropout:

class NetworkRelu(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(784,128)
        self.fc2 = nn.Linear(128,64)
        self.fc3 = nn.Linear(64,10)


    def forward(self,x):
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = F.softmax(self.fc3(x),dim=1)
        return x

【问题讨论】:

    标签: python pytorch dropout


    【解决方案1】:

    由于forward方法中有函数代码,你可以使用函数dropout,但是,最好在__init__()中使用nn.Module,这样模型在设置为model.eval()评估模式时会自动关闭退出。

    下面是实现dropout的代码:

    class NetworkRelu(nn.Module):
        def __init__(self):
            super().__init__()
            self.fc1 = nn.Linear(784,128)
            self.fc2 = nn.Linear(128,64)
            self.fc3 = nn.Linear(64,10)
            self.dropout = nn.Dropout(p=0.5)
    
        def forward(self,x):
            x = self.dropout(F.relu(self.fc1(x)))
            x = self.dropout(F.relu(self.fc2(x)))
            x = F.softmax(self.fc3(x),dim=1)
            return x
    

    【讨论】:

    • 我们也可以像示例中那样多次使用相同的dropout 对象,对吧?无需为转发的第二行创建self.dropout2 = nn.Dropout(p=0.5)x = self.dropout2(F.relu(self.fc2(x)))
    • @patti_jane 是的,我们可以多次使用同一个 dropout 对象。
    猜你喜欢
    • 2018-10-14
    • 2019-01-29
    • 2021-10-08
    • 2017-07-30
    • 2022-01-13
    • 2020-04-14
    • 2023-01-25
    • 2021-01-09
    • 2019-03-30
    相关资源
    最近更新 更多