DL学习10-vggnet-mnist

本文介绍了VGG网络的核心部分——VGGblock,它由多个卷积层加ReLU激活函数组成,通过MaxPool2d进行下采样。模型通过多个这样的块构建,最终使用Flatten层展平特征并接入全连接层进行分类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于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])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值