第 7 课
← 返回系列列表

Course 4:卷积神经网络基础

Deep Learning Specialization — 深度学习专项课程

卷积运算、Padding、Stride、Pooling 等 CNN 核心组件。

Course 4:卷积神经网络基础

课程简介

卷积运算、Padding、Stride、Pooling 等 CNN 核心组件。

🎬 本课程视频:Deep Learning Specialization — 深度学习专项课程


一、卷积神经网络基础

卷积神经网络(CNN)是计算机视觉领域最重要的突破。全连接网络处理图像有两个致命问题:参数太多(一张1000×1000的彩色图像有300万输入),缺乏空间不变性。

1.1 边缘检测

垂直边缘检测滤波器(3×3):

$$G_x = \begin{bmatrix} 1 & 0 & -1 \ 1 & 0 & -1 \ 1 & 0 & -1 \end{bmatrix}$$

滤波器左侧覆盖亮区域、右侧暗区域时输出大的正值→检测到从亮到暗的垂直边缘。

水平边缘检测滤波器:

$$G_y = \begin{bmatrix} 1 & 1 & 1 \ 0 & 0 & 0 \ -1 & -1 & -1 \end{bmatrix}$$

1.2 卷积操作的数学定义

输入尺寸$(n_H, n_W)$,滤波器尺寸$(f, f)$,输出尺寸:$(n_H - f + 1) \times (n_W - f + 1)$

$$(I * K)(i, j) = \sum_{a=0}^{f-1}\sum_{b=0}^{f-1} I(i+a, j+b) \cdot K(a, b)$$

1.3 Padding(填充)

Valid卷积(无填充):输出尺寸$(n_H - f + 1) \times (n_W - f + 1)$
Same卷积:填充$p = (f-1)/2$,输入输出尺寸相同

通用公式(含填充$p$和步长$s$):

$$\left\lfloor \frac{n_H + 2p - f}{s} + 1 \right\rfloor \times \left\lfloor \frac{n_W + 2p - f}{s} + 1 \right\rfloor$$

1.4 三维卷积

输入尺寸:$(n_H, n_W, n_C)$,滤波器尺寸:$(f, f, n_C)$,输出单个特征图。

使用多个滤波器得到多通道输出:

$$Z^{[l]} = W^{[l]} * A^{[l-1]} + b^{[l]}$$

$W^{[l]}$维度:$(f, f, n_C^{[l-1]}, n_C^{[l]})$

1.5 池化层

最大池化:在每个$f \times f$区域内取最大值。最常用,保留最激活的特征。

平均池化:取平均值。池化层没有需要学习的参数。

1.6 卷积层的优势

  1. 参数共享:同一滤波器在整张图像上滑动,参数全图共享。3×3×3滤波器仅27个参数。
  2. 稀疏连接:每个输出像素只与输入的一个局部区域相连,符合生物视觉系统结构。

1.7 简单CNN实现

import numpy as np

class ConvLayer:
    def __init__(self, num_filters, filter_size, in_channels):
        self.num_filters = num_filters
        self.filter_size = filter_size
        scale = np.sqrt(2.0 / (filter_size * filter_size * in_channels))
        self.filters = np.random.randn(filter_size, filter_size, in_channels, num_filters) * scale
        self.bias = np.zeros((1, 1, 1, num_filters))

    def forward(self, X):
        batch, h, w, c = X.shape
        f = self.filter_size
        out_h = h - f + 1
        out_w = w - f + 1
        out = np.zeros((batch, out_h, out_w, self.num_filters))
        for i in range(out_h):
            for j in range(out_w):
                region = X[:, i:i+f, j:j+f, :, np.newaxis]  # (batch, f, f, c, 1)
                out[:, i, j, :] = np.sum(region * self.filters[np.newaxis, :, :, :, :], axis=(1,2,3))
        return out

# 示例
X = np.random.randn(1, 28, 28, 3)
conv = ConvLayer(8, 3, 3)
out = conv.forward(X)
print(f"输入: {X.shape} -> 输出: {out.shape}")

1.8 LeNet-5架构

LeNet-5 (1998, Yann LeCun) 是首个成功应用的CNN,用于手写数字识别:
- 输入:32×32灰度图
- Conv1: 6个5×5滤波器 → 28×28×6
- Pool1: 2×2平均池化 → 14×14×6
- Conv2: 16个5×5滤波器 → 10×10×16
- Pool2: 2×2平均池化 → 5×5×16
- FC1: 120 → FC2: 84 → Output: 10 (Softmax)

延伸阅读

← Course 3:机器学习策略(下) Course 4:经典 CNN 架构 →