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…
- CoursePython Fundamentals
- Lesson85 of 22
- Video17 min
- FormatJupyter notebook · 24 code cells
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.")
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)
# 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()
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)
# What types are our variables?
print("Type of name:", type(name))
print("Type of favorite_number:", type(favorite_number))
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)
# Access the first and last item in the list.
print("First item:", items[0])
print("Last item:", items[-1])
# 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)
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)
# Useful functions: Find the length of a list.
print("How many items:", len(items))
# Looping through a list: print each fashion item.
for item in items:
print("Fashion item:", item)
# 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}")
# 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())
# 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)
# 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}")
# 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()
# 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])
# 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}")
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}")
# 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.")
# Extra tip: Save your trained model
model.save("fashion_model.h5")
print("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.



