Deep Learning with TensorFlow: A Practical Tutorial

Authored By: Ankita Prajapati

TensorFlow is an open-source software library for dataflow and differentiable programming across a range of tasks. It is used for machine learning applications such as neural networks.

TensorFlow was developed by the Google Brain team and was released under the Apache 2.0 open source license on November 9, 2015.

TensorFlow allows developers to create a graph of computations to be performed, and then executes that graph efficiently on any available hardware.

In this tutorial, we will discuss how to implement a deep learning model using TensorFlow. We will cover the following topics:

  1. Installation of TensorFlow
  2. Building a simple neural network using TensorFlow
  3. Creating a more complex neural network using TensorFlow
  4. Training and evaluating the model
  5. Saving and loading the model

Installation of TensorFlow:

Before we can start using TensorFlow, we need to install it. TensorFlow can be installed using pip, which is a package manager for Python.

To install TensorFlow, open a command prompt and type the following command:

				
					pip install tensorflow
				
			

This will download and install the latest version of TensorFlow.

Building a simple neural network using TensorFlow:

Once TensorFlow is installed, we can start building a simple neural network. In this example, we will create a neural network that can classify handwritten digits from the MNIST dataset.

The MNIST dataset consists of 60,000 training images and 10,000 test images of handwritten digits. Each image is a 28×28 grayscale image, and the labels are the digits 0-9.

To load the MNIST dataset, we can use the following code:

				
					import tensorflow as tf
from tensorflow import keras

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

This will load the training and testing data into the variables x_train, y_train, x_test, and y_test.

Next, we need to preprocess the data. In this case, we will normalize the pixel values to be between 0 and 1.

				
					x_train = x_train / 255.0
x_test = x_test / 255.0
				
			

Now, we can create the neural network. We will use a simple neural network with one hidden layer.

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

The first layer, Flatten, takes the 28×28 input images and flattens them into a 784-dimensional vector. The second layer, Dense(128, activation='relu'), is a hidden layer with 128 neurons and uses the ReLU activation function. The third and final layer, Dense(10, activation='softmax'), is the output layer with 10 neurons, one for each digit, and uses the softmax activation function.

Creating a more complex neural network using TensorFlow:

In some cases, a more complex neural network may be needed to solve a particular problem. In this example, we will create a neural network that can classify images from the CIFAR-10 dataset, which consists of 60,000 32×32 color images in 10 classes.

To load the CIFAR-10 dataset, we can use the following code:

				
					import tensorflow as tf
from tensorflow import keras

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

This will load the training and testing data into the variables x_train, y_train, x_test, and y_test.

Next, we need to preprocess the data. In this case, we will normalize the pixel values and perform data augmentation to increase the size of our dataset.

				
					x_train = x_train / 255.0
x_test = x_test / 255.0

data_augmentation = keras.Sequential([
    keras.layers.experimental.preprocessing.RandomFlip('horizontal'),
    keras.layers.experimental.preprocessing.RandomRotation(0.1),
    keras.layers.experimental.preprocessing.RandomZoom(0.1)
])

x_train = data_augmentation(x_train)

				
			

The RandomFlip, RandomRotation, and RandomZoom layers are used to randomly flip, rotate, and zoom the images in our dataset, respectively.

Now, we can create the neural network. We will use a more complex neural network with multiple convolutional and pooling layers.

				
					model = keras.Sequential([
    keras.layers.Conv2D(32, (3,3), padding='same', activation='relu', input_shape=(32,32,3)),
    keras.layers.MaxPooling2D((2,2)),
    keras.layers.Conv2D(64, (3,3), padding='same', activation='relu'),
    keras.layers.MaxPooling2D((2,2)),
    keras.layers.Conv2D(128, (3,3), padding='same', activation='relu'),
    keras.layers.MaxPooling2D((2,2)),
    keras.layers.Flatten(),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10)
])

				
			

The first three layers are convolutional layers, which apply a set of learnable filters to the input image to extract relevant features. The MaxPooling2D layers are used to reduce the spatial dimensions of the output from the convolutional layers. The Flatten layer is used to convert the output from the convolutional layers into a 1D vector, which can be passed to the fully connected layers. Finally, we have two fully connected layers, including the output layer.

Training and evaluating the model:

Once the neural network is defined, we can train and evaluate it using the fit method.

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

history = model.fit(x_train, y_train, epochs=10,
                    validation_data=(x_test, y_test))

				
			

We compile the model using the Adam optimizer, the sparse categorical crossentropy loss function, and accuracy as the evaluation metric. We train the model for 10 epochs and use the validation set to monitor the performance of the model during training.

After training the model, we can evaluate its performance on the test set using the evaluate method.

				
					test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print('Test accuracy:', test_acc)

				
			

Saving and loading the model:

Once we have trained and evaluated our model, we can save it to disk using the save method.

				
					model.save('my_model')

				
			

To load the model, we can use the load_model function from the tensorflow.keras.models module.

				
					from tensorflow.keras.models import load_model

model = load_model('my_model')

				
			

Conclusion

This tutorial covered the basics of deep learning with TensorFlow, how to build simple and complex neural networks, how to train and evaluate the model, and how to save and load the model. 

With these skills, you can start developing your own deep learning models using TensorFlow.

What is YourEngineer?

YourEngineer is the first Engineering Community Worldwide that focuses on spreading Awareness, providing Collaboration and building a focused Career Approach for Engineering Students.

Deep dive into upskilling with YourEngineer
Join millions like you

campus cover
  • Create an Account and Earn 1000 Coins
  • Pass a Quiz and Earn 20 Coins
  • Earn 10 Coins for Daily Visit 
  • Earn 50 Coins for invite someone to join a group
  • Earn 100 Coins for finishing a course