第8章 使用卷积进行泛化(1)

本章主要内容

1、理解什么是卷积

2、构建卷积神经网络

3、构建自定义的nn.Module的子类

4、模块和函数API之间的区别

5、神经网络的设计选择

1 使用卷积进行泛化

torch.nn模块提供一维、二维、三维的卷积

nn.Conv1d用于时间序列

nn.Conv2d用于图像

nn.Conv3d用于体数据、视频

1.1 加载数据

%matplotlib inline
import torch
import numpy as np
from matplotlib import pyplot as plt
import torch.nn as nn
from torchvision import transforms

from torchvision import datasets
data_path = 'D:\\DeepLearning data\\data\\p1ch7'
cifar10 = datasets.CIFAR10(data_path, train=True, download=True)
cifar10_val = datasets.CIFAR10(data_path, train=False, download=True)

transformed_cifar10 = datasets.CIFAR10(data_path, train=True, download=False, 
                                       transform=transforms.Compose([
                                       transforms.ToTensor(),
                                       transforms.Normalize((0.4914, 0.4822, 0.4465),(0.2470, 0.2435, 0.2616))
                                       ]))
transformed_cifar10_val = datasets.CIFAR10(data_path, train=False, download=False, 
                                       transform=transforms.Compose([
                                       transforms.ToTensor(),
                                       transforms.Normalize((0.4914, 0.4822, 0.4465),(0.2470, 0.2435, 0.2616))
                                       ]))

label_map = {0:0, 2:1} 
class_names = ['airplane','bird']
cifar2 = [(img, label_map[label])
          for img, label in transformed_cifar10 ###修改代码
          if label in [0,2]]

cifar2_val = [(img, label_map[label]) 
              for img, label in transformed_cifar10_val 
              if label in [0,2]]

1.2 卷积介绍

class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)
in_channels 即为[B, C, H, W]中的C,输入张量的channels数;
out_channels 期望的四维输出张量的channels数;
kernel_size 卷积核的大小,一般我们会使用5x5、3x3这种左右两个数相同的卷积核,因此这种情况只需要写kernel_size = 5这样的就行了。
如果左右两个数不同,比如3x5的卷积核,那么写作kernel_size = (3, 5),注意需要写一个tuple,而不能写一个列表(list)
stride=1 卷积核在图像窗口上每次平移的间隔,即所谓的步长。

conv = nn.Conv2d(3, 16, kernel_size=3)
print(conv)
print(conv.weight.shape,conv.bias.shape)

输出:

小栗子:

##举个例子
img, _ = cifar2[0]
output = conv(img.unsqueeze(0))##原本的img是(3,32,32)的,需要添加一个维度 因为conv2d期望输入的是(BxCxHxW).
plt.imshow(img.permute(1,2,0))
plt.show()
print(img.unsqueeze(0).shape,output.shape)
# print(output)
# print(output[0,0])
plt.imshow(output[0,0].detach(),cmap='gray') ###为啥是output[0,0]?
plt.show()

 输出:

我们发现 图像丢失了一些像素。原因是奇数大小的卷积核作用后,会得到width-kernel_size+1的水平和垂直长度(32-3+1)。

注:对于偶数大小的卷积核,需要在上下左右填充不同的数字,但是torch.nn.functional.pad()函数可以处理。但是还是推荐使用奇数的卷积核。

如果需要保持输出图像的大小不变,我们可以使用填充边界(padding)

例如:

##填充边界padding以保证输出图像的大小
conv = nn.Conv2d(3, 1, kernel_size=3,padding=1)
output = conv(img.unsqueeze(0))
print(img.unsqueeze(0).shape,output.shape)
##可见输出图像大小没变  输出的通道数是卷积核中输出通道数

 可见输出图像大小没变  输出的通道数是卷积核中输出通道数。

但是,需要注意的是,并不是只要padding=1输出图像大小就不会变!

稍后举例说明。

为了消除干扰因素,首先把偏置归零,再将权重设为一常数值:

with torch.no_grad():
    conv.bias.zero_()
    
with torch.no_grad():
    conv.weight.fill_(1.0/9.0)

观察其对cifar10图像的影响:

output = conv(img.unsqueeze(0))
plt.imshow(output[0,0].detach(),cmap='gray')
plt.show()

 输出:

 尝试不同的卷积核:

##尝试不同的卷积核
conv = nn.Conv2d(3, 1, kernel_size=3, padding=1)

with torch.no_grad():
    conv.weight[:] = torch.tensor([[-1.0, 0.0, 1.0],
                                   [-1.0, 0.0, 1.0],
                                   [-1.0, 0.0, 1.0]])
    conv.bias.zero_()

output = conv(img.unsqueeze(0))
plt.imshow(output[0,0].detach(),cmap='gray')
plt.show()

2 池化技术

2.1 从大到小:下采样

使用最大池化将输入图像缩小一半:

##使用深度和池化技术进一步研究
#从大到小:下采样
#最大池化
pool = nn.MaxPool2d(2)#核大小为2
output = pool(img.unsqueeze(0))
print(img.unsqueeze(0).shape,output.shape)
#可见图像缩小了一半

输出:

可见图像缩小了一半

2.2 卷积+池化

顺便举例说明一下前边提到的padding

3x3卷积核,padding=1:

#结合卷积和下采样结合
#(1,3,32,32)——>(1,16,32,32)——>(1,16,16,16)——>(1,8,16,16)——>(1,8,8,8)
model = nn.Sequential(
            nn.Conv2d(3, 16, kernel_size=3, padding=1),##图像输出大小不会变,通道数变为16
            nn.Tanh(),
            nn.MaxPool2d(2),##图像大小减半,通道数不变
            nn.Conv2d(16, 8, kernel_size=3, padding=1),##图像大小不变,通道数变为8
            nn.Tanh(),
            nn.MaxPool2d(2)#图像大小减半,通道数不变
            )
output = model(img.unsqueeze(0))
print(img.unsqueeze(0).shape,output.shape)

可见padding操作确实保证了输出图像的大小。

但是,我们改变卷积核大小为5x5(练习题也会用到)

model = nn.Sequential(
            nn.Conv2d(3, 16, kernel_size=5, padding=1),##图像输出大小不会变,通道数变为16
            nn.Tanh(),
            nn.MaxPool2d(2),##图像大小减半,通道数不变
            nn.Conv2d(16, 8, kernel_size=5, padding=1),##图像大小不变,通道数变为8
            nn.Tanh(),
            nn.MaxPool2d(2)#图像大小减半,通道数不变
            )
output = model(img.unsqueeze(0))
print(img.unsqueeze(0).shape,output.shape)

输出:

我们发现输出图像的大小并没有保持不变。

这里看的不是很清楚,输出每一步的图像大小看看~

首先是3x3卷积核:

conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1)
pool1 = nn.MaxPool2d(2)
conv2 = nn.Conv2d(16, 8, kernel_size=3, padding=1)
pool2 = nn.MaxPool2d(2)
output1 = conv1(img.unsqueeze(0))
print(output1.shape)
output2 = pool1(output1)
print(output2.shape)
output3 = conv2(output2)
print(output3.shape)
output4 = pool1(output3)
print(output4.shape)

输出:

5x5卷积核:

###5x5卷积核对图片尺寸的影响
conv1 = nn.Conv2d(3, 16, kernel_size=5, padding=1)
pool1 = nn.MaxPool2d(2)
conv2 = nn.Conv2d(16, 8, kernel_size=5, padding=1)
pool2 = nn.MaxPool2d(2)
output1 = conv1(img.unsqueeze(0))
print(output1.shape)
output2 = pool1(output1)
print(output2.shape)
output3 = conv2(output2)
print(output3.shape)
output4 = pool1(output3)
print(output4.shape)

输出:

这就不得不谈一谈卷积核和padding操作对于图像尺寸大小的影响了。放上链接:

CNN中卷积核大小、池化以及padding对输入图像大小的影响_Cary.的博客-CSDN博客我们发现在不使用padding操作时,经过卷积操作后,输出图像比输入图像小一点。为保证输出图像的大小不变,我们可以使用padding操作:conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1)pool1 = nn.MaxPool2d(2)conv2 = nn.Conv2d(16, 8, kernel_size=3, padding=1)pool2 = nn.MaxPool2d(2)output1 = conv1(img.unsqueeze(https://blog.csdn.net/weixin_45985148/article/details/124765912

2.3 整合网络

##将一个8通道,8x8的图像转换为一个一维向量:
model = nn.Sequential(
            nn.Conv2d(3, 16, kernel_size=3, padding=1),##图像输出大小不会变,通道数变为16
            nn.Tanh(),
            nn.MaxPool2d(2),##图像大小减半,通道数不变
            nn.Conv2d(16, 8, kernel_size=3, padding=1),##图像大小不变,通道数变为8
            nn.Tanh(),
            nn.MaxPool2d(2),#图像大小减半,通道数不变
            #...     警告:这里缺失了一些重要东西!!!
            nn.Linear(8*8*8,32),
            nn.Tanh(),
            nn.Linear(32,2)
            )
model(img.unsqueeze(0))  ###肯定会报错
#这里缺少的是从8通道,8*8图像转换为有512个元素的一维向量的步骤,pytorch1.3后便可用nn.Flatten()

查看报错信息:

这里缺少的是从8通道,8*8图像转换为有512个元素的一维向量的步骤,pytorch1.3后便可用nn.Flatten()进行转化。

2.4 子类化nn.Module

将我们的网络作为第一个nn.Module,再用forward()方法:

import torch.optim as optim
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1)
        self.act1 = nn.Tanh()
        self.pool1 = nn.MaxPool2d(2)
        self.conv2 = nn.Conv2d(16, 8, kernel_size=3, padding=1)
        self.act2 = nn.Tanh()
        self.pool2 = nn.MaxPool2d(2)
        self.fc1 = nn.Linear(8*8*8,32)
        self.act3 = nn.Tanh()
        self.fc2 = nn.Linear(32,2)
        
    def forward(self,x):
        out = self.pool1(self.act1(self.conv1(x)))
        out = self.pool2(self.act2(self.conv1(out)))
        out = out.view(-1,8*8*8)
        out = self.act3(self.fc1(out))
        out = self.fc2(out)
        return out

实例化model并查看模型中的参数:

model = Net()

numel_list = [p.numel() for p in model.parameters()]
print(sum(numel_list),numel_list)

同样,我们也可以使用函数式的API进行编写:

##函数式API
import torch.nn.functional as F
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1)
        self.conv2 = nn.Conv2d(16, 8, kernel_size=3, padding=1)
        self.fc1 = nn.Linear(8*8*8, 32)
        self.fc2 = nn.Linear(32, 2)
        
    def forward(self,x):
        out = F.max_pool2d(torch.tanh(self.conv1(x)),2)
        out = F.max_pool2d(torch.tanh(self.conv2(out)),2)
        out = out.view(-1,8*8*8)
        out = torch.tanh(self.fc1(out))
        out = self.fc2(out)
        return out

检查模型是否可行:

##检查模型是否可以运行:
model = Net()
print(model(img.unsqueeze(0))) 

sum(p.numel() for p in model.parameters())

输出:

可见,两者效果是一样的。 下一部分主要是前一章数据集及识别任务的模型构建及训练。

猜你喜欢

转载自blog.csdn.net/weixin_45985148/article/details/124763853