Skip to content

Instantly share code, notes, and snippets.

@jojonki
Created December 1, 2017 22:37
Show Gist options
  • Save jojonki/be1e8af97dfa12c983446391c3640b68 to your computer and use it in GitHub Desktop.
Save jojonki/be1e8af97dfa12c983446391c3640b68 to your computer and use it in GitHub Desktop.
Custom initialization of weights in PyTorch
# https://github.com/pytorch/examples/blob/master/dcgan/main.py#L95-L102
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)
# https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py#L46-L59
def _initialize_weights(self):
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))
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
m.weight.data.normal_(0, 0.01)
m.bias.data.zero_()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment