对于vgg而言,他最重要的是VGGblock,总的来说就是通过循环生成一个多conv加一个relu的block层,然后将其使用flatten进行拉伸,最后送入线形层。
话不多说,看代码。
class reshape_data(nn.Module):
def forward(self,X):
return X.view(-1,1,224,224)
def vgg_block(num_convs, in_channels, out_channels):
layers = list()
for _ in range(num_convs):
layers.append(
nn.Conv2d(in_channels,out_channels,kernel_size=3,padding=1))
layers.append(nn.ReLU())
in_channels = out_channels
layers.append(nn.MaxPool2d(kernel_size=2,stride=2))
return nn.Sequential(*layers)
模型结构定义
class Vggnet(nn.Module):
def __init__(self):
super().__init__()
self.conv_arch = ((1, 64), (1, 128), (2, 256), (2, 512), (2, 512))
self.net = self.vgg(self.conv_arch)
self.reshape_data = reshape_data()
def vgg(self,conv_arch):
conv_bloks = list()
in_channel = 1
for (_num,outchannel) in self.conv_arch:
conv_bloks.append(vgg_block(num_convs=_num,in_channels=in_channel,out_channels=outchannel))
in_channel = outchannel
return nn.Sequential(*conv_bloks,
nn.Flatten(),
nn.Linear(outchannel*7*7,4096),
nn.ReLU(),
nn.Dropout(.5),
nn.Linear(4096,4096),
nn.ReLU(),
nn.Dropout(.5),
nn.Linear(4096,10))
def forward(self,X):
X = self.reshape_data(X)
output = self.net(X)
return output
X = torch.rand(size=(1, 1, 224, 224), dtype=torch.float32)
net = Vggnet()
for layer in net.net:
X = layer(X)
print(layer.__class__.__name__,'output shape: \t',X.shape)
模型结构输出
Sequential output shape: torch.Size([1, 64, 112, 112])
Sequential output shape: torch.Size([1, 128, 56, 56])
Sequential output shape: torch.Size([1, 256, 28, 28])
Sequential output shape: torch.Size([1, 512, 14, 14])
Sequential output shape: torch.Size([1, 512, 7, 7])
Flatten output shape: torch.Size([1, 25088])
Linear output shape: torch.Size([1, 4096])
ReLU output shape: torch.Size([1, 4096])
Dropout output shape: torch.Size([1, 4096])
Linear output shape: torch.Size([1, 4096])
ReLU output shape: torch.Size([1, 4096])
Dropout output shape: torch.Size([1, 4096])
Linear output shape: torch.Size([1, 10])