Jib*_*hew 4 python pytorch dropout
如何在 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
Run Code Online (Sandbox Code Playgroud)
Jib*_*hew 12
由于 forward 方法中有函数代码,您可以使用函数 dropout,但是,最好使用nn.Module
in__init__()
以便模型在设置为model.eval()
评估模式时自动关闭 dropout。
下面是实现 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
Run Code Online (Sandbox Code Playgroud)