Press ESC to exit fullscreen
πŸ“– Lesson ⏱️ 150 minutes

Training Deep Networks in TensorFlow

Hands-on training of deep networks using TensorFlow

Introduction

In this tutorial, you will learn how to build and train your first deep neural network using TensorFlow and Keras to classify handwritten digits using the MNIST dataset.


1️⃣ Setting Up TensorFlow

If you haven’t installed TensorFlow yet, run:

pip install tensorflow

2️⃣ Import Libraries

import tensorflow as tf
from tensorflow.keras import layers, models

3️⃣ Load and Prepare the MNIST Dataset

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# Normalize pixel values to [0, 1]
x_train, x_test = x_train / 255.0, x_test / 255.0

4️⃣ Build Your Deep Neural Network

model = models.Sequential([
    layers.Flatten(input_shape=(28, 28)),
    layers.Dense(128, activation='relu'),
    layers.Dropout(0.2),
    layers.Dense(10, activation='softmax')
])

5️⃣ Compile the Model

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

6️⃣ Train the Model

model.fit(x_train, y_train, epochs=5, validation_split=0.1)

You will see the loss and accuracy printed for each epoch, allowing you to monitor progress.


7️⃣ Evaluate the Model

test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f"Test accuracy: {test_acc:.4f}")

Conclusion

βœ… You have successfully built and trained your first deep neural network in TensorFlow.
βœ… You learned how to preprocess data, build the model, train, and evaluate it.
βœ… You now have the foundation to explore more complex architectures confidently.


What’s Next?

βœ… Try adding more layers or neurons to observe accuracy changes.
βœ… Experiment with different activation functions and optimizers.
βœ… Continue learning with Convolutional Neural Networks (CNNs) to enhance image classification.


Join the SuperML Community to share your progress and get help while learning.


Happy Learning with TensorFlow! πŸš€