Building a Deep Learning Model with TensorFlow and Keras: Easier Than You Think

Guglielmo Cerri
Level Up Coding
Published in
3 min readJun 1, 2023

--

source

Deep Learning has become a vital technology in numerous industries with Python being the go-to language due to powerful libraries like TensorFlow and Keras. But, how to create a deep learning model from scratch using these tools? This step-by-step tutorial will guide you through it.

Setting Up Your Environment 🛠️

Before diving into deep learning, ensure you have a suitable Python environment. Anaconda is highly recommended. It’s also essential to install TensorFlow and Keras libraries. You can do this with the following command:

pip install tensorflow keras

TensorFlow is an open-source platform for machine learning, and Keras is a user-friendly neural network library written in Python.

Preparing the Dataset 📊

For this tutorial, we will use the MNIST dataset, a set of small images of digits handwritten. It’s a good starting point for practicing image classification tasks. Loading the MNIST dataset is straightforward with Keras:

from keras.datasets import mnist 

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

The MNIST dataset is divided into 60,000 training images and 10,000 testing images.

Preprocessing the Data 🧹

Data preprocessing is a crucial step. We need to reshape our data because deep learning models don’t accept raw data. In this case, our images need to be reshaped for the neural network:

train_images = train_images.reshape((60000, 28 * 28)) 
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255

Here, we’re reshaping the 60,000 images into vectors of 28x28 (=784) and normalizing them between 0 and 1.

Building the Model 🏗️

With TensorFlow and Keras, building a deep learning model is quite straightforward. Here we will use a simple feedforward neural network, which means the information moves in only one direction — forward — through the layers:

from keras import models 
from keras import layers

network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
network.add(layers.Dense(10, activation='softmax'))

Our model is composed of two Dense layers, which are fully connected neural layers. The second (and last) layer is a 10-way softmax layer, which means it will return an array of 10 probability scores.

Compiling the Model 🧠

We are almost there! Before training the model, we need to compile it. As part of this step, we’ll define the loss function, the optimizer, and the metrics to track during training:

network.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

We’re using rmsprop as our optimizer, sparse_categorical_crossentropy as our loss function, and we're tracking accuracy as our metric.

Training the Model 🎯

Now it’s time to train our model. We’ll do this with the fit method, which will start the learning process:

network.fit(train_images, train_labels, epochs=5, batch_size=128)

Here, the network will start to iterate on the training data in mini-batches of 128 samples, 5 times over (each iteration over all the training data is called an epoch).

Evaluating the Model 📈

We can assess the performance of our model using the test dataset:

test_loss, test_acc = network.evaluate(test_images, test_labels) 
print('Test accuracy:', test_acc)

The evaluate method checks the model's performance on the test dataset.

Conclusion 🎉

Congratulations! You’ve built your first deep learning model with Python, TensorFlow, and Keras! This field has lots of complexities, but with Python’s great libraries, you can simplify the process. Keep experimenting, keep learning, and stay curious! 🚀

If you found this article interesting, please follow me on Medium for more insightful content! 👋

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job

--

--