DLS, Course 4, Week 1 Assignment 1, Ex. 3.1 - Zero-Padding

Hello,

I have question about zero-padding.
“Ex. 3.1 - Zero-Padding (Exercise 1 - zero_pad)” instructions are:

Why do we use the “constant_values” argument of the np.pad() function as (0, 0)? The np.pad() documentation states:

Constant_Values

So, for zero-padding, we should set “constant_values” to zero.

However, the example in the exercise instruction specifies a non-zero padding: “you want to pad the array “a” of shape (5,5,5,5,5)(5,5,5,5,5) with pad = 1 for the 2nd dimension, pad = 3 for the 4th dimension and pad = 0 for the rest.”).

Could you please clarify this?

Thanks in advance!

Hello Veronika,

In Exercise 1 - zero_pad, the goal is to implement zero-padding for a batch of images, which means adding a border of zeros around each image. The constant_values argument in the np.pad() function allows you to specify which values to use for padding, and by default, it’s set to zero, which is exactly what we want for zero-padding.

In the example provided:

a = np.pad(a, ((0,0), (1,1), (0,0), (3,3), (0,0)), mode='constant', constant_values=(0,0))

The instruction specifies how much padding to apply along each axis:

  • ((0,0), (1,1), (0,0), (3,3), (0,0)) tells us to:
    • Not pad the 1st axis (no padding: (0,0)),
    • Pad the 2nd axis by 1 on both sides ((1,1)),
    • Not pad the 3rd axis ((0,0)),
    • Pad the 4th axis by 3 on both sides ((3,3)),
    • Not pad the 5th axis ((0,0)).

The constant_values argument is set to (0,0) to ensure the padding is zero, consistent with zero-padding. This means that the padding should be filled with zeros, which is the typical behavior for zero-padding. This is just an explicit way to ensure that zeros are used for padding. The default value of constant_values is zero, so explicitly writing (0,0) isn’t necessary in this case, but it’s done for clarity.

In the zero_pad function, you’ll follow the same pattern, making sure the padding uses zeros around the images, and you can either leave the constant_values argument at its default value or set it explicitly to (0,0).

Hope this helps!

2 Likes

@nadtriana Thanks for helpful explanation!

1 Like