前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >一步步构建卷积模型

一步步构建卷积模型

作者头像
云水木石
发布2019-07-01 15:32:13
5240
发布2019-07-01 15:32:13
举报

注:这篇文章的内容来自课程[Convolutional Neural Networks]的编程练习: Convolutional Model: step by step。虽然诸如TensorFlow之类的框架已经有高度集成的卷积神经网络模块,但是一步步构建卷积模型对深入理解卷积神经网络还是有帮助的。

在这个编程练习中,我们将使用numpy实现卷积(CONV)层和池化(POOL)层。

本指南采用的符号

  • 上标[l]代表第l层的对象。
    • 比如:a[4]为第4层的激励函数,W[5]和b[5]是第5层的参数。
  • 上标(i)代表第i个样本的对象。
    • 比如:x(i)是第i个输入样本。
  • 下标i表示向量的第i个项.
    • 例如:a[l]i表示第l层激活函数的第i个项,假定该层是全连接(FC)层。
  • nH、nW和nC分别表示某个层的高、宽和通道数。如果你要指代第l层,可以写作nH[l]、nW[l]、nC[l]。
  • nHprev、nWprev和nCprev分别代表前一层的高、宽和通道数。如果要特别指明是第l层,也可以写作nH[l−1]、nW[l−1]、nC[l−1] .

开始编程之前,你需要熟悉numpy。 让我们开始吧!

1 - 导入包

首先导入本次编程练习所需的包。

  • numpy是python科学计算的基础包。
  • matplotlib是python绘图包。
  • np.random.seed(1)用来保证产生的随机数都是一样的,便于单元测试。
代码语言:javascript
复制
import numpy as np
import h5py
import matplotlib.pyplot as plt%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'%load_ext autoreload
%autoreload 2np.random.seed(1)

:%是Jupyter Notebook中的指令标记,如果上述代码放在纯python脚本中,需要去掉%行。

2 - 编程作业大纲

接下来你将实现卷积神经网络的构建模块!每个功能都有详细的说明:

  • 卷积函数包括:
    • 零填充
    • 卷积窗口
    • 卷积前向传播
  • 池化功能包括:
    • 池化前向传播
    • 创建蒙版

你将在numpy中从头开始实现这些功能,在下一个编程练习中,你将使用TensorFlow来构建以下模型:

请注意,对于每个前向函数,都有对应的反向传播计算。因此,在前向模块的每一步计算中,你都会将一些参数存储在缓存中,这些参数将用于计算反向传播的梯度。

3 - 卷积神经网络

尽管有了编程框架,使得卷积易于使用,但它们仍然是深度学习中最难理解的概念之一。卷积层将输入数据卷转换为不同大小的输出数据卷,如下所示。

在这部分中,你将构建卷积图层的每一步。首先实现两个辅助函数:一个用于零填充,另一个用于计算卷积函数本身。

3.1 - 零填充

零填充在图像的边界周围添加零元素:

图1 零填充:3通道图像填充2个单位。

填充的主要好处有:

  • 使用CONV层,而不必缩小卷的高度和宽度。这对于建立更深的网络非常重要,否则网络很深,高度/宽度会剧减。这其中有一个重要的特例是“相同”卷积,其高度/宽度在卷积运算之后完全保留。
  • 它可以帮助我们保存更多图像的边界信息。如果没有填充,下一层的部分数据将受到像素边缘的影响。

练习:实现以下功能,将样本X中的所有图像做零填充。请使用np.pad实现。请注意,如果要给形状为(5,5,5,5,5)的阵列“a”,第二维以pad=1填充,第四维以pad=3填充,其余维度pad=0,你可以这样实现:

代码语言:javascript
复制
a = np.pad(a, ((0,0), (1,1), (0,0), (3,3), (0,0)), 'constant', constant_values = (..,..))
代码语言:javascript
复制
# GRADED FUNCTION: zero_paddef zero_pad(X, pad):
   """
   Pad with zeros all images of the dataset X. The padding is applied to the height and width of an image,
   as illustrated in Figure 1.   Argument:
   X -- python numpy array of shape (m, n_H, n_W, n_C) representing a batch of m images
   pad -- integer, amount of padding around each image on vertical and horizontal dimensions   Returns:
   X_pad -- padded image of shape (m, n_H + 2*pad, n_W + 2*pad, n_C)
   """   ### START CODE HERE ### (≈ 1 line)
   X_pad = np.pad(X, ((0, 0), (pad, pad),(pad, pad), (0, 0)), 'constant')
   ### END CODE HERE ###   return X_pad

3.2 - 单步卷积

在这一部分中,你将实现一个单步卷积,在该步骤中将过滤器应用于输入的单个位置。它将用来构成一个卷积单元,其中:

  • 获取输入卷
  • 在输入卷的每个位置应用过滤器
  • 输出另一数据卷(通常是不同的大小)

图2 卷积运算:过滤器大小为2x2,步长为1

在计算机视觉应用中,左侧矩阵中的每个值对应一个像素值,我们将3x3滤波器与图像进行卷积运算,将其值与原始矩阵进行元素乘法,然后对它们进行求和并添加偏差。练习的第一步,你将实现单步卷积,也就是将过滤器应用于其中一个位置以获得单个实数输出。

在后面的程序,你将把这个函数应用到输入卷的多个位置,从而实现完整的卷积运算。

练习:实现conv_single_step()。

代码语言:javascript
复制
# GRADED FUNCTION: conv_single_stepdef conv_single_step(a_slice_prev, W, b):
   """
   Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation
   of the previous layer.   Arguments:
   a_slice_prev -- slice of input data of shape (f, f, n_C_prev)
   W -- Weight parameters contained in a window - matrix of shape (f, f, n_C_prev)
   b -- Bias parameters contained in a window - matrix of shape (1, 1, 1)   Returns:
   Z -- a scalar value, result of convolving the sliding window (W, b) on a slice x of the input data
   """   ### START CODE HERE ### (≈ 2 lines of code)
   # Element-wise product between a_slice and W. Do not add the bias yet.
   s = a_slice_prev * W
   # Sum over all entries of the volume s.
   Z = np.sum(s)
   # Add bias b to Z. Cast b to a float() so that Z results in a scalar value.
   Z = Z + b[0, 0, 0]
   ### END CODE HERE ###   return Z

3.3 - 卷积神经网络 - 前向传播

在前向传播中,你将使用多个过滤器,在输入卷上进行卷积运算。每个’卷积’给你一个2D矩阵输出,然后堆叠这些输出以获得3D数据卷:

练习:实现下面的函数,在输入激活A_prev上和过滤器W进行卷积运算。该函数参数有输入A_prev、前一层的激活输出(输入批量为m)、F个滤波器(由权重W以及偏置向量b代表,其中每个滤波器具有其自己的偏置)。最后,你还可以访问包含步幅和填充的超参数字典。

提示

  1. 要选择形状为(5,5,3)的矩阵“a_prev”的左上角2x2切片,你应该这样实现: a_slice_prev = a_prev[0:2,0:2,:]
  2. 要定义a_slice,你需要先定义四个角:vert_start、vert_end、horiz_start和horiz_end。下面这个图可能有助于你在下面的代码中找到如何使用h、w、f和s来定义每个角点。

图3 使用垂直和水平方向的开始/结束定义切片(2x2过滤器),这个图仅展示单通道

提醒:卷积的输出形状与输入形状的公式为:

对于这个练习,我们无需考虑矢量化,用for循环来实现所有的东西。

代码语言:javascript
复制
# GRADED FUNCTION: conv_forwarddef conv_forward(A_prev, W, b, hparameters):
   """
   Implements the forward propagation for a convolution function   Arguments:
   A_prev -- output activations of the previous layer, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)
   W -- Weights, numpy array of shape (f, f, n_C_prev, n_C)
   b -- Biases, numpy array of shape (1, 1, 1, n_C)
   hparameters -- python dictionary containing "stride" and "pad"   Returns:
   Z -- conv output, numpy array of shape (m, n_H, n_W, n_C)
   cache -- cache of values needed for the conv_backward() function
   """   ### START CODE HERE ###
   # Retrieve dimensions from A_prev's shape (≈1 line)  
   (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape   # Retrieve dimensions from W's shape (≈1 line)
   (f, f, n_C_prev, n_C) = W.shape   # Retrieve information from "hparameters" (≈2 lines)
   stride = hparameters["stride"]
   pad = hparameters["pad"]   # Compute the dimensions of the CONV output volume using the formula given above. Hint: use int() to floor. (≈2 lines)
   n_H = int((n_H_prev -f + 2 * pad) / stride) + 1
   n_W = int((n_W_prev -f + 2 * pad) / stride) + 1   # Initialize the output volume Z with zeros. (≈1 line)
   Z = np.zeros((m, n_H, n_W, n_C))   # Create A_prev_pad by padding A_prev
   A_prev_pad = zero_pad(A_prev, pad)   for i in range(m):                                  # loop over the batch of training examples
       a_prev_pad = A_prev_pad[i, :, :, :]             # Select ith training example's padded activation
       for h in range(n_H):                            # loop over vertical axis of the output volume
           for w in range(n_W):                        # loop over horizontal axis of the output volume
               for c in range(n_C):                    # loop over channels (= #filters) of the output volume                   # Find the corners of the current "slice" (≈4 lines)
                   vert_start = h * stride
                   vert_end = vert_start + f
                   horiz_start = w * stride
                   horiz_end = horiz_start + f                   # Use the corners to define the (3D) slice of a_prev_pad (See Hint above the cell). (≈1 line)
                   a_slice_prev = a_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :]                   # Convolve the (3D) slice with the correct filter W and bias b, to get back one output neuron. (≈1 line)
                   Z[i, h, w, c] = conv_single_step(a_slice_prev, W[:, :, :, c], b[:, :, :, c])   ### END CODE HERE ###   # Making sure your output shape is correct
   assert(Z.shape == (m, n_H, n_W, n_C))   # Save information in "cache" for the backprop
   cache = (A_prev, W, b, hparameters)   return Z, cache

最后,CONV层还应包含激活函数,通常添加以下代码行:

代码语言:javascript
复制
# Convolve the window to get back one output neuron
Z[i, h, w, c] = ...
# Apply activation
A[i, h, w, c] = activation(Z[i, h, w, c])

但这里暂时不需要这样做。

4 - 池化层

池化(POOL)层减少输入的高度和宽度。它有助于减少计算量,并有助于使特征检测器的输入位置更加稳定。 这两种池化层是:

  • 最大池化层:在输入上滑动(f,f)窗口,并将窗口的最大值存储在输出中。
  • 平均池化层:在输入上滑动(f,f)窗口,并将窗口的平均值存储在输出中。

这些池话层没有反向传播训练的参数。但是,有超参数,例如窗口大小f,它指定计算最大值或平均值的fxf窗口的高度和宽度。

4.1 - 前向池

现在,你将在同一函数中实现MAX-POOL和AVG-POOL。

练习:实现池化层的前向传播,请根据注释中的提示实现。

提醒:因为没有填充,所以输入形状到输出形状的公式为:

代码语言:javascript
复制
# GRADED FUNCTION: pool_forwarddef pool_forward(A_prev, hparameters, mode = "max"):
   """
   Implements the forward pass of the pooling layer   Arguments:
   A_prev -- Input data, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)
   hparameters -- python dictionary containing "f" and "stride"
   mode -- the pooling mode you would like to use, defined as a string ("max" or "average")   Returns:
   A -- output of the pool layer, a numpy array of shape (m, n_H, n_W, n_C)
   cache -- cache used in the backward pass of the pooling layer, contains the input and hparameters
   """   # Retrieve dimensions from the input shape
   (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape   # Retrieve hyperparameters from "hparameters"
   f = hparameters["f"]
   stride = hparameters["stride"]   # Define the dimensions of the output
   n_H = int(1 + (n_H_prev - f) / stride)
   n_W = int(1 + (n_W_prev - f) / stride)
   n_C = n_C_prev   # Initialize output matrix A
   A = np.zeros((m, n_H, n_W, n_C))                 ### START CODE HERE ###
   for i in range(m):                         # loop over the training examples
       for h in range(n_H):                     # loop on the vertical axis of the output volume
           for w in range(n_W):                 # loop on the horizontal axis of the output volume
               for c in range (n_C):            # loop over the channels of the output volume                   # Find the corners of the current "slice" (≈4 lines)
                   vert_start = h * stride
                   vert_end = vert_start + f
                   horiz_start = w * stride
                   horiz_end = horiz_start + f                   # Use the corners to define the current slice on the ith training example of A_prev, channel c. (≈1 line)
                   a_prev_slice = A_prev[i, vert_start:vert_end, horiz_start:horiz_end, c]                   # Compute the pooling operation on the slice. Use an if statment to differentiate the modes. Use np.max/np.mean.
                   if mode == "max":
                       A[i, h, w, c] = np.max(a_prev_slice)
                   elif mode == "average":
                       A[i, h, w, c] = np.mean(a_prev_slice)   ### END CODE HERE ###   # Store the input and hparameters in "cache" for pool_backward()
   cache = (A_prev, hparameters)   # Making sure your output shape is correct
   assert(A.shape == (m, n_H, n_W, n_C))   return A, cache

恭喜! 你现在已经实现了卷积网络所有层的前向传播。

现代深度学习框架中,你只需要实现前向传播,而框架负责反向传播,所以大多数深度学习工程师不需要考虑反向传播的细节。卷积网络的反向传播很复杂,这里就暂不实现,有兴趣的可以上网查找相关的资料。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-06-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 云水木石 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1 - 导入包
  • 2 - 编程作业大纲
  • 3 - 卷积神经网络
    • 3.1 - 零填充
      • 3.2 - 单步卷积
        • 3.3 - 卷积神经网络 - 前向传播
        • 4 - 池化层
          • 4.1 - 前向池
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档