-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathinit_weight.py
More file actions
57 lines (51 loc) · 2.16 KB
/
init_weight.py
File metadata and controls
57 lines (51 loc) · 2.16 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from torch.nn import init
def weights_init(init_type='normal', gain=0.02, bias=None):
r"""Initialize weights in the network.
Args:
init_type (str): The name of the initialization scheme.
gain (float): The parameter that is required for the initialization
scheme.
bias (object): If not ``None``, specifies the initialization parameter
for bias.
Returns:
(obj): init function to be applied.
"""
def init_func(m):
r"""Init function
Args:
m: module to be weight initialized.
"""
class_name = m.__class__.__name__
if hasattr(m, 'weight') and (
class_name.find('Conv') != -1 or
class_name.find('Linear') != -1 or
class_name.find('Embedding') != -1):
if init_type == 'normal':
init.normal_(m.weight.data, 0.0, gain)
elif init_type == 'xavier':
init.xavier_normal_(m.weight.data, gain=gain)
elif init_type == 'xavier_uniform':
init.xavier_uniform_(m.weight.data, gain=1.0)
elif init_type == 'kaiming':
init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
elif init_type == 'orthogonal':
init.orthogonal_(m.weight.data, gain=gain)
elif init_type == 'none':
m.reset_parameters()
else:
raise NotImplementedError(
'initialization method [%s] is '
'not implemented' % init_type)
if hasattr(m, 'bias') and m.bias is not None:
if bias is not None:
bias_type = getattr(bias, 'type', 'normal')
if bias_type == 'normal':
bias_gain = getattr(bias, 'gain', 0.5)
init.normal_(m.bias.data, 0.0, bias_gain)
else:
raise NotImplementedError(
'initialization method [%s] is '
'not implemented' % bias_type)
else:
init.constant_(m.bias.data, 0.0)
return init_func