什么是卷积
卷积(Convolution)是一种数学运算,在图像处理中,通过卷积核(filter)扫描图像,提取局部特征。
卷积的工作原理
卷积操作示意
# 输入图像(5x5)
Input:
[[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]]
# 3x3 卷积核
Kernel:
[[1, 0, -1],
[1, 0, -1],
[1, 0, -1]]
# 卷积结果(边缘检测)
Output: 3x3 特征图
卷积层的关键参数
| 参数 | 说明 | 作用 |
|---|---|---|
| in_channels | 输入通道数 | RGB 图像为 3 |
| out_channels | 输出通道数 | 卷积核数量 |
| kernel_size | 卷积核大小 | 常用 3x3, 5x5 |
| stride | 步长 | 卷积核移动距离 |
| padding | 填充 | 保持输出尺寸 |
PyTorch 卷积层
import torch
import torch.nn as nn
# 定义卷积层
conv = nn.Conv2d(
in_channels=3, # RGB 3通道
out_channels=16, # 16个卷积核
kernel_size=3, # 3x3 卷积核
stride=1, # 步长为1
padding=1 # 填充1像素
)
# 输入图像:批量大小4,3通道,32x32
x = torch.randn(4, 3, 32, 32)
# 卷积操作
output = conv(x)
print(f"Input: {x.shape}") # torch.Size([4, 3, 32, 32])
print(f"Output: {output.shape}") # torch.Size([4, 16, 32, 32])
# 查看卷积核权重
print(f"Weight: {conv.weight.shape}") # torch.Size([16, 3, 3, 3])
池化层
池化(Pooling)用于降采样,减少特征图尺寸和参数数量。
最大池化(MaxPool)
取区域内的最大值
特点:保留显著特征
平均池化(AvgPool)
取区域内的平均值
特点:平滑特征
# 最大池化
maxpool = nn.MaxPool2d(kernel_size=2, stride=2)
x = torch.randn(4, 16, 32, 32)
output = maxpool(x)
print(output.shape) # torch.Size([4, 16, 16, 16])
# 平均池化
avgpool = nn.AvgPool2d(kernel_size=2, stride=2)
output = avgpool(x)
print(output.shape) # torch.Size([4, 16, 16, 16])
简单的 CNN 模型
import torch.nn as nn
class SimpleCNN(nn.Module):
def __init__(self, num_classes=10):
super(SimpleCNN, self).__init__()
# 卷积层
self.conv1 = nn.Conv2d(1, 32, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
# 池化层
self.pool = nn.MaxPool2d(2, 2)
# 全连接层
self.fc1 = nn.Linear(64 * 7 * 7, 128)
self.fc2 = nn.Linear(128, num_classes)
# 激活函数和 Dropout
self.relu = nn.ReLU()
self.dropout = nn.Dropout(0.5)
def forward(self, x):
# 第一个卷积块
x = self.pool(self.relu(self.conv1(x))) # 28x28 -> 14x14
# 第二个卷积块
x = self.pool(self.relu(self.conv2(x))) # 14x14 -> 7x7
# 展平
x = x.view(x.size(0), -1) # 64*7*7 = 3136
# 全连接层
x = self.dropout(self.relu(self.fc1(x)))
x = self.fc2(x)
return x
# 创建模型
model = SimpleCNN(num_classes=10)
# 测试
x = torch.randn(4, 1, 28, 28) # MNIST 图像
output = model(x)
print(f"Output shape: {output.shape}") # torch.Size([4, 10])