pytorch学习笔记-使用pytorch实现 AlexNet

使用 pytorch 实现 AlexNet 网络

闲话少说,直接上代码!
额…算了。还是过一下 AlexNet 网络吧,辉煌历史就不再赘述,从别的博主那里(忘记哪个博主了,不好意思哈,应该引用的)偷来了张图,直接上图。这里面参数什么的都有,像一个呆瓜直接照着敲就完了!
pytorch学习笔记-使用pytorch实现 AlexNet_第1张图片

class AlexNet(nn.Module):
    def __init__(self):
        super(AlexNet, self).__init__()
        self.conv1 = nn.Conv2d(3,96,kernel_size=11,stride=4)
        self.pool1 = nn.MaxPool2d(kernel_size=3,stride=2)
        self.bn1 = nn.BatchNorm2d(96)

        self.conv2 = nn.Conv2d(96,256,kernel_size=5,padding=2,groups=2)
        self.pool2 = nn.MaxPool2d(kernel_size=3,stride=2)
        self.bn2 = nn.BatchNorm2d(256)

        self.conv3 = nn.Conv2d(256,384,kernel_size=3,padding=1)
        self.conv4 = nn.Conv2d(384,384,kernel_size=3,padding=1)
        self.conv5 = nn.Conv2d(384,256,kernel_size=3,padding=1)

        self.pool3 = nn.MaxPool2d(kernel_size=3,stride=2)

        self.fc1 = nn.Linear(256 *6 *6,4096)
        self.fc2 = nn.Linear(4096,4096)
        self.fc3 = nn.Linear(4096,1000)

    def forward(self,x):
        x = self.conv1(x)
        x = F.relu(x)
        x = self.pool1(x)
        x = self.bn1(x)

        x = self.conv2(x)
        x = F.relu(x)
        x = self.pool2(x)
        x = self.bn2(x)

        x = self.conv3(x)
        x = F.relu(x)

        x = self.conv4(x)
        x = F.relu(x)

        x = self.conv5(x)
        x = F.relu(x)

        x = self.pool3(x)
        # 将多维的数据进行 Flatten 一下
        x = x.view(x.size(0),-1)
        x = self.fc1(x)
        x = F.relu(x)
        x = F.dropout(x)

        x = self.fc2(x)
        x = F.relu(x)
        x = F.dropout(x)

        x = self.fc3(x)
        return x

model3 = AlexNet()
# 输入的是四维 [batch_size,channel_size,width,height]
# 我记得 tensorflow 中的是这个顺序的 [batch_size,width,height,channel_size]
result = model3(torch.randn(32,3,227,227))
print(result.shape)

效果:
在这里插入图片描述
最后得出的就是 32*1000 的矩阵,32个样本,1000个类别。

你可能感兴趣的:(pytorch,pytorch,深度学习,神经网络)