Pytorch两种权重初始化的方法

方法一: 可以在定义模型的时候加入参数的初始化,如torchvision.models内的Resnet初始化。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class ResNet(nn.Module):

def __init__(self, block, layers, num_classes=1000):
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
self.avgpool = nn.AvgPool2d(7)
self.fc = nn.Linear(512 * block.expansion, num_classes)

for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()

方法二: 定义一个函数,在实例化模型后,对模型进行参数的初始化。

1
2
3
4
5
6
7
8
9
10
11
12
def weights_init_xavier(m):
classname = m.__class__.__name__

if classname.find('Conv') != -1:
init.xavier_normal(m.weight.data, gain=0.02)
elif classname.find('Linear') != -1:
init.xavier_normal(m.weight.data, gain=0.02)
elif classname.find('BatchNorm2d') != -1:
init.normal(m.weight.data, 1.0, 0.02)
init.constant(m.bias.data, 0.0)
net = torchvision.models.resnet152(pretrained=False)
net.apply(weights_init_xavier)

1. 上面两种方法在找网络中的Conv层的时候方法也不相同,如:

方法一的: isinstance(m, nn.Conv2d)
方法二的:

1
2
classname = m.__class__.__name__
if classname.find('Conv') != -1:

两种也都可以使用。

2. 上述两种方法对于具体参数的初始化也不相同,如:

方法一的:
m.weight.data.normal_(0, math.sqrt(2. / n))
方法二的 :
调用torch.nn.init
init.normal(m.weight.data, 1.0, 0.02)