(1)下采样目的:减少数据量,降低运算

下采样时通道数不变,高度和宽度发生变化

卷积和下采样统称为特征提取,即通过卷积运算找到某种特征;全连接网络做分类

(2)卷积:

  1> 明确输入输出的张量维度

  2> 输入的通道数和卷积核的通道数相同

  3> 卷积核的总数和输出通道的个数相同

CNN卷积计算公式高宽 cnn的卷积计算_深度学习

 (3)卷积核为3x3的单通道卷积运算:

CNN卷积计算公式高宽 cnn的卷积计算_卷积核_02

(4)三通道卷积运算,最左边输入的红绿蓝组成一个patch,3x5x5(3为通道数C,5为宽度W,5为高度H)和3x3x3(CxWxH)的卷积核做运算,最终输出结果为1x3x3(CxWxH)

CNN卷积计算公式高宽 cnn的卷积计算_卷积核_03

 结论:1> 输入的通道数和卷积核的通道数相同

            2> 卷积核的总数和输出通道的个数相同

 (5)卷积运算代码测试:

import torch
in_channels, out_channels= 5, 10
width, height = 100, 100
kernel_size = 3
batch_size = 1

#torch.randn:用来生成随机数字的tensor,这些随机数字满足标准正态分布(0~1)
#torch.randn(size),size可以是一个整数,也可以是一个元组。
input = torch.randn(batch_size,
                    in_channels,
                    width,
                    height)
#也可以用长方形的卷积核,用元组,大部分用奇数
conv_layer = torch.nn.Conv2d(in_channels,
                             out_channels,
                             kernel_size=kernel_size)
output = conv_layer(input)

print(input.shape)
print(output.shape)
print(conv_layer.weight.shape)

输出结果:

CNN卷积计算公式高宽 cnn的卷积计算_深度学习_04

 (6)Padding

   1> 3x3的卷积核,Padding=1时外层添加1圈0,比如输入为5x5,添加一圈0后变为7x7

CNN卷积计算公式高宽 cnn的卷积计算_CNN卷积计算公式高宽_05

   2> 5x5的卷积核,一般Padding=2

   3> kxk的卷积核,Padding=k/2

(7)padding代码测试:

'''
  Padding
'''
import  torch
input = [3,4,6,5,7,
         2,4,6,8,2,
         1,6,7,8,4,
         9,7,4,6,2,
         3,7,5,4,1]
input = torch.Tensor(input).view(1, 1, 5, 5)
conv_layer = torch.nn.Conv2d(1, 1, kernel_size=3, padding=1, bias=False)
kernel = torch.Tensor([1,2,3,4,5,6,7,8,9]).view(1,1,3,3)
#卷积层权重初始化
conv_layer.weight.data = kernel.data

output = conv_layer(input)
print(output)

输出结果:

CNN卷积计算公式高宽 cnn的卷积计算_卷积核_06

(8)步长stride:stride=2,表示卷积时从第一步到第二步需要在input中走两步

CNN卷积计算公式高宽 cnn的卷积计算_深度学习_07

CNN卷积计算公式高宽 cnn的卷积计算_CNN卷积计算公式高宽_08

 

CNN卷积计算公式高宽 cnn的卷积计算_深度学习_09

 

CNN卷积计算公式高宽 cnn的卷积计算_深度学习_10

(9)stride代码测试: 

'''
   stride=2下一个卷积的时候坐标+2
   改变stride可以降低图像的宽度、高度
'''
import  torch
input = [3,4,6,5,7,
         2,4,6,8,2,
         1,6,7,8,4,
         9,7,4,6,2,
         3,7,5,4,1]
input = torch.Tensor(input).view(1, 1, 5, 5)
conv_layer = torch.nn.Conv2d(1, 1, kernel_size=3, stride=2, bias=False)
kernel = torch.Tensor([1,2,3,4,5,6,7,8,9]).view(1,1,3,3)
#卷积层权重初始化
conv_layer.weight.data = kernel.data

output = conv_layer(input)
print(output)

 输出结果:

CNN卷积计算公式高宽 cnn的卷积计算_CNN卷积计算公式高宽_11

(10)MaxPooling:最大池化层,kernel_size设置为多少,步长stride是多少,每个小块内只取最大的数字,再舍弃其他节点后,保持原有的平面结构得出output

MaxPooling和卷积核的操作区别:池化作用于图像中不重合的区域

CNN卷积计算公式高宽 cnn的卷积计算_深度学习_12

 (11)MaxPooling代码测试:

'''
   下采样的一种:最大池化层Maxpooling,没有权重
   通道数量不变,图像大小变化
'''
import  torch
input = [3,4,6,5,
         2,4,6,8,
         1,6,7,5,
         9,7,4,6,]
input = torch.Tensor(input).view(1,1,4,4)
#kernel_size=2对maxpooling来说stride也被设置为2
maxpooling_layer = torch.nn.MaxPool2d(kernel_size=2)

output = maxpooling_layer(input)
print(output)

输出结果:

CNN卷积计算公式高宽 cnn的卷积计算_神经网络_13

(12)MNIST数据集,用卷积神经网络在GPU中计算完整代码:

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([
    # convert the PIL Image to tensor,单通道变为多通道
    transforms.ToTensor(),
    #数据标准化,切换到(0.1)分布,均值mean和标准差std,对MNIST所有像素值计算的结果
    transforms.Normalize((0.1307, ), (0.3081, ))
])

train_dataset = datasets.MNIST(root='./mnist/',
                               train=True,
                               download=True,
                               transform=transform)
train_loader = DataLoader(dataset=train_dataset,
                          shuffle=True,
                          batch_size=batch_size)

test_dataset = datasets.MNIST(root='./mnist/',
                               train=False,
                               download=True,
                               transform=transform)
test_loader = DataLoader(dataset=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)
        self.fc = torch.nn.Linear(320, 10)

    def forward(self, x):
        batch_size = x.size(0)
        x = F.relu(self.pooling(self.conv1(x)))
        x = F.relu(self.pooling(self.conv2(x)))
        x = x.view(batch_size, -1)
        x = self.fc(x)
        return x

model = Net()
#把模型迁移到GPU上
device = torch.device("cuda:0"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)
        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:
            inputs, target = data
            inputs, target = inputs.to(device), target.to(device)
            outputs = model(inputs)
            _, predicted = torch.max(outputs.data, dim=1)
            total += target.size(0)
            correct += (predicted == target).sum().item()
    print('Accuracy on test set: %d %% [%d/%d]' % (100 * correct / total, correct, total))

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

输出结果:

CNN卷积计算公式高宽 cnn的卷积计算_卷积核_14