pytorch卷积神经网络(六)

卷积神经网络

  • 链接
  • 补充
    • 卷积conv2d
    • 池化MaxPool2d
    • 整体流程
    • 代码实现
    • 代码
  • GoogleNet
  • ResidualNet残差神经网络

链接

卷积神经网络基础

卷积神经网络高级部分

刘二大人笔记链接

刘二大人视频链接

补充

卷积conv2d

pytorch卷积神经网络(六)_第1张图片

  • convolution中的卷积核数量N和输入Channels相同,每N个卷积核计算组成一个输出数据output,每N个卷积核作为一个filters,M个filters组成M维outputs
    pytorch卷积神经网络(六)_第2张图片

pytorch卷积神经网络(六)_第3张图片

  • 一共需要 M ( 输 出 C h a n n e l s ) ∗ N ( 输 入 C h a n n e l s ) M(输出Channels)*N(输入Channels) MChannelsNChannels个卷积核
    pytorch卷积神经网络(六)_第4张图片

  • 一次卷积后输出的每个Channels的数据大小会变成 ( i n p u t s w i d t h − k e r n e l s i z e + 1 ) ∗ ( i n p u t s h e i g h t − k e r n e l s i z e + 1 ) (inputs_{width}-kernel_{size}+1)*(inputs_{height}-kernel_{size}+1) (inputswidthkernelsize+1)(inputsheightkernelsize+1)

  • 可以用padding参数使每个Channels数据大小保持不变,padding = 1 表示增加一圈,就是边缘的两行两列。

  • 卷积(convolution)后,C(Channels)可变可不变(一般都变),W(width)和H(Height)可变可不变,取决于是否padding和kernel的大小。

池化MaxPool2d

torch.nn.MaxPool2d(2)

  • subsampling(或pooling)后,Channels不变,W和H变
    pytorch卷积神经网络(六)_第5张图片

整体流程

pytorch卷积神经网络(六)_第6张图片

代码实现

pytorch卷积神经网络(六)_第7张图片
pytorch卷积神经网络(六)_第8张图片

代码

import torch
from torchvision import transforms
from torchvision import datasets
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch.optim as optim

# 老样子准备数据
batch_size = 64
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])

train_dataset = datasets.MNIST(root=r'D:\code_management\pythonProject\dataset/mnist/', train=True, download=False,
                               transform=transform)
train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size)
test_dataset = datasets.MNIST(root=r'D:\code_management\pythonProject\dataset/dataset/mnist/', train=False,
                              download=False, transform=transform)
test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size)


# 设计神经网络
class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=5)
        self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5)
        self.pooling = torch.nn.MaxPool2d(2)  # 只是用池化stride为2的池化层
        self.fc = torch.nn.Linear(320, 10)
        # 为320的计算过程(根据forward中的值进行)
        # 对于单个图像
        # 1*28*28 ---> 10*24*24 ---> 10*12*12 ---> 20*8*8 ---> 20*4*4 = 320
        # 全连接 : 320 ---> 10

    def forward(self, x):
        # flatten data from (n,1,28,28) to (n, 784)
        # 手写数据集只有一个channels,n为 batch_size
        batch_size = x.size(0)  # 取出batch_size
        x = F.relu(self.pooling(self.conv1(x)))  # 先卷积后池化
        x = F.relu(self.pooling(self.conv2(x)))
        x = x.view(batch_size, -1)  # 为进行全连接做准备,先从三维展成二维矩阵, -1 此处自动算出的是320
        x = self.fc(x)  # 全连接到10维度,一共10种
        return x


model = Net()
# 使用GPU还是CPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)


# 损失与优化方法
criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)


# 训练方法
def train(epoch):
    running_loss = 0.0
    for batch_idx, data in enumerate(train_loader, 0):
        inputs, target = data
        
        inputs, target = inputs.to(device), target.to(device)

        outputs = model(inputs)  # 训练
        loss = criterion(outputs, target)  # 算损失
        optimizer.zero_grad()  # 梯度清零
        loss.backward()  # 反向传播
        optimizer.step()  # 更新优化

        running_loss += loss.item()
        if batch_idx % 300 == 299:
            print('[%d, %5d] loss: %.3f' % (epoch + 1, batch_idx + 1, running_loss / 300))
            running_loss = 0.0


def test():
    correct = 0
    total = 0
    with torch.no_grad():
        for data in test_loader:
            images, labels = data
            images, labels = images.to(device), labels.to(device)
            outputs = model(images)
            _, predicted = torch.max(outputs.data, dim=1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
    print('accuracy on test set: %d %% ' % (100 * correct / total))


if __name__ == '__main__':
    for epoch in range(10):
        train(epoch)
        test()

GoogleNet

卷积核大小为1的操作能通过减小维度较少计算量,但是有信息损失。
pytorch卷积神经网络(六)_第9张图片

  • 16,24表示Channels,注意要保持输出大小width,height保持不变,通过padding和kernelsize大小来保持。

pytorch卷积神经网络(六)_第10张图片

import torch
from torchvision import transforms
from torchvision import datasets
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch.optim as optim

# 老样子准备数据
batch_size = 64
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])

train_dataset = datasets.MNIST(root=r'D:\code_management\pythonProject\dataset/mnist/', train=True, download=False,
                               transform=transform)
train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size)
test_dataset = datasets.MNIST(root=r'D:\code_management\pythonProject\dataset/mnist/', train=False,
                              download=False, transform=transform)
test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size)


# design model using class
class InceptionA(torch.nn.Module):
    """不论输入多少维度,都会以相同的width,height,以及88Channels输出"""

    def __init__(self, in_channels):
        super(InceptionA, self).__init__()
        self.branch1x1 = torch.nn.Conv2d(in_channels, 16, kernel_size=1)  # kernel_size=1数据width,height不变

        self.branch5x5_1 = torch.nn.Conv2d(in_channels, 16, kernel_size=1)  # kernel_size=1数据width,height不变
        self.branch5x5_2 = torch.nn.Conv2d(16, 24, kernel_size=5, padding=2)  # kernel_size=5,加两圈就数据width,height不变

        self.branch3x3_1 = torch.nn.Conv2d(in_channels, 16, kernel_size=1)  # kernel_size=1数据width,height不变
        self.branch3x3_2 = torch.nn.Conv2d(16, 24, kernel_size=3, padding=1)  # kernel_size=3,加1圈就数据width,height不变
        self.branch3x3_3 = torch.nn.Conv2d(24, 24, kernel_size=3, padding=1)  # kernel_size=3,加1圈就数据width,height不变

        self.branch_pool = torch.nn.Conv2d(in_channels, 24, kernel_size=1)  # kernel_size=1数据width,height不变

    def forward(self, x):
        """一共存在四个并列的数据,最后cat合并"""
        branch1x1 = self.branch1x1(x)

        branch5x5 = self.branch5x5_1(x)
        branch5x5 = self.branch5x5_2(branch5x5)

        branch3x3 = self.branch3x3_1(x)
        branch3x3 = self.branch3x3_2(branch3x3)
        branch3x3 = self.branch3x3_3(branch3x3)

        branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
        branch_pool = self.branch_pool(branch_pool)

        outputs = [branch1x1, branch5x5, branch3x3, branch_pool]  # 24*3+16=88,所以88个Channels
        return torch.cat(outputs, dim=1)  # b,c,w,h  c对应的是dim=1


class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=5)
        self.conv2 = torch.nn.Conv2d(88, 20, kernel_size=5)  # 88 = 24x3 + 16

        self.incep1 = InceptionA(in_channels=10)  # 与conv1 中的10对应
        self.incep2 = InceptionA(in_channels=20)  # 与conv2 中的20对应

        self.mp = torch.nn.MaxPool2d(2)
        self.fc = torch.nn.Linear(1408, 10)

    def forward(self, x):
        """数据要是batch_size,Channels,width,height四个维度"""
        batch_size = x.size(0)  # batch_size大小
        x = F.relu(self.mp(self.conv1(x)))  # [batch_size,1,28,28] ---> [batch_size,10,24,24] --->[batch_size,10,12,12] ---> 激活
        x = self.incep1(x)  # [batch_size,10,12,12] ---> [batch_size,88,12,12]
        x = F.relu(self.mp(self.conv2(x)))  # [batch_size,88,12,12] ---> [batch_size,20,8,8] ---> [batch_size,20,4,4] ---> 激活
        x = self.incep2(x)  # [batch_size,20,4,4] ---> [batch_size,88,4,4]
        x = x.view(batch_size, -1)  # [batch_size,88,4,4] ---> [batch_size,88*4*4] == [batch_size,1408] 
        x = self.fc(x)  # 全连接激活 [batch_size,1408] ---> [batch_size,10]
        return x


model = Net()

# 损失和优化
criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)


# 训练
def train(epoch):
    running_loss = 0.0
    for batch_idx, data in enumerate(train_loader, 0):
        inputs, target = data
        optimizer.zero_grad()

        outputs = model(inputs)
        loss = criterion(outputs, target)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        if batch_idx % 300 == 299:
            print('[%d, %5d] loss: %.3f' % (epoch + 1, batch_idx + 1, running_loss / 300))
            running_loss = 0.0


def test():
    correct = 0
    total = 0
    with torch.no_grad():
        for data in test_loader:
            images, labels = data
            outputs = model(images)
            _, predicted = torch.max(outputs.data, dim=1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
    print('accuracy on test set: %d %% ' % (100 * correct / total))


if __name__ == '__main__':
    for epoch in range(10):
        train(epoch)
        test()

ResidualNet残差神经网络

  • 解决梯度消失

残差神经网络链接

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