Created
December 1, 2017 22:37
-
-
Save jojonki/be1e8af97dfa12c983446391c3640b68 to your computer and use it in GitHub Desktop.
Custom initialization of weights in PyTorch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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