【发布时间】:2021-06-25 00:47:43
【问题描述】:
我已经创建了这个神经网络:
class _netD(nn.Module):
def __init__(self, num_classes=1, nc=1, ndf=64):
super(_netD, self).__init__()
self.num_classes = num_classes
# nc is number of channels
# num_classes is number of classes
# ndf is the number of output channel at the first layer
self.main = nn.Sequential(
# input is (nc) x 28 x 28
# conv2D(in_channels, out_channels, kernelsize, stride, padding)
nn.Conv2d(nc, ndf , 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf) x 14 x 14
nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 2),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*2) x 7 x 7
nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 4),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*4) x 3 x 3
nn.Conv2d(ndf * 4, ndf * 8, 3, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 8),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*8) x 2 x 2
nn.Conv2d(ndf * 8, num_classes, 2, 1, 0, bias=False),
# out size = batch x num_classes x 1 x 1
)
if self.num_classes == 1:
self.main.add_module('prob', nn.Sigmoid())
# output = probability
else:
pass
# output = scores
def forward(self, input):
output = self.main(input)
return output.view(input.size(0), self.num_classes).squeeze(1)
我想遍历不同的层并根据层的类型应用权重初始化。我正在尝试执行以下操作:
D = _netD()
for name, param in D.named_parameters():
if type(param) == nn.Conv2d:
param.weight.normal_(...)
但这不起作用。你能帮帮我吗?
谢谢
【问题讨论】:
标签: python-3.x neural-network pytorch torch