Sidebar and Body Layout

Image classification of Cats or Dogs with the FastAI library

This Python code utilizes the FastAI library to perform image classification tasks. It explains each line with comments, covering data loading, labeling, model training, and making predictions. Additionally, it demonstrates how to apply the trained model to classify an image from an external file.

For a detailed explanation, check out the video here.

Data Science with FastAI library

# Importing necessary functions and classes from fastai library for computer vision tasks
from fastai.vision.all import *

# Downloading and extracting the PETS dataset from fastai URLs
path = untar_data(URLs.PETS)

# Getting the paths of all image files within the 'images' directory of the PETS dataset
files = get_image_files(path/"images")

# Defining a function to label images based on their filenames
def label_func(f):
    # If the first letter of the filename is uppercase, label it as "cat"
    if f[0].isupper():
        return "cat"
    # Otherwise, label it as "dog"
    else:
        return "dog"

# Creating DataLoaders for the PETS dataset using the specified labeling function and resizing images to 224x224
dls = ImageDataLoaders.from_name_func(path, files, label_func, item_tfms=Resize(224))

# Displaying a batch of images from the dataset
dls.show_batch()

# Creating a learner object for a vision model using the specified DataLoaders and a pre-trained ResNet34 architecture
learn = vision_learner(dls, resnet34, metrics=error_rate)

# Fine-tuning the model on the dataset for one epoch
learn.fine_tune(1)

# Displaying the results of the model's predictions on a sample image from an external file
learn.show_results()

# Importing the Image class from PIL library to work with images
from PIL import Image

# Opening and loading an image file from a local directory
img = Image.open("C:\\Users\\HP\\Downloads\\1300.jpg")

# Making predictions on the loaded image using the trained model
prediction, _, _ = learn.predict(img)

# Printing the predicted label for the image
print(prediction)