In this article, I will implement convolutional (CONV) and pooling (POOL) layers in numpy, including both forward propagation and backward propagation.

Before you read the text, I hope you remember the following symbols:

• Superscript $[l]$ denotes an object of the $l^{th}$ layer.
• Example: $a^{[4]}$ is the $4^{th}$ layer activation. $W^{[5]}$ and $b^{[5]}$ are the $5^{th}$ layer parameters.
• Superscript $(i)$ denotes an object from the $i^{th}$ example.

• Example: $x^{(i)}$ is the $i^{th}$ training example input.
• Lowerscript $i$ denotes the $i^{th}$ entry of a vector.

• Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the activations in layer $l$, assuming this is a fully connected (FC) layer.
• $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]}$.

• $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]}$.

I assume that you are already familiar with numpy and/or have completed the previous article of this deep-learning theme articles. Let’s get started!

## Outline of the Assignment

I will be implementing the building blocks of a convolutional neural network! Each function I will implement will have detailed instructions that will walk I through the steps needed:

• Convolution functions, including:
• Convolve window
• Convolution forward
• Convolution backward
• Pooling functions, including:
• Pooling forward
• Distribute value
• Pooling backward

This article will ask you to implement these functions from scratch in numpy. In the next article, I will use the TensorFlow equivalents of these functions to build the following model:

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.

## 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.

In this part, I will build every step of the convolution layer. I will first implement two helper functions: one for zero padding and the other for computing the convolution function itself.

Image (3 channels, RGB) with a padding of 2.

The main benefits of padding are the following:

• 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.

• 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.

What I implemented in the following function which pads all the images of a batch of examples X with zeros. Use np.pad. Note if we 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, we would do:

Output:

### Single step of convolution

In this part,I will implement a single step of convolution, in which I apply the filter to a single position of the input. This will be used to build a convolutional unit, which:

• Takes an input volume
• Applies a filter at every position of the input
• Outputs another volume (usually of different size)

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, I 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 article, I’ll apply this function to multiple positions of the input to implement the full convolutional operation.

### Convolutional Neural Networks - Forward pass

In the forward pass, we will take many filters and convolve them on the input. Each ‘convolution’ gives us a 2D matrix output. You will then stack these outputs to get a 3D volume:

Now I will 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 we 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)), I would do:

This will be useful when we will define a_slice_prev below, using the start/end indexes we will define.

1. To define a_slice I will need to first define its corners vert_start, vert_end, horiz_start and horiz_end. This figure may be helpful for us to find how each of the corner can be defined using h, w, f and s in the code below.

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.

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

We don’t need to do it here.

## 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:

• Max-pooling layer: slides an ($f, f$) window over the input and stores the max value of the window in the output.
• Average-pooling layer: slides an ($f, f$) window over the input and stores the average value of the window in the output.

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 we would compute a max or average over.

### Forward Pooling

Now, I am going to implement MAX-POOL and AVG-POOL, in the same function.

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

Implement:

We have now implemented the forward passes of all the layers of a convolutional network.

## Backpropagation in convolutional neural networks

In modern deep learning frameworks, we 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 portion of the article to get a sense of what backprop in a convolutional network looks like.

When in an earlier course we implemented a simple (fully connected) neural network, we used backpropagation to compute the derivatives with respect to the cost to update the parameters. Similarly, in convolutional neural networks we can to calculate the derivatives with respect to the cost in order to update the parameters. The backprop equations are not trivial I briefly presented them below.

### Convolutional layer backward pass

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

#### Computing dA:

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

Where $Wc$ 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.

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

#### Computing dW:

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

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$.

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

#### Computing db:

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

As you have previously seen in basic neural networks, db is computed by summing $dZ$. In this case, we 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:

I will implement the conv_backward function below and sum over all the training examples, filters, heights, and widths. I will then compute the derivatives using formulas 1, 2 and 3 above.

## 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, we still need to backpropagation the gradient through the pooling layer in order to compute gradients for layers that came before the pooling layer.

### Max pooling - backward pass

Before jumping into the backpropagation of the pooling layer, I am 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.

I will implement create_mask_from_window() firstly. This function will be helpful for pooling backward.
Hints:

• np.max() may be helpful. It computes the maximum of an array.
• If we have a matrix X and a scalar x: A = (X == x) will return a matrix A of the same size as X such that:

• Here, we don’t need to consider cases where there are several maxima in a matrix.

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.

### Average pooling - backward pass

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, I will now implement a helper function that reflects this.

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:

This implies that each position in the $dZ$ matrix contributes equally to output because in the forward pass, we took an average.

I will implement the function below to equally distribute a value dz through a matrix of dimension shape. Hint

### Putting it together: Pooling backward

We now have everything we need to compute backward propagation on a pooling layer.

Now I will implement the pool_backward function in both modes ("max" and "average"). I will once again use 4 for-loops (iterating over training examples, height, width, and channels). I will use an if/elif statement to see if the mode is equal to 'max' or 'average'. If it is equal to ‘average’ I will use the distribute_value() function I implemented above to create a matrix of the same shape as a_slice. Otherwise, the mode is equal to ‘max‘, and I will create a mask with create_mask_from_window() and multiply it by the corresponding value of dZ.

### Congratulations

Congratulation on completing this article. You now understand how convolutional neural networks work. You have implemented all the building blocks of a neural network. In the next article I will implement a ConvNet using TensorFlow.

Github