Pulse Data Hub

Convolutional Neural Networks (CNNs) Explained, with a Keras Example

A convolutional neural network (CNN) is the standard type of neural network for images. Instead of looking at every pixel separately, it slides small filters across the image to find edges, textures and shapes, then combines them to recognize objects.

This guide explains how a CNN works step by step, with a convolution and a pooling layer written out in a few lines of NumPy, then builds and trains a real CNN in Keras on 70,000 clothing images. Every output shown is what the code printed when we ran it.

What a CNN does, in one paragraph

A CNN is a stack of layers. Convolutional layers slide small grids of weights, called filters or kernels, over the image and record how strongly each patch matches each filter. Pooling layers shrink the result, keeping the strongest signals. Early layers learn simple patterns such as edges; later layers combine them into parts such as collars, soles or handles. At the end, a dense layer turns those features into a prediction. The network learns the filter values itself during training.

Why not use a regular neural network?

You can feed an image into an ordinary fully connected (dense) network by flattening it into one long row of pixels. It works for small images, but it has two problems:

  • Too many weights. A 224 × 224 color photo has 150,528 values. Connecting it to a single dense layer of 1,000 units needs over 150 million weights.
  • No sense of position. Flattening throws away which pixels are next to each other. A dense network has to learn “edge” separately for every location in the image.

A convolutional layer fixes both. Each filter is small (3 × 3 is typical) and the same filter is reused at every position, so the network learns a pattern once and recognizes it anywhere. Later in this guide, a CNN beats a dense network on the same data while using about a third as many weights.

How convolution works

Here’s a convolution with no libraries beyond NumPy. The image is 6 × 6, dark on the left and bright on the right. The filter is designed to respond to a vertical edge where dark changes to bright.

import numpy as np

# A 6x6 grayscale "image": dark on the left, bright on the right
image = np.array([
    [0, 0, 0, 9, 9, 9],
    [0, 0, 0, 9, 9, 9],
    [0, 0, 0, 9, 9, 9],
    [0, 0, 0, 9, 9, 9],
    [0, 0, 0, 9, 9, 9],
    [0, 0, 0, 9, 9, 9],
])

# A 3x3 filter that responds to dark-to-bright vertical edges
kernel = np.array([
    [-1, 0, 1],
    [-1, 0, 1],
    [-1, 0, 1],
])

def convolve(img, k):
    h, w = k.shape
    out = np.zeros((img.shape[0] - h + 1, img.shape[1] - w + 1))
    for i in range(out.shape[0]):
        for j in range(out.shape[1]):
            out[i, j] = (img[i:i + h, j:j + w] * k).sum()
    return out

feature_map = convolve(image, kernel)
print(feature_map)

Output:

[[ 0. 27. 27.  0.]
 [ 0. 27. 27.  0.]
 [ 0. 27. 27.  0.]
 [ 0. 27. 27.  0.]]

At each position, the filter is laid over a 3 × 3 patch of the image, the overlapping numbers are multiplied, and the products are added up. Where the patch is all one color, the left and right columns cancel out and the result is 0. Where the patch straddles the edge, the result is 27. The output, called a feature map, lights up exactly where the edge is.

A 6 by 6 image with a vertical edge, a 3 by 3 edge filter, and the resulting 4 by 4 feature map with high values in the middle two columns
The filter slides across the image. The feature map is high only where the edge is.

A CNN does exactly this, with two differences: it uses many filters at once (32 in the first layer below), and it learns the filter values from data instead of having them written by hand.

Output size, stride and padding

The feature map is smaller than the image because a 3 × 3 filter can only be placed in 4 positions across a 6-pixel row. The general formula is:

output size = (input size - filter size + 2 × padding) / stride + 1
  • Stride is how far the filter moves each step. A stride of 2 halves the output size.
  • Padding adds a border of zeros so the output keeps the input’s size. In Keras, padding="same" does this; the default, padding="valid", adds none.

How pooling works

A pooling layer shrinks a feature map by summarizing small blocks of it. Max pooling, the most common kind, keeps the largest value in each 2 × 2 block:

def max_pool(fmap, size=2):
    h, w = fmap.shape[0] // size, fmap.shape[1] // size
    return fmap[:h * size, :w * size].reshape(h, size, w, size).max(axis=(1, 3))

print(max_pool(feature_map))

Output:

[[27. 27.]
 [27. 27.]]

The 4 × 4 map becomes 2 × 2, a quarter of the size, and the edge signal survives. Pooling makes the network faster and a little less sensitive to exactly where a feature appears. It has no weights to learn.

Build a CNN in Python with Keras

Now a real one. Fashion-MNIST contains 70,000 grayscale 28 × 28 images of clothing in 10 classes, such as sneakers, shirts and bags. It’s harder than the classic handwritten-digit dataset and small enough to train on a laptop CPU in a few minutes.

pip install tensorflow matplotlib

Step 1: Load and prepare the data

import keras
from keras import layers

(x_train, y_train), (x_test, y_test) = keras.datasets.fashion_mnist.load_data()
class_names = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat",
               "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]

print(x_train.shape, x_test.shape)
print(x_train.min(), x_train.max())

# Scale pixels to 0-1 and add a channel dimension: (28, 28) -> (28, 28, 1)
x_train = (x_train / 255.0)[..., None].astype("float32")
x_test = (x_test / 255.0)[..., None].astype("float32")
print(x_train.shape)

Output:

(60000, 28, 28) (10000, 28, 28)
0 255
(60000, 28, 28, 1)

Keras downloads the dataset the first time (about 30 MB). Two preparation steps matter. Dividing by 255 scales pixels to between 0 and 1, which helps training. Adding a channel dimension tells the convolutional layers each image has one color channel; color images would have 3.

Step 2: A baseline without convolution

To see what convolution adds, first train an ordinary dense network on the same data:

keras.utils.set_random_seed(0)

dense = keras.Sequential([
    keras.Input(shape=(28, 28, 1)),
    layers.Flatten(),
    layers.Dense(128, activation="relu"),
    layers.Dense(10, activation="softmax"),
])
dense.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
dense.fit(x_train, y_train, epochs=10, batch_size=128, validation_split=0.1, verbose=0)

print("parameters:", dense.count_params())
print("test accuracy:", round(dense.evaluate(x_test, y_test, verbose=0)[1], 4))

Output:

parameters: 101770
test accuracy: 0.8787

87.9% accuracy with 101,770 weights. That’s the number to beat.

Step 3: Define the CNN

keras.utils.set_random_seed(0)

model = keras.Sequential([
    keras.Input(shape=(28, 28, 1)),
    layers.Conv2D(32, kernel_size=3, activation="relu"),
    layers.MaxPooling2D(pool_size=2),
    layers.Conv2D(64, kernel_size=3, activation="relu"),
    layers.MaxPooling2D(pool_size=2),
    layers.Flatten(),
    layers.Dropout(0.5),
    layers.Dense(10, activation="softmax"),
])
model.summary()

Output:

Model: "sequential_1"
Layer (type)                    Output Shape               Param #
conv2d (Conv2D)                 (None, 26, 26, 32)             320
max_pooling2d (MaxPooling2D)    (None, 13, 13, 32)               0
conv2d_1 (Conv2D)               (None, 11, 11, 64)          18,496
max_pooling2d_1 (MaxPooling2D)  (None, 5, 5, 64)                 0
flatten_1 (Flatten)             (None, 1600)                     0
dropout (Dropout)               (None, 1600)                     0
dense_2 (Dense)                 (None, 10)                  16,010
 Total params: 34,826 (136.04 KB)
 Trainable params: 34,826 (136.04 KB)
 Non-trainable params: 0 (0.00 B)

Keras draws this table with box lines; they’re left out here so it lines up in the browser. Read it from top to bottom and you can follow the image through the network:

  • The first Conv2D layer applies 32 filters of size 3 × 3, turning the 28 × 28 image into 32 feature maps of 26 × 26. Its 320 weights are 3 × 3 × 32 filter values plus 32 biases.
  • MaxPooling2D halves each map to 13 × 13.
  • The second Conv2D layer applies 64 filters, each looking across all 32 maps from the layer before (3 × 3 × 32 × 64 + 64 = 18,496 weights). Pooling then shrinks the maps to 5 × 5.
  • Flatten turns 5 × 5 × 64 into 1,600 numbers, Dropout randomly switches off half of them during training to reduce overfitting, and the final Dense layer gives a probability for each of the 10 classes.

The whole CNN has 34,826 weights, about a third of the dense network.

Step 4: Train it

model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])

history = model.fit(x_train, y_train, epochs=10, batch_size=128,
                    validation_split=0.1, verbose=2)

Output:

Epoch 1/10
422/422 - 13s - 31ms/step - accuracy: 0.7521 - loss: 0.6928 - val_accuracy: 0.8407 - val_loss: 0.4418
Epoch 2/10
422/422 - 12s - 29ms/step - accuracy: 0.8381 - loss: 0.4494 - val_accuracy: 0.8625 - val_loss: 0.3813
Epoch 3/10
422/422 - 12s - 28ms/step - accuracy: 0.8564 - loss: 0.4043 - val_accuracy: 0.8737 - val_loss: 0.3532
Epoch 4/10
422/422 - 12s - 28ms/step - accuracy: 0.8652 - loss: 0.3748 - val_accuracy: 0.8752 - val_loss: 0.3377
Epoch 5/10
422/422 - 12s - 29ms/step - accuracy: 0.8732 - loss: 0.3529 - val_accuracy: 0.8812 - val_loss: 0.3193
Epoch 6/10
422/422 - 12s - 29ms/step - accuracy: 0.8801 - loss: 0.3385 - val_accuracy: 0.8868 - val_loss: 0.3120
Epoch 7/10
422/422 - 12s - 28ms/step - accuracy: 0.8835 - loss: 0.3236 - val_accuracy: 0.8928 - val_loss: 0.2989
Epoch 8/10
422/422 - 12s - 29ms/step - accuracy: 0.8870 - loss: 0.3141 - val_accuracy: 0.8952 - val_loss: 0.2892
Epoch 9/10
422/422 - 21s - 50ms/step - accuracy: 0.8892 - loss: 0.3060 - val_accuracy: 0.8963 - val_loss: 0.2861
Epoch 10/10
422/422 - 13s - 30ms/step - accuracy: 0.8929 - loss: 0.2944 - val_accuracy: 0.9025 - val_loss: 0.2782

Each epoch is one pass over the 54,000 training images, with 10% held back for validation. Your times per epoch will depend on your machine; the numbers above are from a 2-core CPU. Training ends with 90.3% validation accuracy.

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(history.history["accuracy"], label="training")
ax.plot(history.history["val_accuracy"], label="validation")
ax.set_xlabel("Epoch")
ax.set_ylabel("Accuracy")
ax.legend()
plt.show()
Training and validation accuracy over 10 epochs, both rising from about 75 to 84 percent to about 89 to 90 percent
Accuracy by epoch. Validation accuracy sits above training accuracy because dropout is only active during training.

Validation accuracy is higher than training accuracy throughout. That’s not a bug: dropout switches off half the features while training but not while validating, so the model is handicapped during training. Both curves are still rising, which tells you the model hasn’t finished learning.

Step 5: Evaluate on the test set

test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
print("test accuracy:", round(test_acc, 4))

Output:

test accuracy: 0.8942

89.4% on 10,000 images the model has never seen, against 87.9% for the dense network, with a third of the weights.

Step 6: Train longer, and stop at the right time

The curves were still climbing, so keep training. Instead of guessing how many epochs to run, use early stopping: it watches the validation loss and stops when it hasn’t improved for 3 epochs in a row, then restores the best weights.

early = keras.callbacks.EarlyStopping(monitor="val_loss", patience=3, restore_best_weights=True)
more = model.fit(x_train, y_train, epochs=30, batch_size=128, validation_split=0.1,
                 callbacks=[early], verbose=0)

print("extra epochs run:", len(more.history["loss"]))
print("best val_accuracy:", round(max(more.history["val_accuracy"]), 4))
print("test accuracy:", round(model.evaluate(x_test, y_test, verbose=0)[1], 4))

Output:

extra epochs run: 27
best val_accuracy: 0.9172
test accuracy: 0.9121

Early stopping ran 27 more epochs, then restored the weights from the best one. Test accuracy rises to 91.2%. Early stopping is the simplest protection against overfitting, and it saves you from picking an epoch count by trial and error.

ModelWeightsTest accuracy
Dense network, 10 epochs101,77087.9%
CNN, 10 epochs34,82689.4%
CNN, trained longer with early stopping34,82691.2%
Fashion-MNIST test set, 10,000 images.

Where the model goes wrong

Overall accuracy hides which classes are hard. Check accuracy for each class:

pred = model.predict(x_test, verbose=0).argmax(axis=1)

per_class = [(class_names[c], (pred[y_test == c] == c).mean()) for c in range(10)]
for name, acc in sorted(per_class, key=lambda t: t[1]):
    print(f"{name:12} {acc:.3f}")

Output:

Shirt        0.744
T-shirt/top  0.839
Pullover     0.861
Coat         0.871
Dress        0.935
Ankle boot   0.960
Sandal       0.970
Trouser      0.977
Bag          0.979
Sneaker      0.985

Shoes, bags and trousers are nearly perfect. Shirts are the weak spot at 74%. The most common mistakes show why:

from collections import Counter

mistakes = Counter((class_names[t], class_names[p]) for t, p in zip(y_test, pred) if t != p)
for (true, guess), n in mistakes.most_common(5):
    print(f"{true:12} -> {guess:12} {n}")

Output:

T-shirt/top  -> Shirt        101
Shirt        -> T-shirt/top  97
Pullover     -> Shirt        71
Shirt        -> Coat         67
Coat         -> Shirt        63

Shirts, T-shirts, pullovers and coats are all upper-body garments with similar outlines, and at 28 × 28 pixels the details that separate them, such as buttons, collars and sleeve length, are only a few pixels wide. This is useful to know before you try to improve the model: a deeper network or higher-resolution images would help here, while more epochs mostly won’t.

Make predictions

probs = model.predict(x_test[:3], verbose=0)
for i, p in enumerate(probs):
    print(class_names[y_test[i]], "->", class_names[p.argmax()], f"({p.max():.1%})")

Output:

Ankle boot -> Ankle boot (99.8%)
Pullover -> Pullover (100.0%)
Trouser -> Trouser (100.0%)

predict returns 10 probabilities per image; argmax picks the most likely class. New images need the same preparation as the training data: grayscale, 28 × 28, scaled to 0-1 and with a channel dimension.

Look inside: what the filters detect

You can see what the first convolutional layer responds to by building a small model that stops after it:

first_conv = keras.Model(model.inputs, model.layers[0].output)
maps = first_conv.predict(x_test[:1], verbose=0)
print(maps.shape)

Output:

(1, 26, 26, 32)
fig, axes = plt.subplots(2, 8, figsize=(10, 3))
axes[0, 0].imshow(x_test[0, :, :, 0], cmap="gray_r")
axes[0, 0].set_title("input", fontsize=8)
for k, ax in enumerate(axes.flat[1:]):
    ax.imshow(maps[0, :, :, k], cmap="viridis")
for ax in axes.flat:
    ax.axis("off")
plt.show()
An ankle boot image and 15 of the 32 feature maps from the first convolutional layer, each highlighting different edges and areas of the boot
An ankle boot and 15 of the 32 feature maps from the first layer. Some filters respond to the top edge, some to the sole, some to the whole shape.

Nobody told the network to look for top edges or soles. It learned those filters because they help separate the classes. Deeper layers combine these simple maps into more specific features.

Save and reload the model

model.save("fashion_cnn.keras")
reloaded = keras.models.load_model("fashion_cnn.keras")
print(round(reloaded.evaluate(x_test, y_test, verbose=0)[1], 4))

Output:

0.9121

The .keras file contains the architecture, the learned weights and the optimizer state. To serve predictions from a web app, see our guide to deploying a machine learning model with Flask.

How to improve a CNN

  • Data augmentation. Randomly flip, shift or zoom training images so the model sees more variety. In Keras, add layers such as layers.RandomFlip("horizontal") and layers.RandomTranslation(0.1, 0.1) at the start of the model.
  • More filters or another convolutional block. Add a third Conv2D layer with 128 filters, or use padding="same" to keep more spatial detail.
  • Batch normalization. layers.BatchNormalization() after each convolution usually speeds up training and makes it more stable.
  • Transfer learning. For real photos, start from a network already trained on millions of images, such as ResNet or EfficientNet in keras.applications, and retrain only the last layers. It needs far less data than training from scratch.

Common mistakes

  1. Forgetting the channel dimension. Conv2D expects (height, width, channels). Grayscale images need a channel of size 1 added, as in Step 1.
  2. Not scaling pixel values. Raw values from 0 to 255 make training slow and unstable. Divide by 255.
  3. Preparing new images differently from training images. Different size, color mode or scaling at prediction time is the most common cause of a model that tests well and fails in use.
  4. Reading only overall accuracy. 91% overall hid a class at 74%. Always check per-class results.
  5. Training from scratch on a small photo dataset. With a few thousand real-world images, transfer learning will almost always beat a CNN trained from zero.

CNN architectures you’ll hear about

ArchitectureYearWhy it matters
LeNet-51998Early CNN for reading handwritten digits; the same conv-pool-dense pattern used above
AlexNet2012Won the ImageNet competition by a wide margin and started the deep learning boom
VGG2014Showed that stacking many small 3 × 3 filters works well
ResNet2015Skip connections made networks with 100+ layers trainable
EfficientNet2019Scales depth, width and resolution together for better accuracy per computation

Keep learning

The Keras documentation for Conv2D lists every option of the convolution layer used above.

FAQ

What is a convolutional neural network in simple terms?

It’s a neural network that looks at an image through small sliding windows. It learns which small patterns, such as edges and textures, matter, and combines them into larger features to recognize what’s in the image.

What’s the difference between a CNN and a regular neural network?

A regular dense network connects every input pixel to every unit, so it needs many weights and ignores which pixels are neighbors. A CNN reuses small filters across the whole image, which uses far fewer weights and keeps spatial structure. On Fashion-MNIST, our CNN was more accurate with a third of the weights.

What does the convolution layer do?

It slides each filter across the image, multiplies the filter by each patch it covers and adds the results, producing a feature map that is high wherever the patch matches the filter’s pattern.

What is pooling in a CNN?

Pooling shrinks feature maps by summarizing small blocks, usually keeping the maximum value in each 2 × 2 block. It reduces computation and makes the network less sensitive to the exact position of a feature.

Are CNNs only used for images?

Mostly, but not only. One-dimensional CNNs are used for audio, sensor signals and time series, and CNNs have been used for text classification. For long sequences and language, transformers are now more common.

Should I use TensorFlow/Keras or PyTorch for CNNs?

Both are excellent. Keras is quicker to start with, as this guide shows; PyTorch is more popular in research. The concepts, layers and results carry over directly.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights