SHARE
TWEET

Convolutional Neural Networks: Step by Step

ERENARD63 Apr 12th, 2018 440 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. # coding: utf-8
  3.  
  4. # # Convolutional Neural Networks: Step by Step
  5. #
  6. # Welcome to Course 4's first assignment! In this assignment, you will implement convolutional (CONV) and pooling (POOL) layers in numpy, including both forward propagation and (optionally) backward propagation.
  7. #
  8. # **Notation**:
  9. # - Superscript $[l]$ denotes an object of the $l^{th}$ layer.
  10. #     - Example: $a^{[4]}$ is the $4^{th}$ layer activation. $W^{[5]}$ and $b^{[5]}$ are the $5^{th}$ layer parameters.
  11. #
  12. #
  13. # - Superscript $(i)$ denotes an object from the $i^{th}$ example.
  14. #     - Example: $x^{(i)}$ is the $i^{th}$ training example input.
  15. #    
  16. #    
  17. # - Lowerscript $i$ denotes the $i^{th}$ entry of a vector.
  18. #     - Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the activations in layer $l$, assuming this is a fully connected (FC) layer.
  19. #    
  20. #    
  21. # - $n_H$, $n_W$ and $n_C$ denote respectively the height, width and number of channels of a given layer. If you want to reference a specific layer $l$, you can also write $n_H^{[l]}$, $n_W^{[l]}$, $n_C^{[l]}$.
  22. # - $n_{H_{prev}}$, $n_{W_{prev}}$ and $n_{C_{prev}}$ denote respectively the height, width and number of channels of the previous layer. If referencing a specific layer $l$, this could also be denoted $n_H^{[l-1]}$, $n_W^{[l-1]}$, $n_C^{[l-1]}$.
  23. #
  24. # We assume that you are already familiar with `numpy` and/or have completed the previous courses of the specialization. Let's get started!
  25.  
  26. # ## 1 - Packages
  27. #
  28. # Let's first import all the packages that you will need during this assignment.
  29. # - [numpy](www.numpy.org) is the fundamental package for scientific computing with Python.
  30. # - [matplotlib](http://matplotlib.org) is a library to plot graphs in Python.
  31. # - np.random.seed(1) is used to keep all the random function calls consistent. It will help us grade your work.
  32.  
  33. # In[40]:
  34.  
  35. import numpy as np
  36. import h5py
  37. import matplotlib.pyplot as plt
  38.  
  39. get_ipython().magic('matplotlib inline')
  40. plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
  41. plt.rcParams['image.interpolation'] = 'nearest'
  42. plt.rcParams['image.cmap'] = 'gray'
  43.  
  44. get_ipython().magic('load_ext autoreload')
  45. get_ipython().magic('autoreload 2')
  46.  
  47. np.random.seed(1)
  48.  
  49.  
  50. # ## 2 - Outline of the Assignment
  51. #
  52. # You will be implementing the building blocks of a convolutional neural network! Each function you will implement will have detailed instructions that will walk you through the steps needed:
  53. #
  54. # - Convolution functions, including:
  55. #     - Zero Padding
  56. #     - Convolve window
  57. #     - Convolution forward
  58. #     - Convolution backward (optional)
  59. # - Pooling functions, including:
  60. #     - Pooling forward
  61. #     - Create mask
  62. #     - Distribute value
  63. #     - Pooling backward (optional)
  64. #    
  65. # This notebook will ask you to implement these functions from scratch in `numpy`. In the next notebook, you will use the TensorFlow equivalents of these functions to build the following model:
  66. #
  67. # <img src="images/model.png" style="width:800px;height:300px;">
  68. #
  69. # **Note** that for every forward function, there is its corresponding backward equivalent. Hence, at every step of your forward module you will store some parameters in a cache. These parameters are used to compute gradients during backpropagation.
  70.  
  71. # ## 3 - Convolutional Neural Networks
  72. #
  73. # Although programming frameworks make convolutions easy to use, they remain one of the hardest concepts to understand in Deep Learning. A convolution layer transforms an input volume into an output volume of different size, as shown below.
  74. #
  75. # <img src="images/conv_nn.png" style="width:350px;height:200px;">
  76. #
  77. # In this part, you will build every step of the convolution layer. You will first implement two helper functions: one for zero padding and the other for computing the convolution function itself.
  78.  
  79. # ### 3.1 - Zero-Padding
  80. #
  81. # Zero-padding adds zeros around the border of an image:
  82. #
  83. # <img src="images/PAD.png" style="width:600px;height:400px;">
  84. # <caption><center> <u> <font color='purple'> **Figure 1** </u><font color='purple'>  : **Zero-Padding**<br> Image (3 channels, RGB) with a padding of 2. </center></caption>
  85. #
  86. # The main benefits of padding are the following:
  87. #
  88. # - It allows you to use a CONV layer without necessarily shrinking the height and width of the volumes. This is important for building deeper networks, since otherwise the height/width would shrink as you go to deeper layers. An important special case is the "same" convolution, in which the height/width is exactly preserved after one layer.
  89. #
  90. # - It helps us keep more of the information at the border of an image. Without padding, very few values at the next layer would be affected by pixels as the edges of an image.
  91. #
  92. # **Exercise**: Implement the following function, which pads all the images of a batch of examples X with zeros. [Use np.pad](https://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html). Note if you want to pad the array "a" of shape $(5,5,5,5,5)$ with `pad = 1` for the 2nd dimension, `pad = 3` for the 4th dimension and `pad = 0` for the rest, you would do:
  93. # ```python
  94. # a = np.pad(a, ((0,0), (1,1), (0,0), (3,3), (0,0)), 'constant', constant_values = (..,..))
  95. # ```
  96.  
  97. # In[41]:
  98.  
  99. # GRADED FUNCTION: zero_pad
  100.  
  101. def zero_pad(X, pad):
  102.     """
  103.     Pad with zeros all images of the dataset X. The padding is applied to the height and width of an image,
  104.     as illustrated in Figure 1.
  105.    
  106.     Argument:
  107.     X -- python numpy array of shape (m, n_H, n_W, n_C) representing a batch of m images
  108.     pad -- integer, amount of padding around each image on vertical and horizontal dimensions
  109.    
  110.     Returns:
  111.     X_pad -- padded image of shape (m, n_H + 2*pad, n_W + 2*pad, n_C)
  112.     """
  113.    
  114.     ### START CODE HERE ### (≈ 1 line)
  115.     X_pad=  np.pad(X, ((0,0),(pad,pad), (pad,pad),(0,0)),'constant', constant_values=(0,0))
  116.  
  117.     ### END CODE HERE ###
  118.    
  119.     return X_pad
  120.  
  121.  
  122. # In[42]:
  123.  
  124. np.random.seed(1)
  125. x = np.random.randn(4, 3, 3, 2)
  126. x_pad = zero_pad(x, 2)
  127. print ("x.shape =", x.shape)
  128. print ("x_pad.shape =", x_pad.shape)
  129. print ("x[1,1] =", x[1,1])
  130. print ("x_pad[1,1] =", x_pad[1,1])
  131.  
  132. fig, axarr = plt.subplots(1, 2)
  133. axarr[0].set_title('x')
  134. axarr[0].imshow(x[0,:,:,0])
  135. axarr[1].set_title('x_pad')
  136. axarr[1].imshow(x_pad[0,:,:,0])
  137.  
  138.  
  139. # **Expected Output**:
  140. #
  141. # <table>
  142. #     <tr>
  143. #         <td>
  144. #             **x.shape**:
  145. #         </td>
  146. #         <td>
  147. #            (4, 3, 3, 2)
  148. #         </td>
  149. #     </tr>
  150. #         <tr>
  151. #         <td>
  152. #             **x_pad.shape**:
  153. #         </td>
  154. #         <td>
  155. #            (4, 7, 7, 2)
  156. #         </td>
  157. #     </tr>
  158. #         <tr>
  159. #         <td>
  160. #             **x[1,1]**:
  161. #         </td>
  162. #         <td>
  163. #            [[ 0.90085595 -0.68372786]
  164. #  [-0.12289023 -0.93576943]
  165. #  [-0.26788808  0.53035547]]
  166. #         </td>
  167. #     </tr>
  168. #         <tr>
  169. #         <td>
  170. #             **x_pad[1,1]**:
  171. #         </td>
  172. #         <td>
  173. #            [[ 0.  0.]
  174. #  [ 0.  0.]
  175. #  [ 0.  0.]
  176. #  [ 0.  0.]
  177. #  [ 0.  0.]
  178. #  [ 0.  0.]
  179. #  [ 0.  0.]]
  180. #         </td>
  181. #     </tr>
  182. #
  183. # </table>
  184.  
  185. # ### 3.2 - Single step of convolution
  186. #
  187. # In this part, implement a single step of convolution, in which you apply the filter to a single position of the input. This will be used to build a convolutional unit, which:
  188. #
  189. # - Takes an input volume
  190. # - Applies a filter at every position of the input
  191. # - Outputs another volume (usually of different size)
  192. #
  193. # <img src="images/Convolution_schematic.gif" style="width:500px;height:300px;">
  194. # <caption><center> <u> <font color='purple'> **Figure 2** </u><font color='purple'>  : **Convolution operation**<br> with a filter of 2x2 and a stride of 1 (stride = amount you move the window each time you slide) </center></caption>
  195. #
  196. # In a computer vision application, each value in the matrix on the left corresponds to a single pixel value, and we convolve a 3x3 filter with the image by multiplying its values element-wise with the original matrix, then summing them up and adding a bias. In this first step of the exercise, you will implement a single step of convolution, corresponding to applying a filter to just one of the positions to get a single real-valued output.
  197. #
  198. # Later in this notebook, you'll apply this function to multiple positions of the input to implement the full convolutional operation.
  199. #
  200. # **Exercise**: Implement conv_single_step(). [Hint](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.sum.html).
  201. #
  202.  
  203. # In[43]:
  204.  
  205. # GRADED FUNCTION: conv_single_step
  206.  
  207. def conv_single_step(a_slice_prev, W, b):
  208.     """
  209.     Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation
  210.     of the previous layer.
  211.    
  212.     Arguments:
  213.     a_slice_prev -- slice of input data of shape (f, f, n_C_prev)
  214.     W -- Weight parameters contained in a window - matrix of shape (f, f, n_C_prev)
  215.     b -- Bias parameters contained in a window - matrix of shape (1, 1, 1)
  216.    
  217.     Returns:
  218.     Z -- a scalar value, result of convolving the sliding window (W, b) on a slice x of the input data
  219.     """
  220.  
  221.     ### START CODE HERE ### (≈ 2 lines of code)
  222.     # Element-wise product between a_slice and W. Do not add the bias yet.
  223.     s =  a_slice_prev * W
  224.     #print(a_slice_prev.shape)
  225.     #print(W.shape)
  226.     # Sum over all entries of the volume s.
  227.     Z = np.sum(s,axis=None)
  228.     # Add bias b to Z. Cast b to a float() so that Z results in a scalar value.
  229.     Z = Z+float(b)
  230.     ### END CODE HERE ###
  231.  
  232.     return Z
  233.  
  234.  
  235. # In[44]:
  236.  
  237. np.random.seed(1)
  238. a_slice_prev = np.random.randn(4, 4, 3)
  239. W = np.random.randn(4, 4, 3)
  240. b = np.random.randn(1, 1, 1)
  241.  
  242. Z = conv_single_step(a_slice_prev, W, b)
  243. print("Z =", Z)
  244.  
  245.  
  246. # **Expected Output**:
  247. # <table>
  248. #     <tr>
  249. #         <td>
  250. #             **Z**
  251. #         </td>
  252. #         <td>
  253. #             -6.99908945068
  254. #         </td>
  255. #     </tr>
  256. #
  257. # </table>
  258.  
  259. # ### 3.3 - Convolutional Neural Networks - Forward pass
  260. #
  261. # In the forward pass, you will take many filters and convolve them on the input. Each 'convolution' gives you a 2D matrix output. You will then stack these outputs to get a 3D volume:
  262. #
  263. # <center>
  264. # <video width="620" height="440" src="images/conv_kiank.mp4" type="video/mp4" controls>
  265. # </video>
  266. # </center>
  267. #
  268. # **Exercise**: Implement the function below to convolve the filters W on an input activation A_prev. This function takes as input A_prev, the activations output by the previous layer (for a batch of m inputs), F filters/weights denoted by W, and a bias vector denoted by b, where each filter has its own (single) bias. Finally you also have access to the hyperparameters dictionary which contains the stride and the padding.
  269. #
  270. # **Hint**:
  271. # 1. To select a 2x2 slice at the upper left corner of a matrix "a_prev" (shape (5,5,3)), you would do:
  272. # ```python
  273. # a_slice_prev = a_prev[0:2,0:2,:]
  274. # ```
  275. # This will be useful when you will define `a_slice_prev` below, using the `start/end` indexes you will define.
  276. # 2. To define a_slice you will need to first define its corners `vert_start`, `vert_end`, `horiz_start` and `horiz_end`. This figure may be helpful for you to find how each of the corner can be defined using h, w, f and s in the code below.
  277. #
  278. # <img src="images/vert_horiz_kiank.png" style="width:400px;height:300px;">
  279. # <caption><center> <u> <font color='purple'> **Figure 3** </u><font color='purple'>  : **Definition of a slice using vertical and horizontal start/end (with a 2x2 filter)** <br> This figure shows only a single channel.  </center></caption>
  280. #
  281. #
  282. # **Reminder**:
  283. # The formulas relating the output shape of the convolution to the input shape is:
  284. # $$ n_H = \lfloor \frac{n_{H_{prev}} - f + 2 \times pad}{stride} \rfloor +1 $$
  285. # $$ n_W = \lfloor \frac{n_{W_{prev}} - f + 2 \times pad}{stride} \rfloor +1 $$
  286. # $$ n_C = \text{number of filters used in the convolution}$$
  287. #
  288. # For this exercise, we won't worry about vectorization, and will just implement everything with for-loops.
  289.  
  290. # In[45]:
  291.  
  292. # GRADED FUNCTION: conv_forward
  293.  
  294. def conv_forward(A_prev, W, b, hparameters):
  295.     """
  296.     Implements the forward propagation for a convolution function
  297.    
  298.     Arguments:
  299.     A_prev -- output activations of the previous layer, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)
  300.     W -- Weights, numpy array of shape (f, f, n_C_prev, n_C)
  301.     b -- Biases, numpy array of shape (1, 1, 1, n_C)
  302.     hparameters -- python dictionary containing "stride" and "pad"
  303.        
  304.     Returns:
  305.     Z -- conv output, numpy array of shape (m, n_H, n_W, n_C)
  306.     cache -- cache of values needed for the conv_backward() function
  307.     """
  308.    
  309.     ### START CODE HERE ###
  310.     # Retrieve dimensions from A_prev's shape (≈1 line)  
  311.     (m, n_H_prev, n_W_prev, n_C_prev) = (np.shape(A_prev)[0], np.shape(A_prev)[1], np.shape(A_prev)[2], np.shape(A_prev)[3])
  312.  
  313.     # Retrieve dimensions from W's shape (≈1 line)
  314.    
  315.    
  316.     (f, f, n_C_prev, n_C) = (np.shape(W)[0], np.shape(W)[1], np.shape(W)[2], np.shape(W)[3])
  317.    
  318.     # Retrieve information from "hparameters" (≈2 lines)
  319.     stride =   hparameters.get("stride")
  320.     pad = hparameters.get("pad")
  321.    
  322.     # Compute the dimensions of the CONV output volume using the formula given above. Hint: use int() to floor. (≈2 lines)
  323.     n_H = int((n_H_prev - f + 2* pad)/stride)+1
  324.     n_W = int((n_W_prev - f + 2* pad)/stride)+1
  325.    
  326.     # Initialize the output volume Z with zeros. (≈1 line)
  327.     initizeros= (m, n_H, n_W, n_C)
  328.     Z = np.zeros (initizeros)
  329.        
  330.     # Create A_prev_pad by padding A_prev
  331.     A_prev_pad = zero_pad(A_prev, pad)
  332.    
  333.    
  334.     for i in range(m):                               # loop over the batch of training examples
  335.         a_prev_pad = A_prev_pad[i,:,:,:]                     # Select ith training example's padded activation
  336.        
  337.         for h in range(n_H):                           # loop over vertical axis of the output volume
  338.             for w in range(n_W):                       # loop over horizontal axis of the output volume
  339.                 for c in range(n_C):                   # loop over channels (= #filters) of the output volume
  340.                    
  341.                     # Find the corners of the current "slice" (≈4 lines)
  342.                     vert_start = h*stride
  343.                     vert_end = vert_start+f
  344.                     horiz_start = w*stride
  345.                     horiz_end = horiz_start+f
  346.                    
  347.                     # Use the corners to define the (3D) slice of a_prev_pad (See Hint above the cell). (≈1 line)
  348.                     a_slice_prev = a_prev_pad[vert_start:vert_end,horiz_start:horiz_end,:]
  349.                                      
  350.                    
  351.                     # Convolve the (3D) slice with the correct filter W and bias b, to get back one output neuron. (≈1 line)
  352.                     Z[i, h, w, c] = conv_single_step(a_slice_prev, W[:,:,:,c], b[:,:,:,c])
  353.                    
  354.                    
  355.                                        
  356.     ### END CODE HERE ###
  357.    
  358.     # Making sure your output shape is correct
  359.     assert(Z.shape == (m, n_H, n_W, n_C))
  360.    
  361.     # Save information in "cache" for the backprop
  362.     cache = (A_prev, W, b, hparameters)
  363.    
  364.     return Z, cache
  365.  
  366.  
  367. # In[46]:
  368.  
  369. np.random.seed(1)
  370. A_prev = np.random.randn(10,4,4,3)
  371. W = np.random.randn(2,2,3,8)
  372. b = np.random.randn(1,1,1,8)
  373. hparameters = {"pad" : 2,
  374.                "stride": 2}
  375.  
  376. Z, cache_conv = conv_forward(A_prev, W, b, hparameters)
  377. print("Z's mean =", np.mean(Z))
  378. print("Z[3,2,1] =", Z[3,2,1])
  379. print("cache_conv[0][1][2][3] =", cache_conv[0][1][2][3])
  380.  
  381.  
  382. # **Expected Output**:
  383. #
  384. # <table>
  385. #     <tr>
  386. #         <td>
  387. #             **Z's mean**
  388. #         </td>
  389. #         <td>
  390. #             0.0489952035289
  391. #         </td>
  392. #     </tr>
  393. #     <tr>
  394. #         <td>
  395. #             **Z[3,2,1]**
  396. #         </td>
  397. #         <td>
  398. #             [-0.61490741 -6.7439236  -2.55153897  1.75698377  3.56208902  0.53036437
  399. #   5.18531798  8.75898442]
  400. #         </td>
  401. #     </tr>
  402. #     <tr>
  403. #         <td>
  404. #             **cache_conv[0][1][2][3]**
  405. #         </td>
  406. #         <td>
  407. #             [-0.20075807  0.18656139  0.41005165]
  408. #         </td>
  409. #     </tr>
  410. #
  411. # </table>
  412. #
  413.  
  414. # Finally, CONV layer should also contain an activation, in which case we would add the following line of code:
  415. #
  416. # ```python
  417. # # Convolve the window to get back one output neuron
  418. # Z[i, h, w, c] = ...
  419. # # Apply activation
  420. # A[i, h, w, c] = activation(Z[i, h, w, c])
  421. # ```
  422. #
  423. # You don't need to do it here.
  424. #
  425.  
  426. # ## 4 - Pooling layer
  427. #
  428. # The pooling (POOL) layer reduces the height and width of the input. It helps reduce computation, as well as helps make feature detectors more invariant to its position in the input. The two types of pooling layers are:
  429. #
  430. # - Max-pooling layer: slides an ($f, f$) window over the input and stores the max value of the window in the output.
  431. #
  432. # - Average-pooling layer: slides an ($f, f$) window over the input and stores the average value of the window in the output.
  433. #
  434. # <table>
  435. # <td>
  436. # <img src="images/max_pool1.png" style="width:500px;height:300px;">
  437. # <td>
  438. #
  439. # <td>
  440. # <img src="images/a_pool.png" style="width:500px;height:300px;">
  441. # <td>
  442. # </table>
  443. #
  444. # These pooling layers have no parameters for backpropagation to train. However, they have hyperparameters such as the window size $f$. This specifies the height and width of the fxf window you would compute a max or average over.
  445. #
  446. # ### 4.1 - Forward Pooling
  447. # Now, you are going to implement MAX-POOL and AVG-POOL, in the same function.
  448. #
  449. # **Exercise**: Implement the forward pass of the pooling layer. Follow the hints in the comments below.
  450. #
  451. # **Reminder**:
  452. # As there's no padding, the formulas binding the output shape of the pooling to the input shape is:
  453. # $$ n_H = \lfloor \frac{n_{H_{prev}} - f}{stride} \rfloor +1 $$
  454. # $$ n_W = \lfloor \frac{n_{W_{prev}} - f}{stride} \rfloor +1 $$
  455. # $$ n_C = n_{C_{prev}}$$
  456.  
  457. # In[47]:
  458.  
  459. # GRADED FUNCTION: pool_forward
  460.  
  461. def pool_forward(A_prev, hparameters, mode = "max"):
  462.     """
  463.     Implements the forward pass of the pooling layer
  464.    
  465.     Arguments:
  466.     A_prev -- Input data, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)
  467.     hparameters -- python dictionary containing "f" and "stride"
  468.     mode -- the pooling mode you would like to use, defined as a string ("max" or "average")
  469.    
  470.     Returns:
  471.     A -- output of the pool layer, a numpy array of shape (m, n_H, n_W, n_C)
  472.     cache -- cache used in the backward pass of the pooling layer, contains the input and hparameters
  473.     """
  474.    
  475.     # Retrieve dimensions from the input shape
  476.     (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape
  477.    
  478.     # Retrieve hyperparameters from "hparameters"
  479.     f = hparameters["f"]
  480.     stride = hparameters["stride"]
  481.    
  482.     # Define the dimensions of the output
  483.     n_H = int(1 + (n_H_prev - f) / stride)
  484.     n_W = int(1 + (n_W_prev - f) / stride)
  485.     n_C = n_C_prev
  486.    
  487.     # Initialize output matrix A
  488.     A = np.zeros((m, n_H, n_W, n_C))              
  489.    
  490.     ### START CODE HERE ###
  491.     for i in range(m):                         # loop over the training examples
  492.         for h in range(n_H):                     # loop on the vertical axis of the output volume
  493.             for w in range(n_W):                 # loop on the horizontal axis of the output volume
  494.                 for c in range (n_C):            # loop over the channels of the output volume
  495.                    
  496.                     # Find the corners of the current "slice" (≈4 lines)
  497.                     vert_start = h*stride
  498.                     vert_end = vert_start+f
  499.                     horiz_start = w*stride
  500.                     horiz_end = horiz_start+f
  501.                    
  502.                    
  503.                     # Use the corners to define the current slice on the ith training example of A_prev, channel c. (≈1 line)
  504.                     #a_prev_slice = None
  505.                     a_slice_prev = A_prev[i,vert_start:vert_end,horiz_start:horiz_end,c]
  506.                    
  507.                     # Compute the pooling operation on the slice. Use an if statment to differentiate the modes. Use np.max/np.mean.
  508.                     if mode == "max":
  509.                         A[i, h, w, c] = np.max(a_slice_prev)
  510.                     elif mode == "average":
  511.                         A[i, h, w, c] = np.average(a_slice_prev)
  512.    
  513.     ### END CODE HERE ###
  514.    
  515.     # Store the input and hparameters in "cache" for pool_backward()
  516.     cache = (A_prev, hparameters)
  517.    
  518.     # Making sure your output shape is correct
  519.     assert(A.shape == (m, n_H, n_W, n_C))
  520.    
  521.     return A, cache
  522.  
  523.  
  524. # In[48]:
  525.  
  526. np.random.seed(1)
  527. A_prev = np.random.randn(2, 4, 4, 3)
  528. hparameters = {"stride" : 2, "f": 3}
  529.  
  530. A, cache = pool_forward(A_prev, hparameters)
  531. print("mode = max")
  532. print("A =", A)
  533. print()
  534. A, cache = pool_forward(A_prev, hparameters, mode = "average")
  535. print("mode = average")
  536. print("A =", A)
  537.  
  538.  
  539. # **Expected Output:**
  540. # <table>
  541. #
  542. #     <tr>
  543. #     <td>
  544. #     A  =
  545. #     </td>
  546. #         <td>
  547. #          [[[[ 1.74481176  0.86540763  1.13376944]]]
  548. #
  549. #
  550. #  [[[ 1.13162939  1.51981682  2.18557541]]]]
  551. #
  552. #         </td>
  553. #     </tr>
  554. #     <tr>
  555. #     <td>
  556. #     A  =
  557. #     </td>
  558. #         <td>
  559. #          [[[[ 0.02105773 -0.20328806 -0.40389855]]]
  560. #
  561. #
  562. #  [[[-0.22154621  0.51716526  0.48155844]]]]
  563. #
  564. #         </td>
  565. #     </tr>
  566. #
  567. # </table>
  568. #
  569.  
  570. # Congratulations! You have now implemented the forward passes of all the layers of a convolutional network.
  571. #
  572. # The remainer of this notebook is optional, and will not be graded.
  573. #
  574.  
  575. # ## 5 - Backpropagation in convolutional neural networks (OPTIONAL / UNGRADED)
  576. #
  577. # In modern deep learning frameworks, you only have to implement the forward pass, and the framework takes care of the backward pass, so most deep learning engineers don't need to bother with the details of the backward pass. The backward pass for convolutional networks is complicated. If you wish however, you can work through this optional portion of the notebook to get a sense of what backprop in a convolutional network looks like.
  578. #
  579. # When in an earlier course you implemented a simple (fully connected) neural network, you used backpropagation to compute the derivatives with respect to the cost to update the parameters. Similarly, in convolutional neural networks you can to calculate the derivatives with respect to the cost in order to update the parameters. The backprop equations are not trivial and we did not derive them in lecture, but we briefly presented them below.
  580. #
  581. # ### 5.1 - Convolutional layer backward pass
  582. #
  583. # Let's start by implementing the backward pass for a CONV layer.
  584. #
  585. # #### 5.1.1 - Computing dA:
  586. # This is the formula for computing $dA$ with respect to the cost for a certain filter $W_c$ and a given training example:
  587. #
  588. # $$ dA += \sum _{h=0} ^{n_H} \sum_{w=0} ^{n_W} W_c \times dZ_{hw} \tag{1}$$
  589. #
  590. # Where $W_c$ is a filter and $dZ_{hw}$ is a scalar corresponding to the gradient of the cost with respect to the output of the conv layer Z at the hth row and wth column (corresponding to the dot product taken at the ith stride left and jth stride down). Note that at each time, we multiply the the same filter $W_c$ by a different dZ when updating dA. We do so mainly because when computing the forward propagation, each filter is dotted and summed by a different a_slice. Therefore when computing the backprop for dA, we are just adding the gradients of all the a_slices.
  591. #
  592. # In code, inside the appropriate for-loops, this formula translates into:
  593. # ```python
  594. # da_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] += W[:,:,:,c] * dZ[i, h, w, c]
  595. # ```
  596. #
  597. # #### 5.1.2 - Computing dW:
  598. # This is the formula for computing $dW_c$ ($dW_c$ is the derivative of one filter) with respect to the loss:
  599. #
  600. # $$ dW_c  += \sum _{h=0} ^{n_H} \sum_{w=0} ^ {n_W} a_{slice} \times dZ_{hw}  \tag{2}$$
  601. #
  602. # Where $a_{slice}$ corresponds to the slice which was used to generate the acitivation $Z_{ij}$. Hence, this ends up giving us the gradient for $W$ with respect to that slice. Since it is the same $W$, we will just add up all such gradients to get $dW$.
  603. #
  604. # In code, inside the appropriate for-loops, this formula translates into:
  605. # ```python
  606. # dW[:,:,:,c] += a_slice * dZ[i, h, w, c]
  607. # ```
  608. #
  609. # #### 5.1.3 - Computing db:
  610. #
  611. # This is the formula for computing $db$ with respect to the cost for a certain filter $W_c$:
  612. #
  613. # $$ db = \sum_h \sum_w dZ_{hw} \tag{3}$$
  614. #
  615. # As you have previously seen in basic neural networks, db is computed by summing $dZ$. In this case, you are just summing over all the gradients of the conv output (Z) with respect to the cost.
  616. #
  617. # In code, inside the appropriate for-loops, this formula translates into:
  618. # ```python
  619. # db[:,:,:,c] += dZ[i, h, w, c]
  620. # ```
  621. #
  622. # **Exercise**: Implement the `conv_backward` function below. You should sum over all the training examples, filters, heights, and widths. You should then compute the derivatives using formulas 1, 2 and 3 above.
  623.  
  624. # In[49]:
  625.  
  626. def conv_backward(dZ, cache):
  627.     """
  628.     Implement the backward propagation for a convolution function
  629.    
  630.     Arguments:
  631.     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)
  632.     cache -- cache of values needed for the conv_backward(), output of conv_forward()
  633.    
  634.     Returns:
  635.     dA_prev -- gradient of the cost with respect to the input of the conv layer (A_prev),
  636.                numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)
  637.     dW -- gradient of the cost with respect to the weights of the conv layer (W)
  638.           numpy array of shape (f, f, n_C_prev, n_C)
  639.     db -- gradient of the cost with respect to the biases of the conv layer (b)
  640.           numpy array of shape (1, 1, 1, n_C)
  641.     """
  642.    
  643.     ### START CODE HERE ###
  644.     # Retrieve information from "cache"
  645.     (A_prev, W, b, hparameters) = cache
  646.    
  647.     # Retrieve dimensions from A_prev's shape
  648.     (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape
  649.    
  650.     # Retrieve dimensions from W's shape
  651.     (f, f, n_C_prev, n_C) = W.shape
  652.    
  653.     # Retrieve information from "hparameters"
  654.     stride = hparameters["stride"]
  655.     pad = hparameters["pad"]
  656.    
  657.     # Retrieve dimensions from dZ's shape
  658.     (m, n_H, n_W, n_C) = dZ.shape
  659.    
  660.     # Initialize dA_prev, dW, db with the correct shapes
  661.     dA_prev = np.zeros((m, n_H_prev, n_W_prev, n_C_prev))                      
  662.     dW = np.zeros((f, f, n_C_prev, n_C))
  663.     db = np.zeros((1, 1, 1, n_C))
  664.  
  665.     # Pad A_prev and dA_prev
  666.     A_prev_pad = zero_pad(A_prev, pad)
  667.     dA_prev_pad = zero_pad(dA_prev, pad)
  668.    
  669.     for i in range(m):                       # loop over the training examples
  670.        
  671.         # select ith training example from A_prev_pad and dA_prev_pad
  672.         a_prev_pad = A_prev_pad[i,:,:,:]  
  673.         da_prev_pad = dA_prev_pad[i,:,:,:]  
  674.        
  675.         for h in range(n_H):                   # loop over vertical axis of the output volume
  676.             for w in range(n_W):               # loop over horizontal axis of the output volume
  677.                 for c in range(n_C):           # loop over the channels of the output volume
  678.                    
  679.                     # Find the corners of the current "slice"
  680.                     vert_start = h*stride
  681.                     vert_end = vert_start+f
  682.                     horiz_start = w*stride
  683.                     horiz_end = horiz_start+f
  684.                    
  685.                     # Use the corners to define the slice from a_prev_pad
  686.                     a_slice = a_prev_pad[vert_start:vert_end,horiz_start:horiz_end,:]
  687.  
  688.                     # Update gradients for the window and the filter's parameters using the code formulas given above
  689.                     da_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] += W[:,:,:,c] * dZ[i, h, w, c]
  690.                     dW[:,:,:,c] += a_slice * dZ[i, h, w, c]
  691.                     db[:,:,:,c] += dZ[i, h, w, c]
  692.                    
  693.         # Set the ith training example's dA_prev to the unpaded da_prev_pad (Hint: use X[pad:-pad, pad:-pad, :])
  694.         dA_prev[i, :, :, :] = da_prev_pad[pad:-pad, pad:-pad, :]
  695.     ### END CODE HERE ###
  696.    
  697.     # Making sure your output shape is correct
  698.     assert(dA_prev.shape == (m, n_H_prev, n_W_prev, n_C_prev))
  699.    
  700.     return dA_prev, dW, db
  701.  
  702.  
  703. # In[50]:
  704.  
  705. np.random.seed(1)
  706. dA, dW, db = conv_backward(Z, cache_conv)
  707. print("dA_mean =", np.mean(dA))
  708. print("dW_mean =", np.mean(dW))
  709. print("db_mean =", np.mean(db))
  710.  
  711.  
  712. # ** Expected Output: **
  713. # <table>
  714. #     <tr>
  715. #         <td>
  716. #             **dA_mean**
  717. #         </td>
  718. #         <td>
  719. #             1.45243777754
  720. #         </td>
  721. #     </tr>
  722. #     <tr>
  723. #         <td>
  724. #             **dW_mean**
  725. #         </td>
  726. #         <td>
  727. #             1.72699145831
  728. #         </td>
  729. #     </tr>
  730. #     <tr>
  731. #         <td>
  732. #             **db_mean**
  733. #         </td>
  734. #         <td>
  735. #             7.83923256462
  736. #         </td>
  737. #     </tr>
  738. #
  739. # </table>
  740. #
  741.  
  742. # ## 5.2 Pooling layer - backward pass
  743. #
  744. # Next, let's implement the backward pass for the pooling layer, starting with the MAX-POOL layer. Even though a pooling layer has no parameters for backprop to update, you still need to backpropagation the gradient through the pooling layer in order to compute gradients for layers that came before the pooling layer.
  745. #
  746. # ### 5.2.1 Max pooling - backward pass  
  747. #
  748. # Before jumping into the backpropagation of the pooling layer, you are going to build a helper function called `create_mask_from_window()` which does the following:
  749. #
  750. # $$ X = \begin{bmatrix}
  751. # 1 && 3 \\
  752. # 4 && 2
  753. # \end{bmatrix} \quad \rightarrow  \quad M =\begin{bmatrix}
  754. # 0 && 0 \\
  755. # 1 && 0
  756. # \end{bmatrix}\tag{4}$$
  757. #
  758. # As you can see, this function creates a "mask" matrix which keeps track of where the maximum of the matrix is. True (1) indicates the position of the maximum in X, the other entries are False (0). You'll see later that the backward pass for average pooling will be similar to this but using a different mask.  
  759. #
  760. # **Exercise**: Implement `create_mask_from_window()`. This function will be helpful for pooling backward.
  761. # Hints:
  762. # - [np.max()]() may be helpful. It computes the maximum of an array.
  763. # - If you have a matrix X and a scalar x: `A = (X == x)` will return a matrix A of the same size as X such that:
  764. # ```
  765. # A[i,j] = True if X[i,j] = x
  766. # A[i,j] = False if X[i,j] != x
  767. # ```
  768. # - Here, you don't need to consider cases where there are several maxima in a matrix.
  769.  
  770. # In[51]:
  771.  
  772. def create_mask_from_window(x):
  773.     """
  774.     Creates a mask from an input matrix x, to identify the max entry of x.
  775.    
  776.     Arguments:
  777.     x -- Array of shape (f, f)
  778.    
  779.     Returns:
  780.     mask -- Array of the same shape as window, contains a True at the position corresponding to the max entry of x.
  781.     """
  782.    
  783.     ### START CODE HERE ### (≈1 line)
  784.     mask = (x == np.max(x))
  785.     ### END CODE HERE ###
  786.    
  787.     return mask
  788.  
  789.  
  790. # In[52]:
  791.  
  792. np.random.seed(1)
  793. x = np.random.randn(2,3)
  794. mask = create_mask_from_window(x)
  795. print('x = ', x)
  796. print("mask = ", mask)
  797.  
  798.  
  799. # **Expected Output:**
  800. #
  801. # <table>
  802. # <tr>
  803. # <td>
  804. #
  805. # **x =**
  806. # </td>
  807. #
  808. # <td>
  809. #
  810. # [[ 1.62434536 -0.61175641 -0.52817175] <br>
  811. #  [-1.07296862  0.86540763 -2.3015387 ]]
  812. #
  813. #   </td>
  814. # </tr>
  815. #
  816. # <tr>
  817. # <td>
  818. # **mask =**
  819. # </td>
  820. # <td>
  821. # [[ True False False] <br>
  822. #  [False False False]]
  823. # </td>
  824. # </tr>
  825. #
  826. #
  827. # </table>
  828.  
  829. # Why do we keep track of the position of the max? It's because this is the input value that ultimately influenced the output, and therefore the cost. Backprop is computing gradients with respect to the cost, so anything that influences the ultimate cost should have a non-zero gradient. So, backprop will "propagate" the gradient back to this particular input value that had influenced the cost.
  830.  
  831. # ### 5.2.2 - Average pooling - backward pass
  832. #
  833. # In max pooling, for each input window, all the "influence" on the output came from a single input value--the max. In average pooling, every element of the input window has equal influence on the output. So to implement backprop, you will now implement a helper function that reflects this.
  834. #
  835. # For example if we did average pooling in the forward pass using a 2x2 filter, then the mask you'll use for the backward pass will look like:
  836. # $$ dZ = 1 \quad \rightarrow  \quad dZ =\begin{bmatrix}
  837. # 1/4 && 1/4 \\
  838. # 1/4 && 1/4
  839. # \end{bmatrix}\tag{5}$$
  840. #
  841. # This implies that each position in the $dZ$ matrix contributes equally to output because in the forward pass, we took an average.
  842. #
  843. # **Exercise**: Implement the function below to equally distribute a value dz through a matrix of dimension shape. [Hint](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ones.html)
  844.  
  845. # In[53]:
  846.  
  847. def distribute_value(dz, shape):
  848.     """
  849.     Distributes the input value in the matrix of dimension shape
  850.    
  851.     Arguments:
  852.     dz -- input scalar
  853.     shape -- the shape (n_H, n_W) of the output matrix for which we want to distribute the value of dz
  854.    
  855.     Returns:
  856.     a -- Array of size (n_H, n_W) for which we distributed the value of dz
  857.     """
  858.    
  859.     ### START CODE HERE ###
  860.     # Retrieve dimensions from shape (≈1 line)
  861.     (n_H, n_W) = shape
  862.    
  863.     # Compute the value to distribute on the matrix (≈1 line)
  864.     average = dz/(n_H * n_W)
  865.    
  866.     # Create a matrix where every entry is the "average" value (≈1 line)
  867.     a = np.empty((n_H, n_W))
  868.     a[:]= average
  869.     ### END CODE HERE ###
  870.    
  871.     return a
  872.  
  873.  
  874. # In[54]:
  875.  
  876. a = distribute_value(2, (2,2))
  877. print('distributed value =', a)
  878.  
  879.  
  880. # **Expected Output**:
  881. #
  882. # <table>
  883. # <tr>
  884. # <td>
  885. # distributed_value =
  886. # </td>
  887. # <td>
  888. # [[ 0.5  0.5]
  889. # <br\>
  890. # [ 0.5  0.5]]
  891. # </td>
  892. # </tr>
  893. # </table>
  894.  
  895. # ### 5.2.3 Putting it together: Pooling backward
  896. #
  897. # You now have everything you need to compute backward propagation on a pooling layer.
  898. #
  899. # **Exercise**: Implement the `pool_backward` function in both modes (`"max"` and `"average"`). You will once again use 4 for-loops (iterating over training examples, height, width, and channels). You should use an `if/elif` statement to see if the mode is equal to `'max'` or `'average'`. If it is equal to 'average' you should use the `distribute_value()` function you implemented above to create a matrix of the same shape as `a_slice`. Otherwise, the mode is equal to '`max`', and you will create a mask with `create_mask_from_window()` and multiply it by the corresponding value of dZ.
  900.  
  901. # In[55]:
  902.  
  903. def pool_backward(dA, cache, mode = "max"):
  904.     """
  905.     Implements the backward pass of the pooling layer
  906.    
  907.     Arguments:
  908.     dA -- gradient of cost with respect to the output of the pooling layer, same shape as A
  909.     cache -- cache output from the forward pass of the pooling layer, contains the layer's input and hparameters
  910.     mode -- the pooling mode you would like to use, defined as a string ("max" or "average")
  911.    
  912.     Returns:
  913.     dA_prev -- gradient of cost with respect to the input of the pooling layer, same shape as A_prev
  914.     """
  915.    
  916.     ### START CODE HERE ###
  917.    
  918.     # Retrieve information from cache (≈1 line)
  919.     (A_prev, hparameters) = cache
  920.    
  921.     # Retrieve hyperparameters from "hparameters" (≈2 lines)
  922.     stride = hparameters["stride"]
  923.     f = hparameters["f"]
  924.    
  925.     #stride = None
  926.     #f = None
  927.    
  928.     # Retrieve dimensions from A_prev's shape and dA's shape (≈2 lines)
  929.     (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape
  930.     (m, n_H, n_W, n_C) = dA.shape
  931.    
  932.     # Initialize dA_prev with zeros (≈1 line)
  933.     initdim=(m, n_H_prev, n_W_prev, n_C_prev)
  934.     dA_prev = np.zeros(initdim)
  935.    
  936.     for i in range(m):                       # loop over the training examples
  937.        
  938.         # select training example from A_prev (≈1 line)
  939.         a_prev = A_prev[i,:,:,:]
  940.        
  941.        
  942.         for h in range(n_H):                   # loop on the vertical axis
  943.             for w in range(n_W):               # loop on the horizontal axis
  944.                 for c in range(n_C):           # loop over the channels (depth)
  945.                    
  946.                     # Find the corners of the current "slice" (≈4 lines)
  947.                     vert_start = h*stride
  948.                     vert_end = vert_start+f
  949.                     horiz_start = w*stride
  950.                     horiz_end = horiz_start+f
  951.                    
  952.                     # Compute the backward propagation in both modes.
  953.                     if mode == "max":
  954.                        
  955.                         # Use the corners and "c" to define the current slice from a_prev (≈1 line)
  956.                         a_prev_slice = a_prev[vert_start:vert_end,horiz_start:horiz_end,c]
  957.                         # Create the mask from a_prev_slice (≈1 line)
  958.                         mask = create_mask_from_window(a_prev_slice)
  959.                         # Set dA_prev to be dA_prev + (the mask multiplied by the correct entry of dA) (≈1 line)
  960.                         #dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += mask*dA[i, vert_start: vert_end, horiz_start: horiz_end, c]
  961.                         dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += mask*dA[i, vert_start, horiz_start, c]
  962.                        
  963.                     elif mode == "average":
  964.                        
  965.                         # Get the value a from dA (≈1 line)
  966.                         #da = dA[i, vert_start: vert_end, horiz_start: horiz_end, c]
  967.                         da = dA[i, vert_start, horiz_start, c]
  968.                         # Define the shape of the filter as fxf (≈1 line)
  969.                         shape = (f,f)
  970.                         # Distribute it to get the correct slice of dA_prev. i.e. Add the distributed value of da. (≈1 line)
  971.                         dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += distribute_value(da, shape)
  972.                        
  973.     ### END CODE ###
  974.    
  975.     # Making sure your output shape is correct
  976.     assert(dA_prev.shape == A_prev.shape)
  977.    
  978.     return dA_prev
  979.  
  980.  
  981. # In[56]:
  982.  
  983. np.random.seed(1)
  984. A_prev = np.random.randn(5, 5, 3, 2)
  985. hparameters = {"stride" : 1, "f": 2}
  986. A, cache = pool_forward(A_prev, hparameters)
  987. dA = np.random.randn(5, 4, 2, 2)
  988.  
  989. dA_prev = pool_backward(dA, cache, mode = "max")
  990. print("mode = max")
  991. print('mean of dA = ', np.mean(dA))
  992. print('dA_prev[1,1] = ', dA_prev[1,1])  
  993. print()
  994. dA_prev = pool_backward(dA, cache, mode = "average")
  995. print("mode = average")
  996. print('mean of dA = ', np.mean(dA))
  997. print('dA_prev[1,1] = ', dA_prev[1,1])
  998.  
  999.  
  1000. # **Expected Output**:
  1001. #
  1002. # mode = max:
  1003. # <table>
  1004. # <tr>
  1005. # <td>
  1006. #
  1007. # **mean of dA =**
  1008. # </td>
  1009. #
  1010. # <td>
  1011. #
  1012. # 0.145713902729
  1013. #
  1014. #   </td>
  1015. # </tr>
  1016. #
  1017. # <tr>
  1018. # <td>
  1019. # **dA_prev[1,1] =**
  1020. # </td>
  1021. # <td>
  1022. # [[ 0.          0.        ] <br>
  1023. #  [ 5.05844394 -1.68282702] <br>
  1024. #  [ 0.          0.        ]]
  1025. # </td>
  1026. # </tr>
  1027. # </table>
  1028. #
  1029. # mode = average
  1030. # <table>
  1031. # <tr>
  1032. # <td>
  1033. #
  1034. # **mean of dA =**
  1035. # </td>
  1036. #
  1037. # <td>
  1038. #
  1039. # 0.145713902729
  1040. #
  1041. #   </td>
  1042. # </tr>
  1043. #
  1044. # <tr>
  1045. # <td>
  1046. # **dA_prev[1,1] =**
  1047. # </td>
  1048. # <td>
  1049. # [[ 0.08485462  0.2787552 ] <br>
  1050. #  [ 1.26461098 -0.25749373] <br>
  1051. #  [ 1.17975636 -0.53624893]]
  1052. # </td>
  1053. # </tr>
  1054. # </table>
  1055.  
  1056. # ### Congratulations !
  1057. #
  1058. # Congratulation on completing this assignment. You now understand how convolutional neural networks work. You have implemented all the building blocks of a neural network. In the next assignment you will implement a ConvNet using TensorFlow.
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top