CNN 卷积神经网络处理图片任务 | PyTorch 深度学习实战

前一篇文章,学习率调整策略 | PyTorch 深度学习实战

本系列文章 GitHub Repo: https://github.com/hailiang-wang/pytorch-get-started

CNN 卷积神经网络

CNN

什么是卷积

【通信原理 入坑之路】------深入、详细地理解通信里面"卷积"概念

卷积,首先是一种数学运算。两个多项式通过滑动,求解多项式参数。


深度学习的卷积概念,就是借鉴了通信领域使用了卷积。跨学科运用知识,一直是大牛们的惯用手段。掌握人类已经精通的领域的经验,然后推广到前沿领域。

工作原理

利用卷积操作实现平移、扭曲情况下,依然能识别特征

图片是一个二维数据,如果只是利用全连接网络,那么数据的二维特征就丢失了,原始的物理信息丢失了。比如,同一个人出现在不同的照片中,很可能是在不同的位置,作为同样的一张人脸,当其出现在图片中的不同位置[1](#1),都可以正确的识别和分类呢?

深度学习的卷积运算

深度学习领域的卷积,参考文章

卷积核是一个小矩阵,在输入矩阵上,滑动。

最终得到一个新的 output 矩阵。

提取特征

因为这种运算,Output 实际上代表了卷积核 Kernel 作用于 Input 后过滤出来的特征。每一个卷积核,就是一个过滤器,从源图片中,提取特定的形状。为了理解这一点,看下面这张图。

以黑白两个颜色,实现卷积运算,最终输入图片里和特征核(Single filter)重叠的部分得到了加强,和特征核不一致的部分得到了抑制。

不同特征核的效果比较

当特征核变大,增加多个特征提取器,那么就可以识别一张图片上的特征组,从而判定图片中包含的物体的分类。

  • 左侧是运算符,中间是对应的特征核,右侧是输出的图片



当然,计算机不是【看图】,而是通过卷积后的矩阵,从数字上去检查分类。当输出的矩阵组成一个全连接,使用目标的标注数据,计算出损失,就可以学习分类的权重,实现分类的效果。

卷积核

卷积核,也称为特征提取器,后者的名字更加的形象,特征提取器类似于通信领域的滤波器。

感受野

感受野(Receptive Field)的定义是卷积神经网络每一层输出的特征图(feature map)上的像素点在输入图片上映射的区域大小。参考文章

共享权重

使用同一个特征核过滤图片,也就是一个特征核对于一个图片上的多个感受野,特征核的矩阵不变。

使用梯度下降原理更新参数时,参数包括了每个卷积核,虽然一个卷积核是滑动在多个感受野得到输出矩阵的,但是特征核更新时,不会针对单独的某个感受野。

对于一个卷积神经网络,都包括哪些参数,参考文章

池化

经过多个卷积核以后,维度更多,虽然因为保留了重要的特征信息,但是会远远的大于分类信息,在加入最后的全连接层之前,还需要浓缩一下信息,类似于结晶。

这个操作就是池化,比如常用的最大池化,方法如下:

示例源码

下面以一段 PyTorch 代码为例,使用卷积神经网络完成图片分类任务。

复制代码
'''
CNN Model
'''
import torch
import torchvision.datasets as ds
import torchvision.transforms as ts
from torch.utils.data import DataLoader
from torch.autograd import Variable
import random

torch.manual_seed(777)# reproducibility

# parameters
batch_size=100
learning_rate=0.001
epochs=2

# MNIST dataset
ds_train=ds.MNIST(root='../../../DATA/MNIST_data',
                  train=True,
                  transform=ts.ToTensor(),
                  download=True)
ds_test=ds.MNIST(root='../../../DATA/MNIST_data',
                 train=False,
                 transform=ts.ToTensor(),
                 download=True)
# dataset loader
dl=DataLoader(dataset=ds_train,batch_size=batch_size,shuffle=True)

# CNN Model (2 conv layers)
class CNN(torch.nn.Module):
    def __init__(self):
        super(CNN,self).__init__()
        # L1 ImgIn shape=(?, 28, 28, 1)
        #    Conv     -> (?, 28, 28, 32)
        #    Pool     -> (?, 14, 14, 32)
        self.layer1=torch.nn.Sequential(
            torch.nn.Conv2d(1,32,kernel_size=3,stride=1,padding=1),#padding=1进行0填充
            torch.nn.ReLU(),
            torch.nn.MaxPool2d(kernel_size=2,stride=2)
        )
        # L2 ImgIn shape=(?, 14, 14, 32)
        #    Conv      ->(?, 14, 14, 64)
        #    Pool      ->(?, 7, 7, 64)
        self.layer2=torch.nn.Sequential(
            torch.nn.Conv2d(32,64,kernel_size=3,stride=1,padding=1),
            torch.nn.ReLU(),
            torch.nn.MaxPool2d(kernel_size=2,stride=2)
        )
        # Final FC 7x7x64 inputs -> 10 outputs
        self.fc=torch.nn.Linear(7*7*64,10)
        torch.nn.init.xavier_uniform(self.fc.weight)
    def forward(self,x):
        out=self.layer1(x)
        out=self.layer2(out)
        out=out.view(out.size(0),-1)# Flatten them for FC
        out=self.fc(out)
        return out

# instantiate CNN model
model=CNN()

# define cost/loss & optimizer
criterion=torch.nn.CrossEntropyLoss()# Softmax is internally computed.
optimizer=torch.optim.Adam(model.parameters(),lr=learning_rate)

# train my model
print('Learning started. It takes sometime.')
for epoch in range(epochs):
    avg_cost=0
    total_batch=len(ds_train)//batch_size
    for step,(batch_xs,batch_ys) in enumerate(dl):
        x=Variable(batch_xs)#[100, 1, 28, 28] image is already size of (28x28), no reshape
        y=Variable(batch_ys)#[100] label is not one-hot encoded

        optimizer.zero_grad()
        h=model(x)
        cost=criterion(h,y)
        cost.backward()
        optimizer.step()

        avg_cost+=cost/total_batch
    print(epoch+1,avg_cost.item())
print('Learning Finished!')

# Test model and check accuracy
model.eval()#!!将模型设置为评估/测试模式 set the model to evaluation mode (dropout=False)

# x_test=ds_test.test_data.view(len(ds_test),1,28,28).float()
x_test=ds_test.test_data.view(-1,1,28,28).float()
y_test=ds_test.test_labels

pre=model(x_test)

print("pre.data=")
print(pre.data)
print("*"*3)

pre=torch.max(pre.data,1)[1].float()
acc=(pre==y_test.data.float()).float().mean()
print("acc", acc)

r=random.randint(0,len(x_test)-1)
x_r=x_test[r:r+1]
y_r=y_test[r:r+1]
pre_r=model(x_r)

# IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
# https://discuss.pytorch.org/t/indexerror-dimension-out-of-range-expected-to-be-in-range-of-1-0-but-got-1/54267/12
print("pre_r.data=")
print(pre_r.data)
print("*"*3)

pre_r=torch.max(pre_r.data,-1)[1].float()
print('pre_r')
print(pre_r)

acc_r=(pre_r==y_r.data).float().mean()
print(acc_r)

  1. 图片相关任务,包括图片分类、物体检测、实例分割、目标跟踪等。这些任务有不同的功能,但是都依赖于图片中包含的特征,这些特征都是可能平移、变幻、扭曲的。 ↩︎
相关推荐
惯导马工1 天前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
隐语SecretFlow2 天前
国人自研开源隐私计算框架SecretFlow,深度拆解框架及使用【开发者必看】
深度学习
Billy_Zuo3 天前
人工智能深度学习——卷积神经网络(CNN)
人工智能·深度学习·cnn
羊羊小栈3 天前
基于「YOLO目标检测 + 多模态AI分析」的遥感影像目标检测分析系统(vue+flask+数据集+模型训练)
人工智能·深度学习·yolo·目标检测·毕业设计·大作业
l12345sy3 天前
Day24_【深度学习—广播机制】
人工智能·pytorch·深度学习·广播机制
IT古董3 天前
【第五章:计算机视觉-项目实战之图像分类实战】1.经典卷积神经网络模型Backbone与图像-(4)经典卷积神经网络ResNet的架构讲解
人工智能·计算机视觉·cnn
九章云极AladdinEdu3 天前
超参数自动化调优指南:Optuna vs. Ray Tune 对比评测
运维·人工智能·深度学习·ai·自动化·gpu算力
研梦非凡3 天前
ICCV 2025|从粗到细:用于高效3D高斯溅射的可学习离散小波变换
人工智能·深度学习·学习·3d
通街市密人有3 天前
IDF: Iterative Dynamic Filtering Networks for Generalizable Image Denoising
人工智能·深度学习·计算机视觉
智数研析社3 天前
9120 部 TMDb 高分电影数据集 | 7 列全维度指标 (评分 / 热度 / 剧情)+API 权威源 | 电影趋势分析 / 推荐系统 / NLP 建模用
大数据·人工智能·python·深度学习·数据分析·数据集·数据清洗