CNN卷积神经网络(二)——AlexNet网络PyTorch实现

CNN卷积神经网络(二)——AlexNet网络PyTorch实现

相较于LeNet5,AlexNet只是堆叠了更多的网络层。一共有8个网络层,由5个卷积层和3个全连接层组成。
原文章:ImageNet Classification with Deep Convolutional Neural Networks
CNN卷积神经网络(二)——AlexNet网络PyTorch实现_第1张图片

AlexNet网络PyTorch实现

import torch
import torch.nn as nn

class AlexNet(nn.Module):
    def __init__(self):
        super(AlexNet, self).__init__()
        self.feature = nn.Sequential(
            # 卷积层1
            nn.Conv2d(in_channels=3,out_channels=96,kernel_size=11,stride=4,padding=0),  #(B,3,227,227) ——> (B,96,55,55)
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3,stride=2),                                        #(B,96,55,55)  ——> (B,96,27,27)
            # 卷积层2
            nn.Conv2d(in_channels=96,out_channels=256,kernel_size=5,stride=1,padding=2), #(B,96,27,27)  ——> (B,256,27,27)
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3,stride=2),                                        #(B,256,27,27)  ——> (B,256,13,13)
            # 卷积层3
            nn.Conv2d(in_channels=256,out_channels=384,kernel_size=3,stride=1,padding=1),#(B,256,13,13)  ——> (B,384,13,13)
            nn.ReLU(inplace=True),
            # 卷积层4
            nn.Conv2d(in_channels=384,out_channels=384,kernel_size=3,stride=1,padding=1),#(B,384,13,13)  ——> (B,384,13,13)
            nn.ReLU(inplace=True),
            # 卷积层5
            nn.Conv2d(in_channels=384,out_channels=256,kernel_size=3,stride=1,padding=1),#(B,384,13,13)  ——> (B,256,13,13)
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3,stride=2),                                        #(B,256,13,13)  ——> (B,256,6,6)
        )

        self.classify = nn.Sequential(
            nn.Linear(256*6*6, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(4096, 1000)
        )

    def forward(self,x):
        x = self.feature(x)
        x = x.view(-1,256*6*6)
        x = self.classify(x)
        return x

if __name__ == "__main__":
    x = torch.rand((8,3,227,227))
    net = AlexNet()
    y = net(x)
    print(y.shape)

你可能感兴趣的:(pytorch,cnn,网络)