Skip to content

Instantly share code, notes, and snippets.

@jbxamora
Created March 30, 2023 21:44
Show Gist options
  • Save jbxamora/7356dc9a07d920c37ffc2b3b259b384b to your computer and use it in GitHub Desktop.
Save jbxamora/7356dc9a07d920c37ffc2b3b259b384b to your computer and use it in GitHub Desktop.
TensorFlow Img Classification

TensorFlow Image Classification

This is an example neural network implemented in Python using TensorFlow library. The purpose of this network is to classify images of hand-written digits from the MNIST dataset.

Architecture

The network has three hidden layers, each with 128 neurons and ReLU activation function. The output layer has 10 neurons, corresponding to the 10 classes (digits) in the dataset, and uses softmax activation function to output class probabilities.

Code

Here's the code for the neural network:

import tensorflow as tf
from tensorflow import keras

# Load the MNIST dataset
mnist = keras.datasets.mnist
(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

# Define the model architecture
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.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=10)

# Evaluate the model on the test set
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)

Result

The model achieved an accuracy of 97.9% on the test set after 10 epochs of training.

Conclusion

This is a simple example of a neural network for image classification using TensorFlow. With some modifications, this network can be applied to various other classification tasks.

Learn More

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment