nn.Dropout
官方定义
Dropout是一种常用的正则化方法,通过随机将部分神经元的输出置为0来减少过拟合。
Dropout在训练时随机讲某些张量的值设为0,从而减少模型对训练数据的依赖程序,提高泛化能力;同时在测试时需要关闭Dropout,具体来说,如果处于model.eval模式时,并不会使用Dropout。
官方的文档如下,nn.dropout
例子
import torch
import torch.nn as nn
m = nn.Dropout(p=0.2)
input = torch.randn(20, 16)
output = m(input)
print(input[0])
print(output[0])
输出的结果:
- 有一部分的值变为了0,这些值大约占据总数的0.2。
- 其它非0参数都除以0.8,使得值变大了。比如:0.3514 / 0.8 =0.4392,-1.0317 / 0.8 = -1.2896
Dropout的位置
一般来说,我们在实现的神级网络中这么定义:
self.dropout = nn.Dropout(0.3)
Dropout使用位置是在隐藏层之间的节点上,具体来说,就是在全连接层之间放置Dropout来避免过拟合:
import torch
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(in_features, hidden_size)
self.dropout = nn.Dropout(dropout_prob)
self.fc2 = nn.Linear(hidden_size, out_features)
def forward(self, x):
x = self.fc1(x)
x = self.dropout(x)
x = torch.relu(x)
x = self.fc2(x)
return x
比如上面得这个例子,dropout被放置在fc1和fc2之间。