CNN卷积神经网络原理详解

🎙️ 语音朗读 当前: 晓晓 (温柔女声)

CNN卷积神经网络原理详解

卷积神经网络(Convolutional Neural Network,CNN)是深度学习中最成功的架构之一,尤其在计算机视觉领域取得了突破性的成果。

卷积操作

卷积是CNN的核心操作,通过卷积核在输入特征图上滑动,提取局部特征:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import numpy as np

def conv2d(input_matrix, kernel, stride=1, padding=0):
"""手动实现二维卷积操作"""
if padding > 0:
input_matrix = np.pad(input_matrix, padding, mode='constant')

h, w = input_matrix.shape
kh, kw = kernel.shape
oh = (h - kh) // stride + 1
ow = (w - kw) // stride + 1

output = np.zeros((oh, ow))
for i in range(oh):
for j in range(ow):
region = input_matrix[i*stride:i*stride+kh, j*stride:j*stride+kw]
output[i, j] = np.sum(region * kernel)
return output

# 示例:使用边缘检测卷积核
input_img = np.random.randn(6, 6)
edge_kernel = np.array([[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]])
output = conv2d(input_img, edge_kernel)
print(f"输入尺寸: {input_img.shape}, 输出尺寸: {output.shape}")

CNN的核心组件

1. 卷积层(Convolutional Layer)

卷积层通过可学习的卷积核提取特征。关键参数包括:

  • 卷积核大小(Kernel Size):通常使用3×3或5×5
  • 步长(Stride):卷积核每次移动的像素数
  • 填充(Padding):在输入边缘补零,控制输出尺寸

2. 池化层(Pooling Layer)

池化层用于降低特征图的空间维度,减少参数量和计算量:

1
2
3
4
5
6
7
8
9
10
11
12
13
def max_pool2d(input_matrix, pool_size=2, stride=2):
"""最大池化操作"""
h, w = input_matrix.shape
oh = h // stride
ow = w // stride
output = np.zeros((oh, ow))

for i in range(oh):
for j in range(ow):
region = input_matrix[i*stride:i*stride+pool_size,
j*stride:j*stride+pool_size]
output[i, j] = np.max(region)
return output

3. 全连接层(Fully Connected Layer)

全连接层将提取的特征映射到最终输出空间,通常用于分类任务。

经典CNN架构

LeNet-5

LeNet-5是最早的CNN架构之一,由Yann LeCun于1998年提出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import torch
import torch.nn as nn

class LeNet5(nn.Module):
def __init__(self, num_classes=10):
super(LeNet5, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 6, kernel_size=5, padding=2),
nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Conv2d(6, 16, kernel_size=5),
nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2, stride=2)
)
self.classifier = nn.Sequential(
nn.Linear(16 * 5 * 5, 120),
nn.Sigmoid(),
nn.Linear(120, 84),
nn.Sigmoid(),
nn.Linear(84, num_classes)
)

def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x

感受野与特征层次

CNN的一个重要特性是层次化的特征提取:

  • 浅层:提取边缘、纹理等低级特征
  • 中层:提取部件、形状等中级特征
  • 深层:提取语义、对象等高级特征

1×1卷积的作用

1×1卷积看似简单,但有着重要的作用:

  1. 实现跨通道信息的组合与交互
  2. 进行降维或升维,减少计算量
  3. 增加非线性表达

用PyTorch实现图像分类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms

# 数据预处理
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])

train_dataset = datasets.MNIST('./data', train=True, download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)

# 定义模型
model = LeNet5(num_classes=10)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

# 训练
for epoch in range(10):
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
print(f'Epoch {epoch+1}, Loss: {loss.item():.4f}')

总结

CNN通过卷积操作的局部连接和权值共享,大幅减少了参数量,同时保持了空间局部性。从LeNet到现代的ResNet、EfficientNet,CNN架构不断演进,但其核心原理始终不变。理解卷积、池化和反向传播是掌握CNN的关键。

© 2019-2026 ovo$^{mc^2}$ All Rights Reserved. | 站点总访问 28969 次 | 访客 19045
Theme by hiero