前言
本文为8月22日计算机视觉理论学习笔记——CNN,分为三个章节:
- 尺寸计算;
- 反向传播;
- 实例。
一、尺寸计算
- W = W − s i z e + 2 ∗ p a d d i n g s t r i d e + 1 W = \frac{W - size + 2 * padding}{stride + 1} W=stride+1W−size+2∗padding;
- H = H − s i z e + 2 ∗ p a d d i n g s t r i d e + 1 H = \frac{H - size + 2 * padding}{stride + 1} H=stride+1H−size+2∗padding;
- D = o u t p u t n u m b e r D = output\ number D=output number.
二、反向传播
- a l a^l al:第 l l l 层的输出, a l = σ ( z l ) a^l=\sigma(z^l) al=σ(zl);
- z l = w l a l + b l z^l = w^la^l + b^l zl=wlal+bl;
- C C C 为 loss function;
- δ l \delta^l δl 为第 l l l 层的残差。
1、池化层的误差反向传播
假设第
l
−
1
l-1
l−1 层为卷积层,第
l
l
l 层为池化层,池化层的残差为
δ
j
l
\delta^l_j
δjl,卷积层的残差为
δ
j
l
−
1
\delta^{l-1}_j
δjl−1,有:
δ
j
l
−
1
=
u
p
s
a
m
p
l
e
(
δ
j
l
)
⊙
σ
′
(
z
j
l
−
1
)
\delta^{l-1}_j = upsample(\delta^l_j) \odot \sigma'(z^{l-1}_j)
δjl−1=upsample(δjl)⊙σ′(zjl−1)
其中,
σ
′
(
z
j
l
−
1
)
\sigma'(z^{l-1}_j)
σ′(zjl−1) 为第
l
−
1
l-1
l−1 层第
j
j
j 个节点处激励函数的导数,
⊙
\odot
⊙ 表示对应位置元素相乘。
假设池化后的残差如图:
(1)、mean-pooling 层反向传播步骤
- 得到的卷积层应为 4×4 大小:
- 由于需要满足反向传播时各层间残差总和不变,所以卷积层对应每个值需要平摊——除以 pooling 区域大小(2×2=4):
(2)、max-pooling 层反向传播步骤
- 记录前向传播过程中 pooling 区域中最大值的位置;
- 假设 1,3,2,4 对应的区域位置分别为右下、右上、左上、坐下。
2、卷积层的误差反向传播
- 卷积层运算:
- 步骤:
- 先计算 δ l − 1 \delta^{l-1} δl−1;
- a l − 1 = σ ( z l − 1 ) a^{l-1} = \sigma(z^{l-1}) al−1=σ(zl−1) 为本层的输入;
- 根据链式法则:
δ l − 1 = ∂ C ∂ z l − 1 = ∂ C ∂ z l z l ∂ a l − 1 ∂ a l − 1 ∂ z l − 1 = δ l ∂ z l ∂ a l − 1 ⊙ σ ′ ( z l − 1 ) \delta^{l-1} = \frac{\partial C}{\partial z^{l-1}} = \frac{\partial C}{\partial z^l} \frac{z^l}{\partial a^{l-1}} \frac{\partial a^{l-1}}{\partial z^{l-1}} =\delta ^l \frac{\partial z^l}{\partial a^{l-1}} \odot \sigma '(z^{l-1}) δl−1=∂zl−1∂C=∂zl∂C∂al−1zl∂zl−1∂al−1=δl∂al−1∂zl⊙σ′(zl−1)
又,
z l = w l a l + b l z^l = w^l a^l + b^l zl=wlal+bl
所以,
δ l − 1 = W l T δ t ⊙ σ ′ ( z l − 1 ) \delta^{l-1} = W^{lT} \delta^t \odot \sigma'(z^{l-1}) δl−1=WlTδt⊙σ′(zl−1)
三、实例
代码如下:
from __future__ import division, print_function, absolute_import
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np
# print(tf.__path__)
# 导入 MNIST 数据集
from tensorflow.examples.tutorials import input_data
mnist = tf.keras.datasets.mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# 定义超参数
learning_rate = 0.001
num_steps = 2000
batchsz = 128
# 定义网络参数
num_input = 784 # MNIST数据输入 (img shape: 28*28)
num_classes = 10 # MNIST所有类别 (0-9 digits)
dropout = 0.75 # 保留神经元的概率
# 创建深度神经网络的结构
def conv_net(x_dict, n_classes, dropout, reuse, is_training):
# 确定命名空间
with tf.variable_scope('Convnet', reuse=reuse): # 可以让变量有相同的命名
# TF Estimator类型的输入为像素
x = x_dict['image']
# MNIST数据输入格式为一位向量,包含784个特征 (28*28像素)
# 用reshape函数改变形状以匹配图像的尺寸 [h x w x c]
# 输入张量的尺度为四维: [b, h,w,c]
x = tf.reshape(x, shape=[-1, 28, 28, 1])
# 卷积层,32个卷积核,尺寸为5x5
conv1 = tf.layers.conv2d(x, 32, 5, activation=tf.nn.relu)
# 最大池化层,步长为2,无需学习任何参量
conv1 = tf.layers.max_pooling2d(conv1, 2, 2)
# 卷积层,64个卷积核,尺寸为3x3
conv2 = tf.layers.conv2d(conv1, 64, 3, activation=tf.nn.relu)
# 最大池化层,步长为2,无需学习任何参量
conv2 = tf.layers.max_pooling2d(conv1, 2, 2)
# 展开特征为一维向量,以输入全连接层
fc1 = tf.contrib.layers.flatten(conv2)
# 全连接层
fc1 = tf.layers.dense(fc1, 1024)
# 应用Dropout (训练时打开,测试时关闭)
fc1 = tf.layers.dropout(fc1, rate=dropout, training=is_training)
# 输出层,预测类别
out = tf.layers.dense(fc1, n_classes)
return out
# 确定模型功能 (参照TF Estimator模版)
def model_fn(features, labels, mode):
# 因为dropout在训练与测试时的特性不一,为训练和测试过程创建两个独立但共享权值的计算图
logits_train = conv_net(features, num_classes, dropout, reuse=False, is_training=True)
logits_test = conv_net(features, num_classes, dropout, reuse=True, is_training=False)
# 预测
pred_classes = tf.argmax(logits_test, axis=1)
pred_probs = tf.nn.softmax(logits_test)
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode, predictions=pred_classes)
# 确定误差函数与优化器
loss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits_train, labels=tf.cast(labels, dtype=tf.int32)))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op, global_step=tf.train.get_global_step())
# 评估模型精确度
acc_op = tf.metrics.accuracy(labels=labels, predictions=pred_classes)
# TF Estimators需要返回EstimatorSpec
estim_specs = tf.estimator.EstimatorSpec(
mode=mode,
predictions=pred_classes,
loss=loss_op,
train_op=train_op,
eval_metircs_ops={'accuracy': acc_op})
# 构建Estimator
model = tf.estimator.Estimator(model_fn)
# 确定训练输入函数
input_fn = tf.compat.v1.estimator.inputs.numpy_input_fn(
x={'images': mnist.train.images}, y=mnist.train.labels,
batch_size=batchsz, num_epochs=None, shuffle=True)
# 开始训练模型
model.train(input_fn, steps=num_steps)
# 评判模型
# 确定评判用输入函数
input_fn = tf.compat.v1.estimator.inputs.numpy_input_fn(
x={'images': mnist.test.images}, y=mnist.test.labels,
batch_size=batch_size, shuffle=False)
model.evaluate(input_fn)
# 预测单个图像
n_images = 4
# 从数据集得到测试图像
test_images = mnist.test.images[:n_images]
# 准备输入数据
input_fn = tf.compat.v1.estimator.inputs.numpy_input_fn(
x={'images': test_images}, shuffle=False)
# 用训练好的模型预测图片类别
preds = list(model.predict(input_fn))
# 可视化显示
for i in range(n_images):
plt.imshow(np.reshape(test_images[i], [28, 28]), cmap='gray')
plt.show()
print('Model prediction: ', preds[i])