CNNs with Python: A Practical Beginner’s Guide12 min read2,463 words

CNNs with Python: A Practical Beginner’s Guide

Learn how convolutional neural networks process images, then build and evaluate a working MNIST classifier with Python and TensorFlow, step by step.

convolutional neural networksCNN with PythonTensorFlow image classificationMNIST tutorialcomputer vision basics
CNNs with Python: A Practical Beginner’s Guide

Convolutional Neural Networks: Build Your First Image Classifier

A phone can sort photos by the people in them, and a computer vision system can distinguish a handwritten 7 from a 1. Neither task requires someone to write down a complete list of every useful edge, curve, or pixel pattern by hand. A convolutional neural network (CNN) learns visual features from examples and uses them to make predictions.

That said, getting to a working model isn't just "stack layers and hope." You still have to prepare images in the shape the network expects, pick a loss function, keep test data separate from training, and evaluate results with a bit of skepticism. Skip those details and you can end up with a model that looks good on paper but doesn't reliably behave on new images.

This guide covers the core operations in a CNN, then walks through a complete TensorFlow + Keras example using MNIST handwritten digits. You'll see how to train, evaluate, and inspect a prediction - and what this small demo can (and can't) tell you about real-world computer vision work.

What is a CNN and how does it process an image?

A convolutional neural network is built for grid-like data - especially images. An image is a grid of pixel values. A grayscale image has one value per pixel; a color image usually has red, green, and blue values. CNNs use local filters to find patterns across that grid, then combine what they find into increasingly useful representations.

A conventional fully connected network treats every input value as its own feature. For images, that creates an enormous number of connections and ignores a key fact: nearby pixels tend to be related. A convolutional layer instead applies the same small filter across different parts of an image. Because it reuses that filter, the network can detect a pattern no matter where it appears - top, bottom, or somewhere in the middle.

The main layers, in practical terms

A convolutional layer applies learnable filters - often called kernels - to an image (or feature map). Early filters frequently learn simple patterns like edges and oriented strokes. Deeper layers combine those patterns into more complex shapes. You don't set these visual features by hand; training adjusts the kernel values based on the model's errors.

Next comes an activation function. ReLU (Rectified Linear Unit) sets negative values to zero and leaves positive values alone. That's what gives the model nonlinearity - it can't just be a linear combination of pixels anymore.

Pooling reduces the spatial size of a feature map. With max pooling, for example, the layer keeps the largest value in each small region. This cuts down how much data later layers have to process and can make the representation less sensitive to small shifts. The trade-off is that pooling can throw away location detail, so it isn't automatically beneficial for every task.

Finally, a dense (fully connected) layer combines the extracted features to produce a decision. For a basic classifier, the output layer has one value per class. Softmax turns those outputs into a set of scores that sum to one, which are commonly interpreted as class probabilities.

How the pieces fit together

For an image classifier, the flow typically looks like this:

  1. Input: an image tensor with a known height, width, and number of channels.
  2. Convolution and activation: detect local visual patterns and introduce nonlinearity.
  3. Pooling: shrink feature-map dimensions while keeping the strongest responses.
  4. Classification layers: combine learned features and score each class.
  5. Output: pick the class with the highest score, while keeping the scores if you want more detail later.

A CNN doesn't "understand" an image the way a person does. It learns statistical associations between patterns in the training data and the labels you give it. If your labels are inconsistent, or if the images you deploy on differ from the ones you trained with, the model can learn the wrong associations. That's why data quality and evaluation matter as much as the layer diagram.

How do you build a CNN with Python and TensorFlow?

MNIST is a common first dataset because it contains 28×28 grayscale images of handwritten digits labeled from 0 to 9. It's small enough for a beginner experiment, and you don't have to deal with the overhead of collecting and labeling your own images. It's also a familiar benchmark, which makes it useful for learning - not a guarantee that it will translate directly to every other image problem.

Install TensorFlow in your Python environment, then run the example below. It loads MNIST, converts pixel values to floating-point numbers between 0 and 1, adds the channel dimension expected by a 2D convolution, and trains a compact model.

import numpy as np

import tensorflow as tf

from tensorflow.keras import layers, models

# Load the dataset: 60,000 training images and 10,000 test images.

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

# Convert pixels from integers in [0, 255] to float32 values in [0, 1].

X_train = X_train.astype('float32') / 255.0

X_test = X_test.astype('float32') / 255.0

# Add a final channel dimension: height, width, channels.

X_train = X_train[..., np.newaxis]

X_test = X_test[..., np.newaxis]

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')

])

model.compile(

optimizer='adam',

loss='sparse_categorical_crossentropy',

metrics=['accuracy']

)

model.fit(

X_train,

y_train,

epochs=5,

batch_size=32,

validation_split=0.1

)

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

print(f'Test accuracy: {accuracy:.3%}')

# Inspect the model output for the first test image.

probabilities = model.predict(X_test[:1], verbose=0)[0]

predicted_digit = int(np.argmax(probabilities))

print('Predicted digit:', predicted_digit)

print('Actual digit:', int(y_test[0]))

print('Class probabilities:', probabilities)

What the model configuration means

The input shape is (28, 28, 1): height, width, and one grayscale channel. Color images typically have three channels, but the exact shape depends on how your dataset is stored. A common beginner mistake is feeding the model an array that's missing the channel dimension - or has the channels in an unexpected order.

Conv2D uses 32 filters, each with a 3×3 receptive field. During training, the network learns the filter values. MaxPooling2D then reduces the spatial dimensions. Flatten converts the resulting feature maps into a one-dimensional vector so the dense layers can use them. Flattening is convenient here, but for larger models it can create a big dense layer, so people often choose other architectures.

The final dense layer has 10 units because there are 10 digit classes. Its softmax activation produces a score for each class. Since the labels are integers (like 3) rather than one-hot vectors, sparse_categorical_crossentropy matches this setup. If you encode labels as one-hot vectors, use categorical cross-entropy instead.

The optimizer updates the model's weights to reduce the loss. One epoch is one pass through the training data. The validation split holds out part of the training set for checks during training; the test set stays separate until the final evaluation. Five epochs is a reasonable starting point, but it doesn't guarantee a specific result. Training time and accuracy vary depending on your environment and settings.

How do you evaluate a CNN without fooling yourself?

The example prints test accuracy: the fraction of test images classified correctly. On MNIST, that's a useful first check, especially because the digits are fairly evenly represented. But accuracy alone doesn't tell the whole story. On an imbalanced dataset, a model can score well by mostly predicting the most common class while still failing on rarer ones.

Training, validation, and test data aren't interchangeable - they each have a job. Training data updates the weights. Validation data helps you compare choices (like architecture tweaks) and monitor training progress. Test data is meant to be a final check on the data you shouldn't use while making decisions. If you keep adjusting the model based on test results, the test set slowly becomes part of development, and its score stops being an independent estimate.

Check more than one number

For a real classification task, a confusion matrix helps you see what the model mixes up. You might get good overall accuracy but still routinely confuse two classes that matter differently to your users. Per-class precision and recall can also surface these issues.

It's also worth looking at individual predictions, including failures. The probability vector printed for one image shows how the model scored all 10 digits. A top score of 0.99 can still be wrong - softmax scores aren't automatically reliable measures of uncertainty. Review errors across classes and look for patterns: ambiguous handwriting, odd image quality, label issues, or preprocessing mismatches.

Watch for leakage and distribution changes

Data leakage happens when information that wouldn't be available at prediction time somehow influences training or evaluation. A simple example is using test images to decide preprocessing steps or tune the model. More subtle leakage can occur when near-duplicate images end up in both training and test sets.

You also need to think about how your "test" data matches real deployment. A random split from the same source is often too optimistic. If your eventual inputs come from a different camera, a different scanner, different lighting, or a different population of subjects, performance can drop. Keep a holdout set that actually reflects the conditions you care about, document how you collected it, and evaluate on it before trusting the model.

For MNIST, test accuracy is a compact sanity check that the model learned useful patterns. For a product, the question is broader: does the model reduce the specific user or operational problem you care about, at an acceptable error rate and cost? That means checking errors, coverage, inference constraints, and what happens when the model is uncertain.

When are CNNs useful, and what are their limits?

CNNs are a solid starting point when local visual patterns matter and your inputs are images or other spatial data. You'll see them used for classifying product photos, detecting objects in traffic scenes, analyzing plant leaves, and supporting medical-image workflows. The task affects the design: image classification assigns a label to an entire image, object detection must also locate objects, and segmentation assigns classes to pixels.

Because CNNs can learn features directly from examples, you don't always need hand-designed descriptors. But data preparation doesn't disappear. You still need representative images, consistent labels, and preprocessing that matches what your model will receive in the real world. In a business setting, the biggest effort is often building and maintaining the dataset, not defining the first layer.

Trade-offs to consider before choosing one

CNNs can require substantial labeled data and compute, especially for high-resolution inputs or more complex tasks. A small MNIST network works as a learning exercise, but a production system that detects defects on a manufacturing line has different requirements for image capture, failure handling, monitoring, and retraining.

CNNs can also be hard to interpret. You can inspect predictions and use visualization tools to see what regions influenced a decision, but that doesn't prove the model used a causal, "right for the right reason" signal. This matters even more in regulated or high-stakes settings. Treat explanation tools as debugging help, not as a replacement for validation and human oversight.

For a new project, ask three practical questions:

  • Is the task visual? If the useful signal is mostly text, tabular data, or time series, a different model family may fit better.
  • Can you obtain representative labeled examples? A more complex architecture can't fix labels that don't match what you'll see in practice.
  • What is the cost of each error? Choose evaluation metrics and review workflows around real consequences, not just a single headline score.

This tutorial uses a CNN because it's a straightforward way to see the mechanics end-to-end. For a larger image project, you may compare a CNN trained from scratch with a pretrained vision model, depending on data volume, latency requirements, licensing, and how you plan to deploy. There isn't one architecture that's best everywhere. Start with a measurable baseline, test it on data that matches your situation, and add complexity only when the results justify it.

Conclusion

A CNN turns image pixels into learned visual features, then uses those features to predict a class. With MNIST and TensorFlow, you can see a complete workflow: prepare input tensors, define convolution and dense layers, train with an appropriate loss, and evaluate on data held out from training.

This tutorial is a starting point, not proof that your model is ready for production. Keep the test set independent, look at class-level errors, and make sure your evaluation images resemble what you'll actually send to the model. The next useful step is simple: run the example, inspect what it gets wrong, and decide what evidence you'd need before trusting it on your own data.

Frequently Asked Questions

CNNs learn patterns in images and other spatial data. Common tasks include image classification, object detection and segmentation. Their suitability depends on the data, task and cost of errors.
No. This small model can run on a typical CPU, although training may take longer. GPUs become more useful as image resolution, dataset size or model complexity increases.
Scaling pixel values gives the optimizer smaller, more consistent inputs, which can make training more stable. Apply the same preprocessing during training, evaluation and real predictions.
MNIST labels are integers from 0 to 9, so sparse categorical cross-entropy matches that label format. For one-hot encoded labels, use categorical cross-entropy instead.
No. Compare suitable model options using representative data, considering performance, training data, inference speed, licensing and deployment constraints rather than choosing by model type alone.

Related articles