Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Sequential API in Keras

Introduction

The Keras Sequential API is a linear stack of layers. It allows you to build neural networks layer by layer in a straightforward manner. This tutorial will guide you through the basics of using the Sequential API, including the construction of models, compiling them, and fitting them on data.

Getting Started

To use Keras, you need to have TensorFlow installed, as Keras is now integrated within TensorFlow. You can install TensorFlow using pip:

pip install tensorflow

After installation, you can import the necessary modules to start building your model.

import tensorflow as tf
from tensorflow import keras

Building a Sequential Model

You can create a Sequential model by initializing an instance of the Sequential class. After that, you can add layers to the model using the add() method.

model = keras.Sequential() model.add(keras.layers.Dense(64, activation='relu', input_shape=(32,))) model.add(keras.layers.Dense(10, activation='softmax'))

In this example, we create a model with two layers: a Dense layer with 64 units and a Dense output layer with 10 units, suitable for a classification task.

Compiling the Model

Once the model is built, you need to compile it. Compiling the model involves configuring the learning process. You can specify the optimizer, loss function, and metrics to evaluate the model.

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

Here, we use the Adam optimizer and sparse categorical crossentropy as the loss function, which is suitable for multi-class classification problems.

Fitting the Model

After compiling the model, you can fit it to your training data using the fit() method. You will need to provide the training data, labels, batch size, and number of epochs.

model.fit(train_data, train_labels, epochs=5, batch_size=32)

In this example, we fit the model to the training data for 5 epochs, with a batch size of 32.

Evaluating the Model

After training the model, you can evaluate its performance on the test data using the evaluate() method.

test_loss, test_accuracy = model.evaluate(test_data, test_labels)

This will return the loss and accuracy of the model on the test dataset, helping you assess how well your model generalizes.

Conclusion

The Keras Sequential API is a powerful tool for building deep learning models with ease. It allows for straightforward model creation, compilation, and fitting. With this tutorial, you should now have a foundational understanding of how to use the Sequential API to build and train your neural networks.