This tutorial explains each Keras building block you need to write a CNN, what it does and which arguments matter. In the CNN Practically tutorial we put these blocks together to classify cats and dogs.
What You Will Learn
- The five Keras classes used to build a CNN
- The key arguments of
Conv2D,MaxPooling2DandDense - How the output shape changes after each layer
- How to count the parameters of a CNN
Prerequisites
Step 1: Import the Building Blocks
from keras.models import Sequential
from keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense
Explanation: Older tutorials import Convolution2D; in current Keras the class is called Conv2D (the old name is an alias). The line import tensorflow.python.framework.dtypes seen in some old notebooks is not needed.
| Class | Purpose |
|---|---|
Sequential |
A model where layers are stacked one after another, each with one input and one output. |
Conv2D |
Applies filters to the image to detect features; each filter creates a feature map. |
MaxPooling2D |
Keeps the maximum value in each window (e.g. 2×2) to shrink the feature maps. |
Flatten |
Reshapes the 2-D feature maps into a 1-D vector. |
Dense |
A fully connected layer; the last one gives the prediction. |
Step 2: Conv2D Arguments
Conv2D(filters=32, kernel_size=(3, 3), strides=1, padding='valid', activation='relu')
| Argument | Meaning |
|---|---|
filters |
How many features to learn (number of feature maps). 32 or 64 is common. |
kernel_size |
Size of each filter, usually (3, 3). |
strides |
How far the filter moves each step. 1 = every pixel. |
padding |
"valid" = no padding (output shrinks); "same" = pad so output has the same size. |
activation |
Usually "relu". |
Step 3: Build and Inspect a Small CNN
model = Sequential([
Input(shape=(64, 64, 3)),
Conv2D(32, (3, 3), activation='relu'),
MaxPooling2D(pool_size=(2, 2)),
Conv2D(32, (3, 3), activation='relu'),
MaxPooling2D(pool_size=(2, 2)),
Flatten(),
Dense(128, activation='relu'),
Dense(1, activation='sigmoid')
])
model.summary()
Explanation: Each 3×3 convolution with "valid" padding removes 2 pixels from width and height, and each 2×2 pooling halves them (rounding down).
Layer (type) Output Shape Param # conv2d (Conv2D) (None, 62, 62, 32) 896 max_pooling2d (MaxPooling2D) (None, 31, 31, 32) 0 conv2d_1 (Conv2D) (None, 29, 29, 32) 9,248 max_pooling2d_1 (MaxPooling2D) (None, 14, 14, 32) 0 flatten (Flatten) (None, 6272) 0 dense (Dense) (None, 128) 802,944 dense_1 (Dense) (None, 1) 129 Total params: 813,217
How the Parameters Are Counted
| Layer | Calculation | Params |
|---|---|---|
| Conv2D #1 | (3 × 3 × 3 inputs + 1 bias) × 32 | 896 |
| Conv2D #2 | (3 × 3 × 32 + 1) × 32 | 9,248 |
| Flatten | 14 × 14 × 32 values, no weights | 0 |
| Dense 128 | 6272 × 128 + 128 | 802,944 |
| Dense 1 | 128 + 1 | 129 |
Step 4: Compile
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
Explanation: For two classes use one sigmoid output and binary_crossentropy. For more classes use Dense(n, activation="softmax") with categorical_crossentropy.
Summary of the Roles
- Sequential builds a linear stack of layers.
- Conv2D extracts features with filters.
- MaxPooling2D reduces size and keeps the strongest signals.
- Flatten turns maps into a vector.
- Dense makes the final decision.
Common Errors
| Problem | Cause and fix |
|---|---|
ImportError: cannot import name Convolution2D |
Use Conv2D. |
| Negative dimension error | The image became too small after many conv/pool layers; use a bigger input or padding="same". |
UserWarning about input_shape |
Add an Input(shape=...) layer first. |
Series
Deep Learning series: Introduction to Deep Learning · AI vs ML vs DL · Introduction to ANN · ANN – Plan of Attack · ANN Practical · Introduction to CNN · CNN Steps · CNN Practically · Introduction to RNN · RNN Steps · RNN Practically
Interview Questions
Q: Why do pooling layers have 0 parameters?
They only take a max (or mean); there is nothing to learn.
Q: What does padding=”same” do?
Adds zeros around the input so the output has the same width and height.
Practice Exercises
- Change the first layer to 64 filters and recalculate the parameters.
- Add a third Conv2D + MaxPooling2D block and check the new Flatten size.
Summary
A Keras CNN is built from Sequential, Conv2D, MaxPooling2D, Flatten and Dense. Knowing how shapes and parameters change after each layer helps you design and debug models.
Next: CNN Practically
Machine Learning Tutorials, Courses and Certifications