Learning Guides
Convolutional Neural Networks (CNN) in Python: Complete Guide
Quick answer: Learn Convolutional Neural Networks including convolution, pooling, and fully connected layers, with a complete image classification example in Python using Keras.
What is a Convolutional Neural Network?
A Convolutional Neural Network, or CNN, is a deep learning architecture designed specifically for grid-like data such as images. It uses filters that scan across the image to detect local patterns like edges and textures, then combines them in deeper layers to recognise increasingly complex shapes.
The Convolution Layer
A small filter, or kernel, slides across the image, computing a weighted sum at each position to produce a feature map highlighting where a specific pattern, such as a vertical edge, appears in the image.
from tensorflow.keras import layers, models
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
])
32 here means 32 different filters are learned, each detecting a different pattern.
The Pooling Layer
Pooling reduces the spatial size of the feature maps, keeping the most important information while reducing computation and making the model less sensitive to the exact position of a feature.
layers.MaxPooling2D((2, 2))
Max pooling takes the largest value from each small region, effectively downsampling the feature map by a factor of 2 in each dimension here.
A Complete CNN for Image Classification
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax') # 10 output classes
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(X_train, y_train, epochs=10, validation_data=(X_test, y_test))
Why Flatten Before the Dense Layers
Convolution and pooling layers output multi-dimensional feature maps. The Flatten layer converts this into a single long vector so it can be fed into standard fully connected Dense layers, which perform the final classification based on the extracted features.
Why CNNs Outperform Plain Neural Networks on Images
A standard fully connected network treats every pixel independently with no awareness of spatial relationships, and would need an enormous number of parameters for a realistically sized image. CNNs exploit the fact that meaningful patterns in images are local and repeated across the image, using far fewer parameters through shared filter weights while capturing spatial structure directly.
Data Augmentation
Since CNNs typically need substantial data to train well, augmentation techniques like random rotation, flipping and zooming artificially expand the effective training set from existing images, helping reduce overfitting.
Common Interview Questions
Why does a CNN use far fewer parameters than a fully connected network on the same image?
Because each filter's weights are shared across the entire image rather than having a separate independent weight for every pixel connection, dramatically reducing the total parameter count.
What is the purpose of the pooling layer?
It reduces the spatial size of feature maps, cutting computation and making the model less sensitive to the exact pixel position of a detected feature.
FAQ
Frequently Asked Questions
What is a Convolutional Neural Network used for?
It is a deep learning architecture designed for grid-like data such as images, using filters to detect local patterns like edges and combining them to recognise more complex shapes.
What does the pooling layer do in a CNN?
It reduces the spatial size of feature maps, cutting computation and making the model less sensitive to the exact position of a detected feature.
Why do CNNs use far fewer parameters than a plain fully connected network on images?
Because each filter's weights are shared across the entire image, rather than needing a separate weight for every individual pixel connection.
What is data augmentation used for with CNNs?
Artificially expanding the training set through techniques like rotation and flipping, since CNNs typically need substantial data and augmentation helps reduce overfitting.
Keep Reading
Related Articles
Learning Guides
INNER JOIN in SQL with Examples: Complete Beginner's Guide
Learn INNER JOIN in SQL with practical examples, syntax, interview questions, and real-world use cases. A complete beginner-friendly SQL JOI
Learning Guides
OUTER JOIN in SQL: Complete Guide with Examples for Beginners
Master OUTER JOIN in SQL with practical examples and real-world scenarios. Learn LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, syntax, use cases,
Learning Guides
Multi-Row Functions in SQL: Complete Guide with Examples
Learn multi-row (aggregate) functions in SQL including SUM, AVG, COUNT, MIN, MAX, GROUP BY and HAVING, with practical examples, NULL handlin