TensorFlow program in Python – creates and trains a basic neural network for image classification

Below is a simple TensorFlow program in Python that creates and trains a basic neural network for image classification using the popular MNIST dataset.

Prerequisites:

  1. Install TensorFlow: pip install tensorflow
  2. Install Matplotlib: pip install matplotlib

TensorFlow Sample Program:

import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt

# Load and preprocess the MNIST dataset
mnist = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images, test_images = train_images / 255.0, test_images / 255.0

# Build a simple neural network model
model = models.Sequential([
    layers.Flatten(input_shape=(28, 28)),  # Flatten the 28x28 images to a 1D array
    layers.Dense(128, activation='relu'),
    layers.Dropout(0.2),
    layers.Dense(10)  # 10 output neurons for 10 classes (digits 0-9)
])

# Compile the model
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

# Train the model
history = model.fit(train_images, train_labels, epochs=5, validation_data=(test_images, test_labels))

# Evaluate the model on the test set
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print("\nTest accuracy:", test_acc)

# Plot the training history
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()

This program uses a simple neural network with one hidden layer to classify handwritten digits from the MNIST dataset. It loads the dataset, preprocesses the images, builds the model, compiles it, and then trains it. Finally, it evaluates the model on the test set and plots the training history.

Feel free to experiment with the architecture, hyperparameters, or even try different datasets based on your interest and requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *