DEV Community

Cover image for Convolutional Neural Networks (CNN): A Beginner’s Guide with Python
nuz14
nuz14

Posted on Edited on

Convolutional Neural Networks (CNN): A Beginner’s Guide with Python

Have you ever wondered how computers recognize objects in photographs? For example, how does your phone identify a face, or how can an application recognize whether an image contains a cat or a dog?

These tasks are made possible through a deep learning technique called Convolutional Neural Networks (CNNs).

CNNs are widely used in image recognition, computer vision, medical imaging, and many other applications.

In this article, we will understand what CNNs are, how they work, their main components, and how to build a simple image classification model using Python.

What is a Convolutional Neural Network?

A Convolutional Neural Network is a type of deep learning model mainly designed to work with images.

Unlike traditional machine learning models, CNNs can automatically identify important features from images, such as edges, shapes, textures, and patterns.

For example, if we train a CNN to recognize cats and dogs, it gradually learns to identify features that help distinguish between the two animals.

It learns these features directly from the training images instead of requiring us to manually define them.

How Does a CNN Work?

A CNN processes an image through multiple layers. Each layer performs a specific task to help the model understand the image.

The general process includes:

  1. Input image: The image is provided to the model.
  2. Convolution: Filters scan the image and identify important features.
  3. ReLU activation: Helps the model learn complex patterns.
  4. Pooling: Reduces the size of the feature maps while keeping important information.
  5. Flattening: Converts the extracted features into a one-dimensional structure.
  6. Fully Connected Layer: Uses the extracted information to make a prediction.
  7. Output: Produces the final predicted category.

Important Components of CNN

Let's understand the main components in simple terms.

1. Convolutional Layer

The convolutional layer is responsible for identifying features in an image.

It uses small filters, also called kernels, that move across the image and detect patterns.

For example, these filters can identify:

  • Edges
  • Lines
  • Corners
  • Shapes
  • Textures

As the network becomes deeper, it can learn more complex features.

2. ReLU Activation Function

ReLU stands for Rectified Linear Unit.

It is an activation function that replaces negative values with zero while keeping positive values unchanged.

For example:

Input:  -5,  2,  -3,  7
Output:  0,  2,   0,  7
Enter fullscreen mode Exit fullscreen mode

It helps the network learn complex patterns.

3. Pooling Layer

The pooling layer reduces the size of the feature maps.

One commonly used method is Max Pooling.

It selects the largest value from a small region.

For example:

2  4
1  3
Enter fullscreen mode Exit fullscreen mode

The maximum value is 4.

Pooling reduces the amount of information the network needs to process while retaining important features.

4. Flattening Layer

After convolution and pooling, the extracted features are converted into a one-dimensional list.

This process is called flattening.

It prepares the information for the fully connected layers.

5. Fully Connected Layer

The fully connected layer uses the extracted features to make a final decision.

For example, it may use the learned features to predict whether an image contains a cat or a dog.

6. Output Layer

The output layer provides the final prediction.

For a classification problem involving two categories, the model can predict the probability of each category.

Building a CNN Using Python

Now let's build a simple CNN using Python.

For this example, we will use the MNIST dataset, which contains handwritten digits from 0 to 9.

Our goal is to train a CNN that can recognize handwritten numbers from images.

We will use TensorFlow and Keras to create the model.

Step 1: Import the libraries

import tensorflow as tf
import numpy as np
from tensorflow.keras import layers, models
Enter fullscreen mode Exit fullscreen mode

Understanding the code:

  • tensorflow: Provides tools for building and training deep learning models.
  • numpy: Helps us work with numerical data.
  • layers: Provides different neural network layers.
  • models: Helps us create and organize the neural network.

Step 2: Load the dataset

(X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()

print("Training images:", X_train.shape)
print("Testing images:", X_test.shape)
Enter fullscreen mode Exit fullscreen mode

The MNIST dataset contains handwritten digit images.

Each image is 28 × 28 pixels.

The dataset is divided into two parts:

  • Training data: Used to teach the model.
  • Testing data: Used to check how well the trained model performs.

Here, X_train contains the training images, while y_train contains their correct digit labels.

Similarly, X_test and y_test contain the testing images and their labels.

Step 3: Normalize the images

X_train = X_train / 255.0
X_test = X_test / 255.0
Enter fullscreen mode Exit fullscreen mode

Each pixel in an image has a value between 0 and 255.

Dividing these values by 255 converts them into a range between 0 and 1.

For example:

  • 0 becomes 0.
  • 128 becomes approximately 0.50.
  • 255 becomes 1.

This process is called normalization. It helps the model work with smaller and more consistent input values.

Step 4: Prepare the image shape

X_train = X_train.reshape(-1, 28, 28, 1)
X_test = X_test.reshape(-1, 28, 28, 1)
Enter fullscreen mode Exit fullscreen mode

CNNs expect image data in a specific format.

Here:

  • 28 represents image height.
  • 28 represents image width.
  • 1 represents the number of color channels because MNIST images are grayscale.
  • -1 allows Python to automatically determine the number of images.

This step prepares the images for the CNN model.

Step 5: Create the CNN model

model = models.Sequential([
    layers.Input(shape=(28, 28, 1)),
    layers.Conv2D(32, (3, 3), activation='relu'),
    layers.MaxPooling2D((2, 2)),
    layers.Flatten(),
    layers.Dense(64, activation='relu'),
    layers.Dense(10, activation='softmax')
])
Enter fullscreen mode Exit fullscreen mode

Let's understand each layer:

  • Sequential: Creates a model where layers are arranged one after another.
  • Input: Defines the size of the input image.
  • Conv2D: Uses 32 filters to identify image features.
  • (3, 3): Defines the size of each filter.
  • MaxPooling2D: Reduces the size of the extracted feature maps.
  • Flatten: Converts the extracted features into a one-dimensional structure.
  • Dense(64): Creates a fully connected layer with 64 neurons.
  • Dense(10): Produces predictions for the 10 possible digits (0 to 9).

The relu activation helps the network learn patterns, while softmax converts the final outputs into probabilities.

Step 6: Compile the model

model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)
Enter fullscreen mode Exit fullscreen mode

Before training, we need to configure the model.

  • optimizer='adam': Helps the model adjust its weights during training.
  • loss: Measures how far the predictions are from the correct answers.
  • accuracy: Measures how many predictions are correct.

In simple terms, this step tells the model how to learn and how its performance will be measured.

Step 7: Train the model

model.fit(
    X_train,
    y_train,
    epochs=5,
    validation_split=0.1
)
Enter fullscreen mode Exit fullscreen mode

The fit() function trains the CNN using the training dataset.

Here:

  • X_train contains the images.
  • y_train contains the correct digit labels.
  • epochs=5 means the model goes through the training dataset five times.
  • validation_split=0.1 uses 10% of the training data to check the model's performance during training.

During training, the CNN learns patterns from the handwritten digit images.

Step 8: Evaluate the model

loss, accuracy = model.evaluate(X_test, y_test)

print("Test Accuracy:", accuracy * 100, "%")
Enter fullscreen mode Exit fullscreen mode

The evaluate() function checks how well the trained model performs on the testing dataset.

The accuracy tells us how many handwritten digits the model correctly identifies.

For example, an accuracy of 95% means the model correctly identifies 95 out of every 100 test images.

The actual result may vary depending on training conditions.

Step 9: Make a prediction

image = X_test[0:1]

prediction = model.predict(image)

predicted_digit = np.argmax(prediction)

print("Predicted digit:", predicted_digit)
print("Actual digit:", y_test[0])
Enter fullscreen mode Exit fullscreen mode

Here, we take one image from the testing dataset.

  • X_test[0:1] selects the first test image.
  • model.predict() asks the trained model to identify the digit.
  • np.argmax() finds the digit with the highest predicted probability.
  • y_test[0] shows the actual digit for comparison.

This allows us to check whether the model predicted the correct number.

Complete Python Code

Here is the complete program in one place. You can copy and run it directly if TensorFlow is installed.

import tensorflow as tf
import numpy as np
from tensorflow.keras import layers, models

# Load dataset
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()

# Normalize images
X_train = X_train / 255.0
X_test = X_test / 255.0

# Prepare image shape
X_train = X_train.reshape(-1, 28, 28, 1)
X_test = X_test.reshape(-1, 28, 28, 1)

# Create CNN model
model = models.Sequential([
    layers.Input(shape=(28, 28, 1)),
    layers.Conv2D(32, (3, 3), activation='relu'),
    layers.MaxPooling2D((2, 2)),
    layers.Flatten(),
    layers.Dense(64, activation='relu'),
    layers.Dense(10, activation='softmax')
])

# Compile model
model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)

# Train model
model.fit(X_train, y_train, epochs=5, validation_split=0.1)

# Evaluate model
loss, accuracy = model.evaluate(X_test, y_test)
print("Test Accuracy:", accuracy * 100, "%")

# Make prediction
image = X_test[0:1]
prediction = model.predict(image)

print("Predicted digit:", np.argmax(prediction))
print("Actual digit:", y_test[0])
Enter fullscreen mode Exit fullscreen mode

This program demonstrates the complete CNN workflow, from loading image data to training the model, evaluating its performance, and predicting handwritten digits.

Applications of Convolutional Neural Networks

CNNs are widely used in different fields.

  • Facial Recognition: Identifying faces in photographs and security systems.
  • Healthcare: Helping analyze medical images such as X-rays and MRI scans.
  • Self-Driving Cars: Recognizing roads, traffic signs, and pedestrians.
  • Object Detection: Identifying and locating objects in images.
  • Agriculture: Detecting plant diseases using leaf images.

Advantages and Limitations of CNN

Advantages

  • Automatically identifies important image features.
  • Works effectively with image classification tasks.
  • Can learn complex visual patterns.
  • Reduces the need for manual feature extraction.

Limitations

  • Requires a large amount of training data for many tasks.
  • Training can require significant computing power.
  • Choosing the right network structure can be challenging.
  • Understanding exactly why a CNN makes a prediction can be difficult.

Conclusion

Convolutional Neural Networks are an important part of deep learning, especially in computer vision and image recognition.

In this article, we explored how CNNs work, understood their main components, and built a simple image classification model using Python and TensorFlow.

By learning convolution, pooling, flattening, and fully connected layers, we can understand how computers extract useful information from images.

CNNs provide an important foundation for exploring more advanced deep learning techniques.

In the next article, we will explore Recurrent Neural Networks (RNNs) and understand how computers process sequential data such as text and time series.

Top comments (0)