Keras Conv2D with examples in Python

Keras is a Python library to implement neural networks. This article is going to provide you with information on the Conv2D class of Keras. It is a class to implement a 2-D convolution layer on your CNN. It takes a 2-D image array as input and provides a tensor of outputs.

Conv2D class looks like this:

keras.layers.Conv2D(
    filters,
    kernel_size,
    strides=(1, 1),
    padding="valid",
    data_format=None,
    dilation_rate=(1, 1),
    activation=None,
    use_bias=True,
    kernel_initializer="glorot_uniform",
    bias_initializer="zeros",
    kernel_regularizer=None,
    bias_regularizer=None,
    activity_regularizer=None,
    kernel_constraint=None,
    bias_constraint=None,
    **kwargs
)

Let’s look at these parameters with an example.

keras.layers.Conv2D in Python


Firstly, make sure that you have Keras installed on your system. If not, follow the steps mentioned here. To check whether it is successfully installed or not, use the following command in your terminal or command prompt. The latest version of Keras is 2.2.4, as of the date of this article.

python -c "import keras; print(keras.__version__)"

Let’s import the necessary libraries and Conv2D class for our example

from keras.layers import Conv2D
import tensorflow as tf

Now we will provide an input to our Conv2D layer. We use tf.random.normal function to randomly initialize our input. Here input_shape is of the format (batch_size, height, width, filters).

input_shape = (4, 128, 128, 3)
X = tf.random.normal(input_shape)
print(X.shape)

Output of the code is the same as input_shape:

(4, 128, 128, 3)

Now, we calculate over convolution with following important parameters

Y = Conv2D(input_shape=input_shape, kernel_size=(2,2), filters=6, strides=(1, 1), padding="same")(X)
print(Y.shape)

Output:

(4, 128, 128, 6)

Let’s look at each parameter:

  • input_shape=input_shape; to be provided only for the starting Conv2D block
  • kernel_size=(2,2); the size of the array that is going to calculate convolutions on the input (X in this case)
  • filters=6; # of channels in the output tensor
  • strides=(1,1); strides of the convolution along height and width
  • padding=”same”; keeps the (height, width) of output similar to input

Let’s change the filters and padding parameters to see the difference

Y = Conv2D(input_shape=input_shape, kernel_size=(2,2), filters=4, strides=(2,2), padding="valid")(X)
print(Y.shape)

Output:

(4, 64, 64, 4)

Conv2D is a basic building block of a CNN architecture and it has a huge scope of applications. This article is all about the basics of the Conv2D class. For in-depth study of CNNs, refer the following:

Let us know in the comments if you have any queries. Cheers!

Leave a Reply