top of page
Gradient With Circle
Image by Nick Morrison

Insights Across Technology, Software, and AI

Discover articles across technology, software, and AI. From core concepts to modern tech and practical implementations.

A Beginner's Guide to Keras in Python for Deep Learning

  • Aug 10, 2024
  • 7 min read

Updated: May 19

Deep learning has become a pivotal technology in the field of artificial intelligence (AI), powering innovations in everything from natural language processing to computer vision. One of the most popular tools for building deep learning models in Python is Keras, an open-source library that provides a high-level interface for working with neural networks. In this blog, we'll explore what Keras is, why it’s widely used, and how to get started with building your own deep learning model using Keras.

Keras in Python for Deep Learning - colabcodes

What is Keras in Python?

Keras is an open-source deep learning library written in Python, designed to provide a high-level interface for building and training neural networks. Developed by François Chollet, Keras is known for its simplicity and user-friendly nature, making it accessible to both beginners and experts in the field of machine learning. It allows developers to quickly prototype models using simple and intuitive APIs. Keras can run on top of various deep learning backends like TensorFlow, Theano, and Microsoft Cognitive Toolkit (CNTK), and is particularly popular for its ability to seamlessly integrate with TensorFlow, which is now its default backend. Few of the key features of keras include:


  1. User-Friendly: Keras is designed to be simple and intuitive, making it easy to build deep learning models with just a few lines of code.

  2. Modular and Extensible: Keras allows you to create complex models by combining smaller, reusable components like layers, optimizers, and loss functions.

  3. Runs on Multiple Backends: While it’s most commonly used with TensorFlow, Keras can also run on other backends like Theano and Microsoft Cognitive Toolkit (CNTK).

  4. Integration with TensorFlow: Since Keras is now part of TensorFlow, it benefits from TensorFlow’s extensive ecosystem, including tools for model training, deployment, and scaling.


Why Choose Keras?

Keras is widely favored for its ease of use, flexibility, and ability to accelerate deep learning development. Its user-friendly API allows developers to build and experiment with neural networks quickly without getting bogged down by complex code. Keras is highly modular, enabling users to design sophisticated models by combining and customizing layers, optimizers, and loss functions. Additionally, Keras seamlessly integrates with TensorFlow, leveraging its powerful computational capabilities and extensive ecosystem. This combination of simplicity, adaptability, and integration makes Keras an ideal choice for both beginners and experts in the deep learning community.


  1. Ease of Use: Keras abstracts many of the complexities involved in designing deep learning models. It provides simple APIs for building models, defining layers, and compiling them.

  2. Extensive Documentation and Community Support: The Keras documentation is thorough, with numerous examples and guides. Additionally, a large community of developers contributes to the library, which means you'll find plenty of tutorials and support.

  3. Flexibility: Keras allows you to build a wide range of deep learning models, from simple feedforward networks to complex models involving convolutional and recurrent layers.

  4. Integration with TensorFlow: Since Keras is part of the TensorFlow ecosystem, you can take advantage of TensorFlow’s powerful tools for model training, deployment, and scaling.


Getting Started with Keras Framwork in Python

Getting started with Keras in Python is straightforward, making it an excellent choice for both newcomers and seasoned developers in deep learning. First, install Keras alongside TensorFlow, as Keras now comes bundled with TensorFlow, providing a powerful backend. With a simple pip install tensorflow keras, you're ready to begin. Keras’ intuitive API allows you to quickly build and train neural networks. From importing libraries and preparing datasets to defining models and running training loops, Keras streamlines the entire process, enabling you to prototype and experiment with ease.


Installing Keras

Before you can start using Keras, you need to install it along with TensorFlow. You can do this using pip:

pip install tensorflow keras

This command installs both TensorFlow and Keras, since Keras now comes bundled with TensorFlow.


Building Your First Neural Network using keras in Python

Let's walk through building a simple neural network model to solve a classification problem. We'll use the popular MNIST dataset, which consists of 28x28 pixel images of handwritten digits.


Step 1: Import Libraries

The first step in building the model is importing the required libraries. The Sequential class is used to create a layered neural network architecture, while the Dense layer adds fully connected neurons to the network. The Flatten layer converts two-dimensional image data into a one-dimensional vector that can be processed by the neural network. Additional utilities such as the MNIST dataset loader and categorical encoding functions are also imported to prepare the data for training.

# Import libraries
import keras
from keras.models import Sequential
from keras.layers import Dense, Flatten
from keras.datasets import mnist
from keras.utils import to_categorical

Step 2: Load and Preprocess the Data

After importing the required libraries, the next step is to load and preprocess the dataset before training the neural network. The MNIST dataset is directly available through Keras and contains separate training and testing datasets. The training set is used to teach the neural network, while the testing set helps evaluate how well the model performs on unseen data.


Since neural networks work more efficiently with normalized numerical values, the pixel intensities are scaled from a range of 0–255 down to 0–1 by dividing them by 255. The images are also reshaped into a four-dimensional format so they can be processed correctly by deep learning models. Finally, the digit labels are converted into one-hot encoded vectors using to_categorical(), allowing the model to treat the classification task as a multi-class prediction problem.

# Load the dataset
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# Preprocess the data
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255

# Convert labels to categorical one-hot encoding
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

Output:
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11490434/11490434 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step

Step 3: Define the Neural Model

Once the dataset has been prepared, the next step is to define the architecture of the neural network. In this example, we use the Sequential API provided by Keras, which allows layers to be stacked one after another in a linear manner. This approach is commonly used for building beginner-friendly deep learning models because of its simplicity and readability.

The model starts with a Flatten layer that converts the 28×28 image matrix into a one-dimensional vector so it can be processed by fully connected neural network layers.


After that, a Dense hidden layer containing 128 neurons is added along with the ReLU activation function, enabling the model to learn complex patterns from the image data. Finally, the output layer contains 10 neurons corresponding to the 10 digit classes in the MNIST dataset, while the softmax activation function converts the outputs into probability scores for classification.


The architecture of the neural network can be summarized as follows:


  • A Flatten layer for reshaping image data

  • A Dense hidden layer with 128 neurons and ReLU activation

  • An output layer with 10 neurons and softmax activation


# Model Architecture
model = Sequential([
    Flatten(input_shape=(28, 28, 1)),
    Dense(128, activation='relu'),
    Dense(10, activation='softmax')])

Step 4: Compile the Model

After defining the architecture, the neural network must be compiled before training begins. During compilation, we specify the optimizer, loss function, and evaluation metrics that guide the learning process.


In this example, the adam optimizer is used because of its efficiency and adaptive learning capabilities, making it one of the most widely used optimizers in Deep Learning. The loss function selected is categorical_crossentropy, which is suitable for multi-class classification problems where the output belongs to one of several categories. Additionally, accuracy is used as the evaluation metric to measure how well the model predicts handwritten digits during training.

# Model compilation
model.compile(
    optimizer='adam',
    loss='categorical_crossentropy',
    metrics=['accuracy'])

The compilation step essentially prepares the neural network for learning by configuring how predictions are evaluated and how the model updates its internal weights during training.


Step 5: Train the Neural Network

After compiling the model, the next step is to train the neural network using the training dataset. Training is the process where the model learns patterns from the input images by continuously adjusting its internal weights to minimize prediction errors.

The fit() method is used to train the model for a specified number of epochs. An epoch represents one complete pass through the entire training dataset.

The batch_size parameter controls how many samples are processed before the model updates its weights. In this example, the neural network is trained for 5 epochs with batches of 32 images at a time.

# Model training
model.fit(
    train_images,
    train_labels,
    epochs=5,
    batch_size=32)

During training, the output displays the model’s accuracy and loss values for each epoch. As training progresses, the accuracy steadily improves while the loss decreases, indicating that the neural network is successfully learning to recognize handwritten digits from the MNIST dataset.

Epoch 1/5 1875/1875 ━━━━━━━━━━━━━━━━━━━━ 15s 7ms/step - accuracy: 0.8758 - loss: 0.4410 
Epoch 2/5 1875/1875 ━━━━━━━━━━━━━━━━━━━━ 16s 5ms/step - accuracy: 0.9640 - loss: 0.1200 
Epoch 3/5 1875/1875 ━━━━━━━━━━━━━━━━━━━━ 7s 4ms/step - accuracy: 0.9758 - loss: 0.0808 
Epoch 4/5 1875/1875 ━━━━━━━━━━━━━━━━━━━━ 9s 5ms/step - accuracy: 0.9822 - loss: 0.0591 
Epoch 5/5 1875/1875 ━━━━━━━━━━━━━━━━━━━━ 7s 4ms/step - accuracy: 0.9876 - loss: 0.0422

The output also demonstrates how quickly modern TensorFlow-based neural networks can learn relatively simple image classification tasks with high accuracy.


Step 6: Evaluate the Model

Once training is complete, the final step is to evaluate the neural network on unseen test data. This helps determine how well the model generalizes beyond the training dataset and measures its real-world predictive performance.

The evaluate() method calculates the loss and accuracy of the model using the test dataset. The resulting accuracy score indicates the percentage of correctly classified handwritten digits.

# Model Evaluation
test_loss, test_acc = model.evaluate(
    test_images,
    test_labels)

print(f'Test accuracy: {test_acc}')

Output: 
313/313 ━━━━━━━━━━━━━━━━━━━━ 1s 2ms/step - accuracy: 0.9748 - loss: 0.0885 Test accuracy: 0.9787999987602234

After evaluation, the output shows that the neural network achieves very high classification accuracy on the test dataset. This demonstrates that even a relatively simple neural network architecture can perform extremely well on image recognition tasks when trained properly.

The evaluation stage is important because it confirms that the model has not simply memorized the training data, but has learned patterns that can generalize effectively to new unseen inputs.


Conclusion

Keras is a powerful and user-friendly library for deep learning in Python, offering a blend of simplicity, flexibility, and integration with TensorFlow’s robust backend. Its intuitive API allows developers to rapidly build and experiment with neural network models, making it accessible to both beginners and experts. Whether you're tackling simple classification tasks or exploring complex neural architectures, Keras provides the tools needed to turn ideas into functional models efficiently. By combining ease of use with advanced capabilities, Keras has solidified its place as a go-to framework in the deep learning landscape. Embracing Keras means harnessing the power of deep learning with minimal effort, allowing you to focus on innovation and experimentation.

Get in touch for customized mentorship, research and freelance solutions tailored to your needs.

bottom of page