Mathew K Analytics

Lesson 85 · Python Fundamentals

Classifying Fashion MNIST Images with TensorFlow and Keras in Python

In this lesson, you will learn Python basics and build a simple image classifier using TensorFlow Keras. We will use Fashion MNIST, a dataset of clothing…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb
 

Welcome to Python: Fashion MNIST Classification!#

In this lesson, you will learn Python basics and build a simple image classifier using TensorFlow Keras.

We will use Fashion MNIST, a dataset of clothing item images and labels.

No prior coding experience is needed.

Let us get started!

# Let us start by importing basic Python libraries.
import warnings
warnings.filterwarnings('ignore')

print("Libraries imported! Ready to go.")
Libraries imported! Ready to go.

What is Fashion MNIST?#

Fashion MNIST is a collection of 70,000 images of clothes, shoes, and bags.

Each image is 28 by 28 pixels and is labeled with its type (like 'Sneaker' or 'Shirt').

# Data setup: Let us load the Fashion MNIST data.
from tensorflow.keras.datasets import fashion_mnist

(X_train, y_train), (X_test, y_test) = fashion_mnist.load_data()

print("Training set:", X_train.shape, y_train.shape)
print("Test set:", X_test.shape, y_test.shape)
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz
29515/29515 ━━━━━━━━━━━━━━━━━━━━ 0s 4us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz
26421880/26421880 ━━━━━━━━━━━━━━━━━━━━ 2s 0us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-labels-idx1-ubyte.gz
5148/5148 ━━━━━━━━━━━━━━━━━━━━ 0s 0s/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-images-idx3-ubyte.gz
4422102/4422102 ━━━━━━━━━━━━━━━━━━━━ 1s 0us/step
Training set: (60000, 28, 28) (60000,)
Test set: (10000, 28, 28) (10000,)
# Let us see the first image and its label.
import matplotlib.pyplot as plt

plt.imshow(X_train[0], cmap="gray")
plt.title(f"Label: {y_train[0]}")
plt.axis('off')
plt.show()
No description has been provided for this image

Python Basics: What is a variable?#

In Python, a variable stores information for you, like a box with a label.

You can use variables to save numbers, text, and even images.

# Create variables for a name and a favorite number.
name = "Zara"
favorite_number = 7

print("Name:", name)
print("Favorite number:", favorite_number)
Name: Zara
Favorite number: 7
# What types are our variables?
print("Type of name:", type(name))
print("Type of favorite_number:", type(favorite_number))
Type of name: <class 'str'>
Type of favorite_number: <class 'int'>

Lists: Storing many things in one place#

A list is a way to keep several pieces of information together in one variable.

You use square brackets [] and commas to make a list.

# Making a list of fashion items
items = ["Dress", "Sandal", "Shirt", "Sneaker"]
print(items)
['Dress', 'Sandal', 'Shirt', 'Sneaker']
# Access the first and last item in the list.
print("First item:", items[0])
print("Last item:", items[-1])
First item: Dress
Last item: Sneaker
# Safe access: What if we ask for a value that is not there?
try:
    print(items[10])
except IndexError as e:
    print("Oops! That was out of range.", e)
    
Oops! That was out of range. list index out of range

Modifying Lists: Adding and Removing Items#

You can change lists by adding new items or removing old ones.

This lets your programs adjust as you go.

# Add and remove items.
items.append("Boot")
items.remove("Dress")
print(items)
['Sandal', 'Shirt', 'Sneaker', 'Boot']
# Useful functions: Find the length of a list.
print("How many items:", len(items))
How many items: 4
# Looping through a list: print each fashion item.
for item in items:
    print("Fashion item:", item)
    
Fashion item: Sandal
Fashion item: Shirt
Fashion item: Sneaker
Fashion item: Boot
# Classification labels for Fashion MNIST
label_names = [
    "T-shirt/top", "Trouser", "Pullover", "Dress", "Coat",
    "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"
]
for i, label in enumerate(label_names):
    print(f"{i}: {label}")
    
0: T-shirt/top
1: Trouser
2: Pullover
3: Dress
4: Coat
5: Sandal
6: Shirt
7: Sneaker
8: Bag
9: Ankle boot
# Prepare data for machine learning: scale images to 0-1.
X_train_scaled = X_train / 255.0
X_test_scaled = X_test / 255.0
# Build a simple neural network with Keras.
from tensorflow.keras import models, layers

model = models.Sequential([
    layers.Flatten(input_shape=(28, 28)),
    layers.Dense(128, activation="relu"),
    layers.Dense(10, activation="softmax")
])

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

print(model.summary())
Model: "sequential"
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
┃ Layer (type)                    ┃ Output Shape           ┃       Param # ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
│ flatten (Flatten)               │ (None, 784)            │             0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ dense (Dense)                   │ (None, 128)            │       100,480 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ dense_1 (Dense)                 │ (None, 10)             │         1,290 │
└─────────────────────────────────┴────────────────────────┴───────────────┘
 Total params: 101,770 (397.54 KB)
 Trainable params: 101,770 (397.54 KB)
 Non-trainable params: 0 (0.00 B)
None
# Train the model on the training data.
history = model.fit(X_train_scaled, y_train,
                    epochs=5, batch_size=32,
                    validation_split=0.1, verbose=2)
Epoch 1/5
1688/1688 - 4s - 2ms/step - accuracy: 0.8211 - loss: 0.5053 - val_accuracy: 0.8578 - val_loss: 0.3942
Epoch 2/5
1688/1688 - 3s - 2ms/step - accuracy: 0.8649 - loss: 0.3747 - val_accuracy: 0.8653 - val_loss: 0.3713
Epoch 3/5
1688/1688 - 3s - 2ms/step - accuracy: 0.8770 - loss: 0.3374 - val_accuracy: 0.8698 - val_loss: 0.3516
Epoch 4/5
1688/1688 - 4s - 2ms/step - accuracy: 0.8839 - loss: 0.3136 - val_accuracy: 0.8717 - val_loss: 0.3465
Epoch 5/5
1688/1688 - 4s - 2ms/step - accuracy: 0.8915 - loss: 0.2973 - val_accuracy: 0.8747 - val_loss: 0.3361
# Evaluate the model on the test data.
test_loss, test_acc = model.evaluate(X_test_scaled, y_test, verbose=0)
print(f"Test accuracy: {test_acc:.2f}")
Test accuracy: 0.87
# Predict on a new test image and display the result.
import numpy as np
img_index = 0
img = X_test_scaled[img_index]
prediction = model.predict(np.expand_dims(img, axis=0))
predicted_label = np.argmax(prediction)

plt.imshow(X_test[img_index], cmap="gray")
plt.title(f"Prediction: {label_names[predicted_label]}")
plt.axis('off')
plt.show()
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 57ms/step
No description has been provided for this image
# Input your own index and predict the item!
index = int(input("Type a test image index from 0 to 9999: "))
img = X_test_scaled[index]
prediction = model.predict(np.expand_dims(img, axis=0), verbose=0)
predicted_label = np.argmax(prediction)
print("Model thinks this is:", label_names[predicted_label])
Model thinks this is: Pullover
 
# Challenge: Print five random predictions and compare to true labels.
import random
for _ in range(5):
    idx = random.randint(0, 9999)
    img = X_test_scaled[idx]
    true_label = label_names[y_test[idx]]
    prediction = model.predict(np.expand_dims(img, axis=0), verbose=0)
    predicted_label = label_names[np.argmax(prediction)]
    print(f"Image {idx}: True={true_label}, Predicted={predicted_label}")
    
Image 1812: True=Ankle boot, Predicted=Ankle boot
Image 3200: True=Sandal, Predicted=Sandal
Image 6591: True=Shirt, Predicted=Shirt
Image 4695: True=Dress, Predicted=Dress
Image 3617: True=Coat, Predicted=Coat

Mini-Project: Build Your Own Classifier#

Now it is your turn!

Try changing how many layers or neurons are in the model.

Can you make accuracy go higher or lower?

Experiment, then re-train the model and test again.

# Try doubling the hidden units and adding another layer.
model = models.Sequential([
    layers.Flatten(input_shape=(28, 28)),
    layers.Dense(256, activation="relu"),
    layers.Dense(64, activation="relu"),
    layers.Dense(10, activation="softmax")
])
model.compile(optimizer="adam",
              loss="sparse_categorical_crossentropy",
              metrics=["accuracy"])
model.fit(X_train_scaled, y_train, epochs=5, batch_size=32, validation_split=0.1, verbose=2)
test_loss, test_acc = model.evaluate(X_test_scaled, y_test, verbose=0)
print(f"New test accuracy: {test_acc:.2f}")
Epoch 1/5
1688/1688 - 5s - 3ms/step - accuracy: 0.8246 - loss: 0.4931 - val_accuracy: 0.8417 - val_loss: 0.4429
Epoch 2/5
1688/1688 - 5s - 3ms/step - accuracy: 0.8649 - loss: 0.3698 - val_accuracy: 0.8662 - val_loss: 0.3629
Epoch 3/5
1688/1688 - 4s - 3ms/step - accuracy: 0.8782 - loss: 0.3317 - val_accuracy: 0.8730 - val_loss: 0.3440
Epoch 4/5
1688/1688 - 5s - 3ms/step - accuracy: 0.8856 - loss: 0.3070 - val_accuracy: 0.8690 - val_loss: 0.3663
Epoch 5/5
1688/1688 - 6s - 3ms/step - accuracy: 0.8914 - loss: 0.2902 - val_accuracy: 0.8818 - val_loss: 0.3223
New test accuracy: 0.87
# Troubleshooting: What if my model accuracy is low?
if test_acc < 0.7:
    print("Do not worry! Try training for more epochs, adding more units, or lowering batch size.")
else:
    print("Great work! Your model is learning well.")
    
Great work! Your model is learning well.
# Extra tip: Save your trained model
model.save("fashion_model.h5")
print("Model saved! You can load and reuse it later.")
WARNING:absl:You are saving your model as an HDF5 file via `model.save()` or `keras.saving.save_model(model)`. This file format is considered legacy. We recommend using instead the native Keras format, e.g. `model.save('my_model.keras')` or `keras.saving.save_model(model, 'my_model.keras')`. 
Model saved! You can load and reuse it later.

Recap: What did you learn?#

You explored Python basics, variables, lists, loops, and built a neural network with real image data.

You learned how to train, test, and predict with a TensorFlow Keras model.

Experimenting and practicing is the best way to get better!

Try it Yourself and Subscribe!#

Practice with your own models and images. Try tweaking layers and settings.

If you enjoyed this, like and subscribe for more beginner Python lessons!

Ask questions in the comments below, and happy coding!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.