Open In App

Unveiling the Power of Fastai: A Deep Dive into the Versatile Deep Learning Library

Last Updated : 26 Dec, 2023
Like Article

Fastai is a powerful deep-learning library designed for researchers and practitioners. It offers high-level abstractions, PyTorch integration, and application-specific APIs, making it both adaptable and accessible for a wide range of deep learning tasks. In this article, we’ll delve into the intricacies of Fastai, a powerful deep-learning library. The article outlines the core features of Fastai, emphasizing its adaptability, ease of use, and efficient handling of common deep-learning tasks.

What is FastAI?

Fastai is a deep learning library that gives researchers low-level components that may be combined to create novel methods and practitioners high-level components that can rapidly and easily provide state-of-the-art outcomes in common deep learning domains. It seeks to accomplish both goals without significantly sacrificing performance, flexibility, or ease of use. This is made feasible by a meticulously built architecture that uses decoupled abstractions to express common underlying patterns shared by numerous deep learning and data processing approaches. By utilizing the flexibility of the PyTorch package and the dynamism of the underlying Python language, these abstractions may be represented succinctly and unambiguously.

Fastai is structured around two primary design objectives: being highly hackable and adaptable and being approachable and productive quickly. It is constructed using modular building components that are provided by a hierarchy of lower-level APIs. In this manner, learning how to utilize the lowest level is not necessary for a user who wants to add specific behavior or rewrite a portion of the high-level API to fit their needs.


Fastai provides three levels of API—high-level, mid-level, and low-level—each catering to different levels of abstraction and customization.

Abstraction refers to the concept of simplifying complex systems by focusing on essential properties while ignoring unnecessary details.

FastAI High level API

The high-level API provides the highest abstraction, emphasizing simplicity and automation for common tasks, making it ideal for beginners or practitioners who seek a quick and easy solution without delving into detailed configurations.

  • Learner: A Learner in Fastai is an object that encapsulates the training process of a machine learning model. It combines the data (provided by a DataLoaders object), the model architecture, and the training configuration. It simplifies the training workflow, allowing to focus on model development and experimentation.
  • DataBlock: The DataBlock class in Fastai is part of the data preprocessing pipeline. It is used to define how to get data into a format that can be fed into a model. It involves specifying the types of data blocks, how to obtain items and labels, data splitting, and transformations.

The DataBlock and Learner work together in the machine learning pipeline. The DataBlock prepares and structures the input data for training, and the Learner takes care of the training and inference processes using the prepared data. The Learner relies on the DataLoaders created by the DataBlock to access and process the training, validation, and potentially test datasets.

By categorizing Learner as part of Model Training and Management and DataBlock as part of Data Preprocessing and Loading, it becomes clearer how these components contribute to different stages of the machine learning workflow in Fastai’s high-level API.

FastAI Mid Level API

The mid-level API strikes a balance between abstraction and customization, offering flexibility to customize various components of the training process, such as data processing, model architecture, and training loop. It caters to users who want more control over specific aspects of their models while still benefiting from higher-level abstractions.

  • Callbacks: Callbacks in Fastai are objects or functions that allow you to customize and extend the training loop. They provide hooks at various stages of training, allowing you to execute additional actions or modify the behavior of the training process. Callbacks can be used for tasks such as saving model checkpoints, adjusting learning rates, logging metrics, and more.
  • General optimizer :The general optimizer in Fastai refers to the choice of optimization algorithm used during the training of a machine learning model. Fastai provides a variety of optimizers, including SGD (Stochastic Gradient Descent), Adam, and others. The optimizer is responsible for updating the model parameters during each iteration of the training loop.
  • Data core: The data core in Fastai refers to the core components and abstractions for handling data. It includes the DataBlock, DataLoaders, and other functionalities that streamline the process of loading, transforming, and managing datasets for training and validation.

FastAI low-level API

The low-level API provides the lowest abstraction, granting full control over the training process. It is suitable for advanced users, researchers, or those experimenting with novel architectures and algorithms, allowing for fine-grained customization at every stage, from data loading to model training.

Several features contribute to the flexibility and control over the training process:

  • Pipeline: It refers to a series of operations or transformations applied sequentially to a piece of data. Pipelines are constructed using the Pipeline class and are used for data processing and augmentation during training enablimg the chaining of various data transformations, making it easy to create a sequence of operations to be applied to the data.
  • Reversible transforms: They are the operations that can be undone, allowing for transformations to be applied and then reversed. The Transform class in Fastai provides a decodes method, which defines how to reverse a transformation. Reversible transforms are crucial when interpreting or visualizing the transformed data.
  • OO Tensors: Fastai’s low-level API introduces an object-oriented approach to working with tensors, referred to as OO tensors. In this paradigm, tensors are treated as objects with associated behaviors and methods, making it more intuitive to perform operations on them. OO tensors enhance code readability and maintainability by encapsulating tensor operations within objects. This approach aligns with the principles of object-oriented programming and can make code more modular and extensible.
  • Optimized Ops: It refers to the use of optimized low-level operations on tensors for efficiency. Fastai leverages PyTorch’s tensor operations, which are optimized for performance, to ensure that computations are carried out efficiently.

The choice of API level depends on the specific needs, experience level, and the degree of control and customization required for machine learning tasks.

Why FastAI?

Choosing Fastai for deep learning tasks offers several compelling advantages, because it includes:

1. API at High Level

With New high-level for data blocks, Fastai reduces the amount of boilerplate code that is usually involved in deep learning applications. By allowing users to concentrate on the essential elements of model construction and training, this abstraction speeds up the development process.

2. Abstractions of Training Loops

The library presents the idea of “Learners,” which are objects that combine the model, data, and optimization specifics. This method makes deep learning more approachable for novices by streamlining the training loop and giving seasoned users more customization options for their processes.

3. PyTorch integration

Fastai, which is based on PyTorch, is well-integrated with the popular deep learning framework. Users can take advantage of Fastai’s high-level abstractions and PyTorch’s functionalities at the same time. Users will always have the option to explore PyTorch-specific features as needed thanks to this integration.

4. APIs Specific to Applications

For a number of disciplines, including computer vision, natural language processing, tabular data, and collaborative filtering, Fastai offers specific APIs. These application-specific APIs speed up the creation of models for certain applications by offering pre-built methods and classes suited to typical tasks in each domain.

5. Data Block API

Deep learning requires handling data, and Fastai’s Data Block API makes this process easier. With clear and expressive code, users may import, preprocess, and enhance datasets with ease. This adaptability is especially helpful when working with various data forms and types.

How to Install FastAI?

With Google Colab, you can utilize fastai without needing to install anything. However, if you’re using Linux or Windows, you can install it on your system using conda(strongly recommended).

Step 1: Install pytorch and FastAI

You can install PyTorch using the conda line shown here

conda install -c fastai fastai
pip install fastai

Train an image with Image Classifier

Step 1: Import necessary libraries


from import *
from PIL import Image
import requests
from io import BytesIO
from sklearn.metrics import classification_report

Step 2: Load the Dataset

Data Loading: The MNIST dataset is loaded using untar_data and ImageDataLoaders.from_folder.


path = untar_data(URLs.MNIST_TINY)
dls = ImageDataLoaders.from_folder(path)




Step 3: Split Data into Train, test and Validation


dls = ImageDataLoaders.from_folder(path, train='train', valid='valid')

Step 4: Train a Model

  • Model Creation: We create a learner (cnn_learner) using a ResNet18 architecture for image classification. The metrics=accuracy argument specifies that we’re interested in tracking the accuracy during training.
  • Training: The model is fine-tuned for 2 epochs using learn.fine_tune.

The cnn_learner function in Fastai is used to create a Convolutional Neural Network (CNN) model for image classification. Here’s a brief explanation of its parameters:

  • dls: DataLoaders object containing your training, validation, and test data.
  • arch: Architecture of the model. You used resnet18 in your code, which is a pre-trained ResNet-18 model.
  • metrics: Evaluation metric(s) to monitor during training. You used accuracy in your code.


learn = cnn_learner(dls, resnet18, metrics=accuracy)

epoch    train_loss    valid_loss    accuracy    time
0    0.979080    0.263832    0.892704    00:15
epoch    train_loss    valid_loss    accuracy    time
0    0.346416    0.196786    0.919886    00:25
1    0.254296    0.185233    0.935622    00:13

Step 5: Evaluation Metrics


preds, targets = learn.get_preds()
pred_labels = preds.argmax(dim=1# Convering to class labels
true_labels = targets
report = classification_report(true_labels, pred_labels)


           precision    recall  f1-score   support

           0       0.94      0.93      0.93       346
           1       0.93      0.94      0.94       353

    accuracy                           0.93       699
   macro avg       0.93      0.93      0.93       699
weighted avg       0.93      0.93      0.93       699

Step 6: Manual Testing


# URL of the image (replace the link with your own link)
# Download the image from the URL
response = requests.get(image_url)
img = PILImage.create(BytesIO(response.content))
# Show the image



Prediction Image


pred, _, _ = learn.predict(img)
print(f"Predicted: {pred}")


Predicted: 7

Since, the image is somewhat representing the form of ‘7’ digit. Hence, it predicted accurately.


In conclusion, Fastai emerges as a robust and user-friendly deep learning library, striking a balance between high-level abstractions for quick development and low-level components for research flexibility. Its integration with PyTorch, modular design, and application-specific APIs make it a preferred choice for both beginners and seasoned practitioners.Overall, Fastai stands out as a powerful tool that empowers both researchers and practitioners in the field of deep learning, offering a harmonious blend of simplicity, flexibility, and performance. With its diverse set of features and a supportive community, Fastai remains at the forefront of facilitating breakthroughs in the dynamic landscape of deep learning.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads