机器人与人工智能爱好者论坛

 找回密码
 立即注册
查看: 11118|回复: 0
打印 上一主题 下一主题

【连载】深度学习笔记11:利用numpy搭建一个卷积神经网络 

[复制链接]

31

主题

34

帖子

363

积分

中级会员

Rank: 3Rank: 3

积分
363
跳转到指定楼层
楼主
发表于 2018-11-19 10:59:53 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 Game 于 2018-11-19 11:02 编辑

      前两个笔记集中探讨了卷积神经网络中的卷积原理,对于二维卷积和三维卷积的原理进行了深入的剖析,对 CNN 的卷积、池化、全连接、滤波器、感受野等关键概念进行了充分的理解。本节内容将继续秉承之前 DNN 的学习路线,在利用 Tensorflow 搭建神经网络之前,先尝试利用 numpy 手动搭建卷积神经网络,以期对卷积神经网络的卷积机制、前向传播和反向传播的原理和过程有更深刻的理解。
单步卷积过程
      在正式搭建 CNN 之前,我们先依据前面笔记提到的卷积机制的线性计算的理解,利用 numpy 定义一个单步卷积过程。代码如下:
  1. def conv_single_step(a_slice_prev, W, b):
  2.     s = a_slice_prev * W    # Sum over all entries of the volume s.
  3.     Z = np.sum(s)    # Add bias b to Z. Cast b to a float() so that Z results in a scalar value.
  4.     Z = float(Z + b)   
  5.     return Z
复制代码

      在上述的单步卷积定义中,我们传入了一个前一层输入的要进行卷积的区域,即感受野  a_slice_prev ,滤波器 W,即卷积层的权重参数,偏差 b,对其执行 Z=Wx+b 的线性计算即可实现一个单步的卷积过程。
CNN前向传播过程:卷积
      正如 DNN 中一样,CNN 即使多了卷积和池化过程,模型仍然是前向传播和反向传播的训练过程。CNN 的前向传播包括卷积和池化两个过程,我们先来看如何利用 numpy 基于上面定义的单步卷积实现完整的卷积过程。卷积计算并不难,我们在单步卷积中就已经实现了,难点在于如何实现滤波器在输入图像矩阵上的的扫描和移动过程。

      这其中我们需要搞清楚一些变量和参数,以及每一个输入输出的 shape,这对于我们执行卷积和矩阵相乘至关重要。首先我们的输入是原始图像矩阵,也可以是前一层经过激活后的图像输出矩阵,这里以前一层的激活输出为准,输入像素的 shape 我们必须明确,然后是滤波器矩阵和偏差,还需要考虑步幅和填充,在此基础上我们基于滤波器移动和单步卷积搭建定义如下前向卷积过程:
  1. def conv_forward(A_prev, W, b, hparameters):   
  2.     """
  3.     Arguments:
  4.     A_prev -- output activations of the previous layer, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)
  5.     W -- Weights, numpy array of shape (f, f, n_C_prev, n_C)
  6.     b -- Biases, numpy array of shape (1, 1, 1, n_C)
  7.     hparameters -- python dictionary containing "stride" and "pad"

  8.     Returns:
  9.     Z -- conv output, numpy array of shape (m, n_H, n_W, n_C)
  10.     cache -- cache of values needed for the conv_backward() function
  11.     """
  12.     # 前一层输入的shape

  13.     (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape   
  14.      
  15.     # 滤波器权重的shape
  16.     (f, f, n_C_prev, n_C) = W.shape   
  17.     # 步幅参数
  18.     stride = hparameters['stride']   
  19.     # 填充参数
  20.     pad = hparameters['pad']   
  21.     # 计算输出图像的高宽
  22.     n_H = int((n_H_prev + 2 * pad - f) / stride + 1)
  23.     n_W = int((n_W_prev + 2 * pad - f) / stride + 1)   
  24.     # 初始化输出
  25.     Z = np.zeROS((m, n_H, n_W, n_C))   
  26.     # 对输入执行边缘填充
  27.     A_prev_pad = zero_pad(A_prev, pad)   
  28.     for i in range(m):                              
  29.         a_prev_pad = A_prev_pad[i, :, :, :]                 
  30.         for h in range(n_H):                          
  31.             for w in range(n_W):                     
  32.                 for c in range(n_C):                  

  33.                     # 滤波器在输入图像上扫描
  34.                     vert_start = h * stride
  35.                     vert_end = vert_start + f
  36.                     horiz_start = w * stride
  37.                     horiz_end = horiz_start + f                    
  38.                     # 定义感受野
  39.                     a_slice_prev = a_prev_pad[vert_start : vert_end, horiz_start : horiz_end, :]                    # 对感受野执行单步卷积
  40.                     Z[i, h, w, c] = conv_single_step(a_slice_prev, W[:,:,:,c], b[:,:,:,c])   
  41.     assert(Z.shape == (m, n_H, n_W, n_C))
  42.     cache = (A_prev, W, b, hparameters)   
  43.     return Z, cache
复制代码

      这样,卷积神经网络前向传播中一个完整的卷积计算过程就被我们定义好了。通常而言,我们也会对卷积后输出加一个 relu 激活操作,正如前面的图2所示,这里我们就省略不加了。
CNN前向传播过程:池化
      池化简单而言就是取局部区域最大值,池化的前向传播跟卷积过程类似,但相对简单一点,无需执行单步卷积那样的乘积运算。同样需要注意的是各参数和输入输出的 shape,因此我们定义如下前向传播池化过程:
  1. def pool_forward(A_prev, hparameters, mode = "max"):   
  2.     """
  3.     Arguments:
  4.     A_prev -- Input data, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)
  5.     hparameters -- python dictionary containing "f" and "stride"
  6.     mode -- the pooling mode you would like to use, defined as a string ("max" or "average")

  7.     Returns:
  8.     A -- output of the pool layer, a numpy array of shape (m, n_H, n_W, n_C)
  9.     cache -- cache used in the backward pass of the pooling layer, contains the input and hparameters
  10.     """

  11.     # 前一层输入的shape
  12.     (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape   
  13.     # 步幅和权重参数
  14.     f = hparameters["f"]
  15.     stride = hparameters["stride"]   
  16.     # 计算输出图像的高宽
  17.     n_H = int(1 + (n_H_prev - f) / stride)
  18.     n_W = int(1 + (n_W_prev - f) / stride)
  19.     n_C = n_C_prev   
  20.     # 初始化输出
  21.     A = np.zeros((m, n_H, n_W, n_C))              

  22.     for i in range(m):                       
  23.         for h in range(n_H):                  
  24.             for w in range(n_W):                 
  25.                 for c in range (n_C):         

  26.                     # 树池在输入图像上扫描
  27.                     vert_start = h * stride
  28.                     vert_end = vert_start + f
  29.                     horiz_start = w * stride
  30.                     horiz_end = horiz_start + f                 
  31.                     # 定义池化区域
  32.                     a_prev_slice = A_prev[i, vert_start:vert_end, horiz_start:horiz_end, c]                    
  33.                     # 选择池化类型
  34.                     if mode == "max":
  35.                         A[i, h, w, c] = np.max(a_prev_slice)                    
  36.                     elif mode == "average":
  37.                         A[i, h, w, c] = np.mean(a_prev_slice)

  38.     cache = (A_prev, hparameters)   
  39.     assert(A.shape == (m, n_H, n_W, n_C))   
  40.     return A, cache
复制代码

      由上述代码结构可以看出,前向传播的池化过程的代码结构和卷积过程非常类似。
CNN反向传播过程:卷积
      定义好前向传播之后,难点和关键点就在于如何给卷积和池化过程定义反向传播过程。卷积层的反向传播向来是个复杂的过程,Tensorflow 中我们只要定义好前向传播过程,反向传播会自动进行计算。但利用 numpy 搭建 CNN 反向传播就还得我们自己定义了。其关键还是在于准确的定义损失函数对于各个变量的梯度:

      由上述梯度计算公式和卷积的前向传播过程,我们定义如下卷积的反向传播函数:
  1. def conv_backward(dZ, cache):    """
  2.     Arguments:
  3.     dZ -- gradient of the cost with respect to the output of the conv layer (Z), numpy array of shape (m, n_H, n_W, n_C)
  4.     cache -- cache of values needed for the conv_backward(), output of conv_forward()

  5.     Returns:
  6.     dA_prev -- gradient of the cost with respect to the input of the conv layer (A_prev),
  7.                numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)
  8.     dW -- gradient of the cost with respect to the weights of the conv layer (W)
  9.           numpy array of shape (f, f, n_C_prev, n_C)
  10.     db -- gradient of the cost with respect to the biases of the conv layer (b)
  11.           numpy array of shape (1, 1, 1, n_C)
  12.     """
  13.     # 获取前向传播中存储的cache
  14.     (A_prev, W, b, hparameters) = cache   
  15.     # 前一层输入的shape
  16.     (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape   
  17.     # 滤波器的 shape
  18.     (f, f, n_C_prev, n_C) = W.shape   
  19.     # 步幅和权重参数
  20.     stride = hparameters['stride']
  21.     pad = hparameters['pad']   
  22.     # dZ 的shape
  23.     (m, n_H, n_W, n_C) = dZ.shape   
  24.     # 初始化 dA_prev, dW, db
  25.     dA_prev = np.zeros((m, n_H_prev, n_W_prev, n_C_prev))                           
  26.     dW = np.zeros((f, f, n_C_prev, n_C))
  27.     db = np.zeros((1, 1, 1, n_C))   
  28.     # 对A_prev 和 dA_prev 执行零填充
  29.     A_prev_pad = zero_pad(A_prev, pad)
  30.     dA_prev_pad = zero_pad(dA_prev, pad)   
  31.     for i in range(m):               
  32.         # select ith training example from A_prev_pad and dA_prev_pad
  33.         a_prev_pad = A_prev_pad[i,:,:,:]
  34.         da_prev_pad = dA_prev_pad[i,:,:,:]        
  35.         for h in range(n_H):                 
  36.             for w in range(n_W):            
  37.                 for c in range(n_C):         

  38.                     # 获取当前感受野
  39.                     vert_start = h * stride
  40.                     vert_end = vert_start + f
  41.                     horiz_start = w * stride
  42.                     horiz_end = horiz_start + f                    
  43.                     # 获取当前滤波器矩阵
  44.                     a_slice = a_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :]                    
  45.                     # 梯度更新
  46.                     da_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] += W[:,:,:,c] * dZ[i, h, w, c]
  47.                     dW[:,:,:,c] += a_slice * dZ[i, h, w, c]
  48.                     db[:,:,:,c] += dZ[i, h, w, c]

  49.                     dA_prev[i, :, :, :] = da_prev_pad[pad:-pad, pad:-pad, :]   
  50.     assert(dA_prev.shape == (m, n_H_prev, n_W_prev, n_C_prev))   
  51.     return dA_prev, dW, db
复制代码

CNN反向传播过程:池化
      反向传播中的池化操作跟卷积也是类似的。再此之前,我们需要根据滤波器为最大池化和平均池化分别创建一个 mask 和一个 distribute_value :
  1. def create_mask_from_window(x):   
  2.     """
  3.     Creates a mask from an input matrix x, to identify the max entry of x.

  4.     Arguments:
  5.     x -- Array of shape (f, f)

  6.     Returns:
  7.     mask -- Array of the same shape as window, contains a True at the position corresponding to the max entry of x.
  8.     """
  9.     mask = (x == np.max(x))   
  10.     return mask
复制代码
  1. def distribute_value(dz, shape):   
  2.     """
  3.     Distributes the input value in the matrix of dimension shape

  4.     Arguments:
  5.     dz -- input scalar
  6.     shape -- the shape (n_H, n_W) of the output matrix for which we want to distribute the value of dz

  7.     Returns:
  8.     a -- Array of size (n_H, n_W) for which we distributed the value of dz
  9.     """

  10.     (n_H, n_W) = shape   
  11.     # Compute the value to distribute on the matrix
  12.     average = dz / (n_H * n_W)   
  13.     # Create a matrix where every entry is the "average" value
  14.     a = np.full(shape, average)   
  15.     return a
复制代码
然后整合封装最大池化的反向传播过程:
  1. def pool_backward(dA, cache, mode = "max"):   
  2.     """
  3.     Arguments:
  4.     dA -- gradient of cost with respect to the output of the pooling layer, same shape as A
  5.     cache -- cache output from the forward pass of the pooling layer, contains the layer's input and hparameters
  6.     mode -- the pooling mode you would like to use, defined as a string ("max" or "average")

  7.     Returns:
  8.     dA_prev -- gradient of cost with respect to the input of the pooling layer, same shape as A_prev
  9.     """
  10.     # Retrieve information from cache
  11.     (A_prev, hparameters) = cache   
  12.     # Retrieve hyperparameters from "hparameters"
  13.     stride = hparameters['stride']
  14.     f = hparameters['f']   
  15.     # Retrieve dimensions from A_prev's shape and dA's shape
  16.     m, n_H_prev, n_W_prev, n_C_prev = A_prev.shape
  17.     m, n_H, n_W, n_C = dA.shape   
  18.     # Initialize dA_prev with zeros
  19.     dA_prev = np.zeros((m, n_H_prev, n_W_prev, n_C_prev))   
  20.     for i in range(m):                     
  21.         # select training example from A_prev
  22.         a_prev = A_prev[i,:,:,:]        
  23.         for h in range(n_H):                  
  24.             for w in range(n_W):              
  25.                 for c in range(n_C):         

  26.                     # Find the corners of the current "slice"
  27.                     vert_start = h * stride
  28.                     vert_end = vert_start + f
  29.                     horiz_start = w * stride
  30.                     horiz_end = horiz_start + f                    
  31.                     # Compute the backward propagation in both modes.
  32.                     if mode == "max":
  33.                         a_prev_slice = a_prev[vert_start:vert_end, horiz_start:horiz_end, c]
  34.                         mask = create_mask_from_window(a_prev_slice)
  35.                         dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += np.multiply(mask, dA[i,h,w,c])                    elif mode == "average":                     # Get the value a from dA
  36.                         da = dA[i,h,w,c]                        
  37.                         # Define the shape of the filter as fxf
  38.                         shape = (f,f)                        
  39.                         # Distribute it to get the correct slice of dA_prev. i.e. Add the distributed value of da.
  40.                         dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += distribute_value(da, shape)   
  41.     # Making sure your output shape is correct
  42.     assert(dA_prev.shape == A_prev.shape)   
  43.     return dA_prev
复制代码

      这样卷积神经网络的整个前向传播和反向传播过程我们就搭建好了。可以说是非常费力的操作了,但我相信,经过这样一步步的根据原理的手写,你一定会对卷积神经网络的原理理解更加深刻了。

本文来自《自兴人工智能》项目部:凯文

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

站长推荐上一条 /1 下一条

QQ|Archiver|手机版|小黑屋|陕ICP备15012670号-1    

GMT+8, 2024-4-28 05:40 , Processed in 0.103163 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表