[关闭]
@mShuaiZhao 2018-01-15T02:55:31.000000Z 字数 20098 阅读 464

week01.Ng's CNN Course Homework

Coursera 2018.01


这个是《deeplearning.ai》课程的作业笔记,仅供个人复习之用,若侵权的可以联系1696144426@qq.com删除。

Convolutional Neural Networks: Step by Step

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.

Notation:
- Superscript denotes an object of the layer.
- Example: is the layer activation. and are the layer parameters.

We assume that you are already familiar with numpy and/or have completed the previous courses of the specialization. Let's get started!

1 - Packages

Let's first import all the packages that you will need during this assignment.
- numpy is the fundamental package for scientific computing with Python.
- matplotlib is a library to plot graphs in Python.
- np.random.seed(1) is used to keep all the random function calls consistent. It will help us grade your work.

  1. import numpy as np
  2. import h5py
  3. import matplotlib.pyplot as plt
  4. %matplotlib inline
  5. plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
  6. plt.rcParams['image.interpolation'] = 'nearest'
  7. plt.rcParams['image.cmap'] = 'gray'
  8. %load_ext autoreload
  9. %autoreload
  10. np.random.seed(1)

2 - Outline of the Assignment

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:

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:

<img src="images/model.png" style="width:800px;height:300px;">

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.

3 - Convolutional Neural Networks

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.

<img src="images/conv_nn.png" style="width:350px;height:200px;">

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.

3.1 - Zero-Padding

Zero-padding adds zeros around the border of an image:

<img src="images/PAD.png" style="width:600px;height:400px;">

Figure 1 : Zero-Padding
Image (3 channels, RGB) with a padding of 2.

The main benefits of padding are the following:

Exercise: Implement the following function, which pads all the images of a batch of examples X with zeros. Use np.pad. Note if you want to pad the array "a" of shape with pad = 1 for the 2nd dimension, pad = 3 for the 4th dimension and pad = 0 for the rest, you would do:

  1. a = np.pad(a, ((0,0), (1,1), (0,0), (3,3), (0,0)), 'constant', constant_values = (..,..))
  1. # GRADED FUNCTION: zero_pad
  2. def zero_pad(X, pad):
  3. """
  4. Pad with zeros all images of the dataset X. The padding is applied to the height and width of an image,
  5. as illustrated in Figure 1.
  6. Argument:
  7. X -- python numpy array of shape (m, n_H, n_W, n_C) representing a batch of m images
  8. pad -- integer, amount of padding around each image on vertical and horizontal dimensions
  9. Returns:
  10. X_pad -- padded image of shape (m, n_H + 2*pad, n_W + 2*pad, n_C)
  11. """
  12. ### START CODE HERE ### (≈ 1 line)
  13. X_pad = np.pad(X, ((0,0), (pad, pad), (pad, pad), (0, 0)), 'constant', constant_values = 0 )
  14. ### END CODE HERE ###
  15. return X_pad
  1. np.random.seed(1)
  2. x = np.random.randn(4, 3, 3, 2)
  3. x_pad = zero_pad(x, 2)
  4. print ("x.shape =", x.shape)
  5. print ("x_pad.shape =", x_pad.shape)
  6. print ("x[1,1] =", x[1,1])
  7. print ("x_pad[1,1] =", x_pad[1,1])
  8. fig, axarr = plt.subplots(1, 2)
  9. axarr[0].set_title('x')
  10. axarr[0].imshow(x[0,:,:,0])
  11. axarr[1].set_title('x_pad')
  12. axarr[1].imshow(x_pad[0,:,:,0])
  1. x.shape = (4, 3, 3, 2)
  2. x_pad.shape = (4, 7, 7, 2)
  3. x[1,1] = [[ 0.90085595 -0.68372786]
  4. [-0.12289023 -0.93576943]
  5. [-0.26788808 0.53035547]]
  6. x_pad[1,1] = [[ 0. 0.]
  7. [ 0. 0.]
  8. [ 0. 0.]
  9. [ 0. 0.]
  10. [ 0. 0.]
  11. [ 0. 0.]
  12. [ 0. 0.]]

3.2 - Single step of convolution

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:

<img src="images/Convolution_schematic.gif" style="width:500px;height:300px;">

Figure 2 : Convolution operation
with a filter of 2x2 and a stride of 1 (stride = amount you move the window each time you slide)

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.

Later in this notebook, you'll apply this function to multiple positions of the input to implement the full convolutional operation.

Exercise: Implement conv_single_step(). Hint.

  1. # GRADED FUNCTION: conv_single_step
  2. def conv_single_step(a_slice_prev, W, b):
  3. """
  4. Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation
  5. of the previous layer.
  6. Arguments:
  7. a_slice_prev -- slice of input data of shape (f, f, n_C_prev)
  8. W -- Weight parameters contained in a window - matrix of shape (f, f, n_C_prev)
  9. b -- Bias parameters contained in a window - matrix of shape (1, 1, 1)
  10. Returns:
  11. Z -- a scalar value, result of convolving the sliding window (W, b) on a slice x of the input data
  12. """
  13. ### START CODE HERE ### (≈ 2 lines of code)
  14. # Element-wise product between a_slice and W. Do not add the bias yet.
  15. s = a_slice_prev * W
  16. # Sum over all entries of the volume s.
  17. Z = np.sum( s )
  18. # Add bias b to Z. Cast b to a float() so that Z results in a scalar value.
  19. Z = Z + b
  20. ### END CODE HERE ###
  21. return Z
  1. np.random.seed(1)
  2. a_slice_prev = np.random.randn(4, 4, 3)
  3. W = np.random.randn(4, 4, 3)
  4. b = np.random.randn(1, 1, 1)
  5. Z = conv_single_step(a_slice_prev, W, b)
  6. print("Z =", Z)
  1. Z = [[[-6.99908945]]]

3.3 - Convolutional Neural Networks - Forward pass

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:


conv_kiank.mp4未知大小

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.

Hint:
1. To select a 2x2 slice at the upper left corner of a matrix "a_prev" (shape (5,5,3)), you would do:

  1. a_slice_prev = a_prev[0:2,0:2,:]

This will be useful when you will define a_slice_prev below, using the start/end indexes you will define.
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.

<img src="images/vert_horiz_kiank.png" style="width:400px;height:300px;">

Figure 3 : Definition of a slice using vertical and horizontal start/end (with a 2x2 filter)
This figure shows only a single channel.

Reminder:
The formulas relating the output shape of the convolution to the input shape is:



For this exercise, we won't worry about vectorization, and will just implement everything with for-loops.

  1. # GRADED FUNCTION: conv_forward
  2. def conv_forward(A_prev, W, b, hparameters):
  3. """
  4. Implements the forward propagation for a convolution function
  5. Arguments:
  6. A_prev -- output activations of the previous layer, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)
  7. W -- Weights, numpy array of shape (f, f, n_C_prev, n_C)
  8. b -- Biases, numpy array of shape (1, 1, 1, n_C)
  9. hparameters -- python dictionary containing "stride" and "pad"
  10. Returns:
  11. Z -- conv output, numpy array of shape (m, n_H, n_W, n_C)
  12. cache -- cache of values needed for the conv_backward() function
  13. """
  14. ### START CODE HERE ###
  15. # Retrieve dimensions from A_prev's shape (≈1 line)
  16. (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape
  17. # Retrieve dimensions from W's shape (≈1 line)
  18. (f, f, n_C_prev, n_C) = W.shape
  19. # Retrieve information from "hparameters" (≈2 lines)
  20. stride = hparameters['stride']
  21. pad = hparameters['pad']
  22. # Compute the dimensions of the CONV output volume using the formula given above. Hint: use int() to floor. (≈2 lines)
  23. n_H = int( ( n_H_prev - f + 2 * pad) / stride ) + 1
  24. n_W = int( ( n_W_prev - f + 2 * pad) / stride ) + 1
  25. # Initialize the output volume Z with zeros. (≈1 line)
  26. Z = np.zeros( (m, n_H, n_W, n_C) )
  27. # Create A_prev_pad by padding A_prev
  28. A_prev_pad = zero_pad(A_prev, pad)
  29. for i in range(m): # loop over the batch of training examples
  30. a_prev_pad = A_prev_pad[i, :, :, :] # Select ith training example's padded activation
  31. for h in range(n_H): # loop over vertical axis of the output volume
  32. for w in range(n_W): # loop over horizontal axis of the output volume
  33. for c in range( n_C ): # loop over channels (= #filters) of the output volume
  34. # Find the corners of the current "slice" (≈4 lines)
  35. vert_start = h * stride
  36. vert_end = h * stride + f
  37. horiz_start = w * stride
  38. horiz_end = w *stride + f
  39. # Use the corners to define the (3D) slice of a_prev_pad (See Hint above the cell). (≈1 line)
  40. a_slice_prev = a_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :]
  41. # Convolve the (3D) slice with the correct filter W and bias b, to get back one output neuron. (≈1 line)
  42. Z[i, h, w, c] = conv_single_step(a_slice_prev, W[:, :, :, c], b[:, :, :, c] )
  43. ### END CODE HERE ###
  44. # Making sure your output shape is correct
  45. assert(Z.shape == (m, n_H, n_W, n_C))
  46. # Save information in "cache" for the backprop
  47. cache = (A_prev, W, b, hparameters)
  48. return Z, cache
  1. np.random.seed(1)
  2. A_prev = np.random.randn(10,4,4,3)
  3. W = np.random.randn(2,2,3,8)
  4. b = np.random.randn(1,1,1,8)
  5. hparameters = {"pad" : 2,
  6. "stride": 2}
  7. Z, cache_conv = conv_forward(A_prev, W, b, hparameters)
  8. print("Z's mean =", np.mean(Z))
  9. print("Z[3,2,1] =", Z[3,2,1])
  10. print("cache_conv[0][7][2][8] =", cache_conv[0][9][2][10])
  1. Z's mean = 0.0489952035289
  2. Z[3,2,1] = [-0.61490741 -6.7439236 -2.55153897 1.75698377 3.56208902 0.53036437
  3. 5.18531798 8.75898442]
  4. cache_conv[0][11][2][12] = [-0.20075807 0.18656139 0.41005165]

Finally, CONV layer should also contain an activation, in which case we would add the following line of code:

  1. # Convolve the window to get back one output neuron
  2. Z[i, h, w, c] = ...
  3. # Apply activation
  4. A[i, h, w, c] = activation(Z[i, h, w, c])

You don't need to do it here.

4 - Pooling layer

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:

<img src="images/max_pool1.png" style="width:500px;height:300px;">

<img src="images/a_pool.png" style="width:500px;height:300px;">

These pooling layers have no parameters for backpropagation to train. However, they have hyperparameters such as the window size . This specifies the height and width of the fxf window you would compute a max or average over.

4.1 - Forward Pooling

Now, you are going to implement MAX-POOL and AVG-POOL, in the same function.

Exercise: Implement the forward pass of the pooling layer. Follow the hints in the comments below.

Reminder:
As there's no padding, the formulas binding the output shape of the pooling to the input shape is:



  1. # GRADED FUNCTION: pool_forward
  2. def pool_forward(A_prev, hparameters, mode = "max"):
  3. """
  4. Implements the forward pass of the pooling layer
  5. Arguments:
  6. A_prev -- Input data, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)
  7. hparameters -- python dictionary containing "f" and "stride"
  8. mode -- the pooling mode you would like to use, defined as a string ("max" or "average")
  9. Returns:
  10. A -- output of the pool layer, a numpy array of shape (m, n_H, n_W, n_C)
  11. cache -- cache used in the backward pass of the pooling layer, contains the input and hparameters
  12. """
  13. # Retrieve dimensions from the input shape
  14. (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape
  15. # Retrieve hyperparameters from "hparameters"
  16. f = hparameters["f"]
  17. stride = hparameters["stride"]
  18. # Define the dimensions of the output
  19. n_H = int(1 + (n_H_prev - f) / stride)
  20. n_W = int(1 + (n_W_prev - f) / stride)
  21. n_C = n_C_prev
  22. # Initialize output matrix A
  23. A = np.zeros((m, n_H, n_W, n_C))
  24. ### START CODE HERE ###
  25. for i in range(m): # loop over the training examples
  26. for h in range(n_H): # loop on the vertical axis of the output volume
  27. for w in range(n_W): # loop on the horizontal axis of the output volume
  28. for c in range (n_C): # loop over the channels of the output volume
  29. # Find the corners of the current "slice" (≈4 lines)
  30. vert_start = h * stride
  31. vert_end = h * stride + f
  32. horiz_start = w * stride
  33. horiz_end = w *stride + f
  34. # Use the corners to define the current slice on the ith training example of A_prev, channel c. (≈1 line)
  35. a_prev_slice = A_prev[i, vert_start:vert_end, horiz_start:horiz_end, c]
  36. # Compute the pooling operation on the slice. Use an if statment to differentiate the modes. Use np.max/np.mean.
  37. if mode == "max":
  38. A[i, h, w, c] = np.max( a_prev_slice )
  39. elif mode == "average":
  40. A[i, h, w, c] = np.mean( a_prev_slice )
  41. ### END CODE HERE ###
  42. # Store the input and hparameters in "cache" for pool_backward()
  43. cache = (A_prev, hparameters)
  44. # Making sure your output shape is correct
  45. assert(A.shape == (m, n_H, n_W, n_C))
  46. return A, cache
  1. np.random.seed(1)
  2. A_prev = np.random.randn(2, 4, 4, 3)
  3. hparameters = {"stride" : 2, "f": 3}
  4. A, cache = pool_forward(A_prev, hparameters)
  5. print("mode = max")
  6. print("A =", A)
  7. print()
  8. A, cache = pool_forward(A_prev, hparameters, mode = "average")
  9. print("mode = average")
  10. print("A =", A)
  1. mode = max
  2. A = [[[[ 1.74481176 0.86540763 1.13376944]]]
  3. [[[ 1.13162939 1.51981682 2.18557541]]]]
  4. mode = average
  5. A = [[[[ 0.02105773 -0.20328806 -0.40389855]]]
  6. [[[-0.22154621 0.51716526 0.48155844]]]]

5 - Backpropagation in convolutional neural networks (OPTIONAL / UNGRADED)

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.

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.

5.1 - Convolutional layer backward pass

Let's start by implementing the backward pass for a CONV layer.

5.1.1 - Computing dA:

This is the formula for computing with respect to the cost for a certain filter and a given training example:

Where is a filter and 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 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.

In code, inside the appropriate for-loops, this formula translates into:

  1. da_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] += W[:,:,:,c] * dZ[i, h, w, c]

5.1.2 - Computing dW:

This is the formula for computing ( is the derivative of one filter) with respect to the loss:

Where corresponds to the slice which was used to generate the acitivation . Hence, this ends up giving us the gradient for with respect to that slice. Since it is the same , we will just add up all such gradients to get .

In code, inside the appropriate for-loops, this formula translates into:

  1. dW[:,:,:,c] += a_slice * dZ[i, h, w, c]

5.1.3 - Computing db:

This is the formula for computing with respect to the cost for a certain filter :

As you have previously seen in basic neural networks, db is computed by summing . In this case, you are just summing over all the gradients of the conv output (Z) with respect to the cost.

In code, inside the appropriate for-loops, this formula translates into:

  1. db[:,:,:,c] += dZ[i, h, w, c]

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.

  1. def conv_backward(dZ, cache):
  2. """
  3. Implement the backward propagation for a convolution function
  4. Arguments:
  5. 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)
  6. cache -- cache of values needed for the conv_backward(), output of conv_forward()
  7. Returns:
  8. dA_prev -- gradient of the cost with respect to the input of the conv layer (A_prev),
  9. numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)
  10. dW -- gradient of the cost with respect to the weights of the conv layer (W)
  11. numpy array of shape (f, f, n_C_prev, n_C)
  12. db -- gradient of the cost with respect to the biases of the conv layer (b)
  13. numpy array of shape (1, 1, 1, n_C)
  14. """
  15. ### START CODE HERE ###
  16. # Retrieve information from "cache"
  17. (A_prev, W, b, hparameters) = cache
  18. # Retrieve dimensions from A_prev's shape
  19. (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape
  20. # Retrieve dimensions from W's shape
  21. (f, f, n_C_prev, n_C) = W.shape
  22. # Retrieve information from "hparameters"
  23. stride = hparameters['stride']
  24. pad = hparameters['pad']
  25. # Retrieve dimensions from dZ's shape
  26. (m, n_H, n_W, n_C) = dZ.shape
  27. # Initialize dA_prev, dW, db with the correct shapes
  28. dA_prev = np.zeros( (m, n_H_prev, n_W_prev, n_C_prev) )
  29. dW = np.zeros( (f, f, n_C_prev, n_C) )
  30. db = np.zeros( (1, 1, 1, n_C) )
  31. # Pad A_prev and dA_prev
  32. A_prev_pad = zero_pad(A_prev, pad)
  33. dA_prev_pad = zero_pad(dA_prev, pad)
  34. for i in range(m): # loop over the training examples
  35. # select ith training example from A_prev_pad and dA_prev_pad
  36. a_prev_pad = A_prev_pad[i, :, :, :]
  37. da_prev_pad = dA_prev_pad[i, :, :, :]
  38. for h in range(n_H): # loop over vertical axis of the output volume
  39. for w in range(n_W): # loop over horizontal axis of the output volume
  40. for c in range(n_C): # loop over the channels of the output volume
  41. # Find the corners of the current "slice"
  42. vert_start = h * stride
  43. vert_end = h * stride + f
  44. horiz_start = w * stride
  45. horiz_end = w *stride + f
  46. # Use the corners to define the slice from a_prev_pad
  47. a_slice = a_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :]
  48. # Update gradients for the window and the filter's parameters using the code formulas given above
  49. da_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] += W[:,:,:,c] * dZ[i, h, w, c]
  50. dW[:,:,:,c] += a_slice * dZ[i, h, w, c]
  51. db[:,:,:,c] += dZ[i, h, w, c]
  52. # Set the ith training example's dA_prev to the unpaded da_prev_pad (Hint: use X[pad:-pad, pad:-pad, :])
  53. dA_prev[i, :, :, :] = da_prev_pad[pad:-pad, pad:-pad, :]
  54. ### END CODE HERE ###
  55. # Making sure your output shape is correct
  56. assert(dA_prev.shape == (m, n_H_prev, n_W_prev, n_C_prev))
  57. return dA_prev, dW, db
  1. np.random.seed(1)
  2. dA, dW, db = conv_backward(Z, cache_conv)
  3. print("dA_mean =", np.mean(dA))
  4. print("dW_mean =", np.mean(dW))
  5. print("db_mean =", np.mean(db))

5.2 Pooling layer - backward pass

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.

5.2.1 Max pooling - backward pass

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:

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.

Exercise: Implement create_mask_from_window(). This function will be helpful for pooling backward.
Hints:
- np.max() may be helpful. It computes the maximum of an array.
- 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:

  1. A[i,j] = True if X[i,j] = x
  2. A[i,j] = False if X[i,j] != x
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注