【Pytorch神经网络】CNN

文章目录

    • CNN输出大小公式(卷积核长宽相等)
    • Code
    • 参考资料

使用Pytorch神经网络框架,搭建一个简单的网络模型,运用了卷积层,池化层,线性层等内容。

CNN输出大小公式(卷积核长宽相等)

  • 输入 n ∗ n n * n nn
  • 卷积核 f ∗ f f*f ff
  • padding: p p p, stride: s s s

公式如下:

O = n − f − 2 p s + 1 O = \frac{n-f-2p}{s} + 1 O=snf2p+1

若卷积核长宽不等,则长宽用上述公式分开计算

Operation Output Shape
Identity function torch.Size([1, 1, 28, 28])
Conv(5 x 5) torch.Size([1, 6, 24, 24])
Maxpooling(2 x 2) torch.Size([1, 6, 12, 12])
Conv(5 x 5) torch.Size([1, 12, 8, 8])
Maxpooling(2 x 2) torch.Size([1, 12, 4,4])
Flatten torch.Size([1, 192])
Linear torch.Size([1, 120])
Linear torch.Size([1, 60])
Linear torch.Size([1, 10])

Code

import torch
import torch.nn as nn
import torch.nn.functional as F

import torchvision
import torchvision.transforms as transforms

class Network(nn.Module):
    def __init__(self):
        super(Network, self).__init__()
        self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5)
        self.conv2 = nn.Conv2d(in_channels=6, out_channels=12, kernel_size=5)
        
        self.fc1 = nn.Linear(in_features=12*4*4, out_features=120)
        self.fc2 = nn.Linear(in_features=120, out_features=60)
        self.out = nn.Linear(in_features=60, out_features=10)
    
    def forward(self, t):
        # 1. 输入层
        t = t
        
        # 2. 卷积层
        t = self.conv1(t)
        t = F.relu(t)
        t = F.max_pool2d(t, kernel_size=2, stride=2)
        
        # 3. 卷积层
        t = self.conv2(t)
        t = F.relu(t)
        t = F.max_pool2d(t, kernel_size=2, stride=2)
        
        # 4. 线性层
        t = t.reshape(-1, 12 * 4 * 4)
        t = self.fc1(t)
        t = F.relu(t)
        
        # 5. 线性层
        t = self.fc2(t)
        t = F.relu(t)
        
        # 6. 输出层
        t = self.out(t)
        
        return t


network = Network()
train_set = torchvision.datasets.FashionMNIST(
    root='../lizard-code/pytorch/data/FasionMNIST',
    train=True,
    download=True,
    transform=transforms.Compose([
        transforms.ToTensor()
    ])
)

sample = next(iter(train_set))
image, label = sample

# 将 单个图像 转换成 一个大小为1的批
output = network(image.unsqueeze(0))
print(output)

print(output.argmax(dim=1))

参考资料

  1. 适用于初学者的Pytorch神经网络编程教学

你可能感兴趣的:(AI,神经网络,pytorch,cnn,python)