Keras is one of the most popular libraries for building deep learning models due to its simplicity and flexibility. The Sequential class in Keras is particularly user-friendly for beginners and allows for quick prototyping of machine learning models by stacking layers sequentially. This article provides a deep dive into the Sequential class, explaining its features, usage, and common practices.
Introduction to Keras and the Sequential Class
The Keras Sequential class is a fundamental component of the Keras library, which is widely used for building and training deep learning models. This class provides a simple and intuitive way to create neural networks by stacking layers in a linear fashion. It is particularly well-suited for beginners and for constructing straightforward feedforward networks.
One of the key components of Keras is the Sequential class, which allows developers to build models layer-by-layer in a linear stack. This class is ideal for creating feedforward neural networks and convolutional networks, where the flow of data is straightforward.
Key Features of the Sequential Class:
- Ease of Use: The Sequential class is designed to be beginner-friendly, allowing users to define and train models quickly without complex configurations.
- Single Input and Output: It supports models with a single input tensor and a single output tensor, making it ideal for tasks with one input source and one output prediction.
- Layer Stacking: Layers can be added one after another using the add() method, resulting in a simple and intuitive model architecture
The Sequential class is particularly suited for situations where your model follows a linear structure. For example, it's ideal for simple neural networks like fully connected layers, convolutional neural networks, and recurrent neural networks. Here are some benefits of using the Sequential model:
Understanding the Structure of Sequential Models
Sequential models work by stacking layers in a linear manner. Each layer takes the output from the previous layer as its input. A Sequential model can be thought of as a pipeline where the input data flows through several transformations (layers) to produce a final prediction.
To create a Sequential model in Keras, you can either pass a list of layer instances to the constructor or add layers incrementally using the add() method. Here is an example of creating a simple Sequential model:
The structure typically looks like this:
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(units=64, activation='relu', input_dim=100))
model.add(Dense(units=10, activation='softmax'))
In this example, the model consists of two layers:
- A Dense layer with 64 units and ReLU activation.
- A Dense layer with 10 units and Softmax activation for multi-class classification.
Creating a Simple Neural Network Using Sequential
Let’s create a basic neural network using the Sequential class. We'll use the MNIST dataset, which consists of handwritten digits.
Python
# Import necessary libraries
import keras
from keras.models import Sequential
from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D
from keras.datasets import mnist
from keras.utils import to_categorical
import tensorflow as tf
# Load the MNIST dataset
(train_X, train_y), (test_X, test_y) = mnist.load_data()
# Preprocess the data by resizing to (64, 64) and converting to RGB
train_X_resized = tf.image.resize(train_X.reshape(-1, 28, 28, 1), (64, 64))
train_X_rgb = tf.image.grayscale_to_rgb(train_X_resized)
test_X_resized = tf.image.resize(test_X.reshape(-1, 28, 28, 1), (64, 64))
test_X_rgb = tf.image.grayscale_to_rgb(test_X_resized)
# Normalize the pixel values
train_X_rgb = train_X_rgb / 255.0
test_X_rgb = test_X_rgb / 255.0
# Convert labels to categorical (one-hot encoding)
train_y = to_categorical(train_y, 10)
test_y = to_categorical(test_y, 10)
model = Sequential()
Output:
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11490434/11490434 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step
/usr/local/lib/python3.10/dist-packages/keras/src/layers/reshaping/flatten.py:37: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an `Input(shape)` object as the first layer in the model instead.
super().__init__(**kwargs)
1. Adding Layers to a Sequential Model
Adding layers in Sequential is as simple as calling the add() method. For example, to add a convolutional layer followed by a pooling layer, you would do:
Python
# Add layers to the model
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(64, 64, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(10, activation='softmax'))
In this example:
- Conv2D adds a convolutional layer with 32 filters of size 3x3.
- MaxPooling2D adds a max pooling layer to reduce spatial dimensions.
2. Compiling a Sequential Model
After defining the model's architecture, the next step is to compile the model. Compiling configures the model for training by specifying the optimizer, loss function, and metrics to monitor during training.
Python
# Compile the model
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
- Optimizer: The algorithm used to update the model’s weights. Common optimizers include adam, sgd, and rmsprop.
- Loss Function: Measures how well the model’s predictions match the true labels. For classification problems, categorical_crossentropy is commonly used.
- Metrics: Additional metrics like accuracy can be monitored during training.
3. Training a Sequential Model
Once compiled, the model can be trained using the fit() method. This method accepts the training data and trains the model for a specified number of epochs.
Python
# Train the model
model.fit(train_X_rgb, train_y, epochs=10, batch_size=32, validation_split=0.2)
# Evaluate the model
test_loss, test_acc = model.evaluate(test_X_rgb, test_y)
print('Test accuracy:', test_acc)
# Make predictions
predictions = model.predict(test_X_rgb)
Output:
Epoch 1/10
1500/1500 ━━━━━━━━━━━━━━━━━━━━ 242s 160ms/step - accuracy: 0.9103 - loss: 0.2891 - val_accuracy: 0.9712 - val_loss: 0.0934
Epoch 2/10
1500/1500 ━━━━━━━━━━━━━━━━━━━━ 262s 160ms/step - accuracy: 0.9831 - loss: 0.0533 - val_accuracy: 0.9808 - val_loss: 0.0671
Epoch 3/10
1500/1500 ━━━━━━━━━━━━━━━━━━━━ 244s 148ms/step - accuracy: 0.9911 - loss: 0.0289 - val_accuracy: 0.9818 - val_loss: 0.0719
Epoch 4/10
1500/1500 ━━━━━━━━━━━━━━━━━━━━ 267s 151ms/step - accuracy: 0.9944 - loss: 0.0164 - val_accuracy: 0.9804 - val_loss: 0.0775
Epoch 5/10
1500/1500 ━━━━━━━━━━━━━━━━━━━━ 254s 146ms/step - accuracy: 0.9972 - loss: 0.0087 - val_accuracy: 0.9803 - val_loss: 0.0853
Epoch 6/10
1500/1500 ━━━━━━━━━━━━━━━━━━━━ 277s 156ms/step - accuracy: 0.9970 - loss: 0.0093 - val_accuracy: 0.9810 - val_loss: 0.0914
Epoch 7/10
1500/1500 ━━━━━━━━━━━━━━━━━━━━ 229s 153ms/step - accuracy: 0.9979 - loss: 0.0068 - val_accuracy: 0.9809 - val_loss: 0.1056
Epoch 8/10
1500/1500 ━━━━━━━━━━━━━━━━━━━━ 253s 147ms/step - accuracy: 0.9978 - loss: 0.0063 - val_accuracy: 0.9803 - val_loss: 0.1141
Epoch 9/10
1500/1500 ━━━━━━━━━━━━━━━━━━━━ 260s 145ms/step - accuracy: 0.9980 - loss: 0.0061 - val_accuracy: 0.9819 - val_loss: 0.1107
Epoch 10/10
1500/1500 ━━━━━━━━━━━━━━━━━━━━ 259s 143ms/step - accuracy: 0.9989 - loss: 0.0037 - val_accuracy: 0.9830 - val_loss: 0.1137
313/313 ━━━━━━━━━━━━━━━━━━━━ 14s 44ms/step - accuracy: 0.9780 - loss: 0.1101
Test accuracy: 0.9828000068664551
313/313 ━━━━━━━━━━━━━━━━━━━━ 10s 32ms/step
Limitations of the Sequential Class
While the Sequential class offers simplicity and ease of use, it comes with certain limitations:
- Lack of Flexibility: It does not support models with multiple inputs or outputs or architectures that require shared layers or complex branching.
- No Layer Sharing: You cannot easily share layers between different parts of the model using the Sequential API.
- Not Suitable for Complex Architectures: For models requiring skip connections or residual connections (e.g., ResNet), the functional API or Model subclassing should be used instead.
When to Use the Sequential Class
The Sequential class is best used when:
- You are working with simple feedforward networks.
- Your model has a single input and output.
- You prefer an easy-to-use interface for quick prototyping.
- You are new to deep learning and want to learn the basics without dealing with complex configurations.
Conclusion
The Sequential class in Keras offers an intuitive way to build simple neural networks. With its easy-to-use interface, developers can prototype models quickly. However, for more complex architectures, alternative approaches like the Functional API or Model subclassing may be more suitable. Nonetheless, Sequential remains a powerful tool for building standard neural networks efficiently.
Similar Reads
Sequential Estimation
Sequential estimation is a statistical method that updates parameter estimates step by step as new data arrives, rather than recalculating everything from scratch. This makes it ideal for real-time applications like financial forecasting, machine learning and sensor monitoring. Unlike batch estimati
4 min read
Sequential Covering Algorithm
Prerequisites: Learn-One-Rule Algorithm Sequential Covering is a popular algorithm based on Rule-Based Classification used for learning a disjunctive set of rules. The basic idea here is to learn one rule, remove the data that it covers, then repeat the same process. In this process, In this way, it
3 min read
Sequential Data Analysis in Python
Sequential data, often referred to as ordered data, consists of observations arranged in a specific order. This type of data is not necessarily time-based; it can represent sequences such as text, DNA strands, or user actions. In this article, we are going to explore, sequential data analysis, it's
8 min read
Sequential Decision Problems in AI
Sequential decision problems are at the heart of artificial intelligence (AI) and have become a critical area of study due to their vast applications in various domains, such as robotics, finance, healthcare, and autonomous systems. These problems involve making a sequence of decisions over time, wh
10 min read
Kotlin Sealed Classes
Kotlin provides an important new type of class that is not present in Java. These are known as sealed classes. As the word sealed suggests, sealed classes conform to restricted or bounded class hierarchies. A sealed class defines a set of subclasses within it. It is used when it is known in advance
3 min read
Sequential File Organization in DBMS
Database Management System (DBMS) is a software system that manages the creation, storage, retrieval, and manipulation of data in a structured and organized way. It allows users to perform CRUD operations (Create, Read, Update, Delete) and organize data efficiently. What is File Organization?File Or
6 min read
Sequential File Organization in Database
Sequential file organization is the simplest type of file organization, where files are stored one after the other, rather than storing different files in rows and columns (in a tabular form), storing data in rows. In this article, we will learn about sequential file organization and its advantages
5 min read
Types of Sequential Circuit
A sequential circuit is widely used for storing and processing information such as retaining and manipulating data which makes them an essential component in various electronic devices in the realm of digital electronics. Sequential circuits process data in a sequential manner which makes them essen
5 min read
Sequential File Organization and Access in DBMS
Sequential File Organization is a basic technique employed in a database management system DBMS for storing and retrieving data. It is mostly applied when data access is sequential or in a particular order. In this article, we will describe what sequential file organization is, define some fundament
6 min read
Episodic vs. Sequential Environment in AI
Episodic and sequential environment in AI is the zone where the AI software agent operates. These environments differ in how an agent's experiences are structured and the extent to which they influence subsequent actions and behaviour. Understanding the features of these environments provides a soli
5 min read