Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Build a small image classifier that learns to identify handwritten digits from the MNIST dataset. This first project demonstrates the full Keras workflow—load and inspect data, define a model, configure and train it, then evaluate it on examples withheld from training. Its purpose is to make the process understandable, not to claim state-of-the-art results or suitability for consequential use.

What you will build

The model will take a 28-by-28 grayscale image and produce scores for ten possible classes, one for each digit from 0 through 9. You will use the predicted class with the highest score as the model’s answer. Keras’s introductory material uses MNIST for its first example, and its code catalog also includes a simple MNIST convolutional network (Keras code example).

The important distinction is between fitting and evaluation: training uses examples to adjust the model; evaluation measures it on a separate test set that was not used for fitting. A test result is useful evidence about this dataset, not proof that the model will handle every style of handwriting.

Set up Keras and choose a backend

Keras 3 is a Python deep learning API that can run with JAX, TensorFlow, or PyTorch as its backend. Install Keras and one backend framework in a fresh Python environment, following the current Keras installation guide. The standalone Keras command shown there is pip install --upgrade keras; a backend framework is also needed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If you choose a backend explicitly, set KERAS_BACKEND before importing Keras. For example, in a shell session using TensorFlow:

export KERAS_BACKEND=tensorflow

Then start Python or the notebook kernel and import Keras. Keras documents that backend choice cannot be changed after Keras has been imported. The equivalent environment-variable syntax differs across shells; a hosted notebook can avoid some local setup, but availability of accelerators and other resources depends on the service and runtime.

Version assumptions matter. TensorFlow 2.16 and later installs Keras 3 by default; TensorFlow 2.15 and earlier have a different Keras 2 relationship. The install guide separately documents the legacy tf_keras package. Do not combine package commands from an older Keras 2 tutorial with a current Keras 3 setup without checking which version that tutorial expects. For a project you plan to rerun, record or pin the versions you installed.

Load and inspect the example data

The following example follows the Keras MNIST workflow. Each image is represented as a 28-by-28 array of pixel values, and each label is an integer from 0 to 9. The Keras dataset loader provides separate training and test data:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import keras
import numpy as np

(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()

print("Training images:", x_train.shape)
print("Training labels:", y_train.shape)
print("Test images:", x_test.shape)
print("First label:", y_train[0])

Inspecting shapes and a label before building the model helps catch mismatches early. The images are two-dimensional arrays, while the labels are single integers, not ten-element one-hot vectors. This choice determines the model’s output and the loss function used later.

Prepare inputs and define a model

Scale pixel values to the range 0–1, then build a compact dense classifier. The first layer flattens each image into a vector of 784 pixel values; the hidden dense layer learns combinations of those values; the final layer produces ten class scores. softmax converts those scores into values that can be interpreted as class probabilities.

x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0

model = keras.Sequential([
    keras.layers.Input(shape=(28, 28)),
    keras.layers.Flatten(),
    keras.layers.Dense(128, activation="relu"),
    keras.layers.Dense(10, activation="softmax"),
])

Sequential fits a straightforward stack in which each layer passes its output to the next. Keras recommends a more flexible Functional or custom model for structures with branches, shared layers, or multiple inputs or outputs (Keras Sequential model guide). A convolutional model is another sensible image-classification extension: convolutional layers are designed to learn local image patterns, and Keras provides a Simple MNIST convnet example.

Configure and train the model

compile() configures the training process. Here, the labels are integer class IDs, so sparse_categorical_crossentropy matches the ten-class output without requiring one-hot encoded labels. The Adam optimizer adjusts the model’s weights during training, and accuracy is a metric for monitoring the fraction of predictions matching labels.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
model.compile(
    optimizer="adam",
    loss="sparse_categorical_crossentropy",
    metrics=["accuracy"],
)

history = model.fit(
    x_train,
    y_train,
    epochs=5,
    validation_split=0.1,
)

fit() trains the model in batches over epochs. An epoch is a pass through the training data; the value of five here is a starting choice for an experiment, not a guarantee of any particular score. The validation split holds out part of the supplied training data to monitor training behavior. It is not the final test set, which remains unused until evaluation.

Rank #4
Sale
Deep Learning with Python
  • Care instruction: Keep away from fire
  • It can be used as a gift
  • It is made up of premium quality material.

Evaluate held-out data and inspect predictions

Use evaluate() to measure performance on the test images and labels:

test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=0)
print("Test loss:", test_loss)
print("Test accuracy:", test_accuracy)

Then use predict() to get ten class scores for each input image. Taking the index of the largest score gives the predicted digit:

scores = model.predict(x_test[:5], verbose=0)
predicted_digits = np.argmax(scores, axis=1)

print("Predicted:", predicted_digits)
print("Actual:   ", y_test[:5])

Because the output layer has ten units, each row of scores corresponds to the ten digit classes. Comparing predictions with their actual labels is a quick sanity check; it does not replace evaluation across the held-out test set. Keras describes these separate training, evaluation, and prediction steps in its About Keras 3 overview and built-in training methods guide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Fix common first-project problems

  • Backend errors or an unexpected framework: Set KERAS_BACKEND before the first Keras import, then restart the Python process or notebook kernel after changing it.
  • Conflicting Keras versions: Check the current install guide’s TensorFlow version notes instead of mixing current Keras 3 commands with legacy Keras 2 instructions.
  • Input-shape mismatch: Confirm that images have shape (28, 28) before passing them to this model. If you change the data representation, update the model input and preprocessing to match.
  • Loss or label mismatch: This example uses integer labels with sparse_categorical_crossentropy. If you change labels to one-hot vectors, choose a loss appropriate to that encoding.

Once the workflow runs, useful extensions include plotting training and validation metrics, reviewing examples the model misclassified, and changing one architectural choice at a time. The Keras getting started guide covers setup, while the model training APIs reference explains training-related methods.

Optional deeper reading

Deep Learning with Python, Third Edition by François Chollet and Matthew Watson covers Keras 3 alongside TensorFlow, PyTorch, and JAX. The publisher listing describes it for readers with intermediate Python skills, so it is optional background rather than a prerequisite for this small project (Manning book listing; Google Books listing).

Quick Recap

SaleBestseller No. 1
SaleBestseller No. 2
SaleBestseller No. 4
Deep Learning with Python
Deep Learning with Python
Care instruction: Keep away from fire; It can be used as a gift; It is made up of premium quality material.
$40.74

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.