[4fa73e]: / pytorch / graphs / weights_initializer.py

Download this file

44 lines (37 with data), 1.2 kB

 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
"""
A file for all models' weight initialization functions
"""
import torch
from torch import nn
import numpy as np
import graphs
import math
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
def weights_init_normal(m):
"""
Initialize the weights of Convolution3D and BatchNorm3D with normal.
:param m:
:return:
"""
if isinstance(m, nn.Conv3d):
m.weight.data.normal_(0.0, 0.02)
elif isinstance(m, nn.BatchNorm3d):
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
def init_model_weights(m):
### initialize
for m in m.modules():
if isinstance(m, nn.Conv3d):
n = m.kernel_size[0] * m.kernel_size[1] * m.kernel_size[2] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm3d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
m.bias.data.zero_()