How do you classified images uning MNIST dataset wth example

 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

  1. Load the Dataset
  2. Preprocess the Data
  3. Build the Model
  4. Compile the Model
  5. Train the Model
  6. Evaluate the Model
  7. 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]}')


This example demonstrates how to classify handwritten digits from the MNIST dataset using a simple neural network model in TensorFlow and Keras. The model is trained on the training data and evaluated on the test data to measure its accuracy. Finally, it makes predictions on new data.

Comments