Classifying images using the MNIST dataset involves building a machine learning model, typically a neural network, to recognize handwritten digits (0-9). The MNIST dataset contains 60,000 training images and 10,000 test images, each 28x28 pixels in grayscale. Here's a step-by-step guide to classify images using the MNIST dataset with an example:
Step-by-Step Guide
- Load the Dataset
- Preprocess the Data
- Build the Model
- Compile the Model
- Train the Model
- Evaluate the Model
- Make Predictions
Full example code ---
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Flatten, Dense
import numpy as np
# Load the MNIST dataset
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# Normalize the images
train_images = train_images / 255.0
test_images = test_images / 255.0
# Build the model
model = Sequential([
Flatten(input_shape=(28, 28)),
Dense(128, activation='relu'),
Dense(10, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Train the model
model.fit(train_images, train_labels, epochs=5)
# Evaluate the model
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f'Test accuracy: {test_acc}')
# Make predictions
predictions = model.predict(test_images)
# Example: Predict the first test image
predicted_label = np.argmax(predictions[0])
print(f'Predicted label: {predicted_label}')
print(f'True label: {test_labels[0]}')
Comments
Post a Comment