AutoMM for Image Classification - Quick Start

Open In Colab Open In SageMaker Studio Lab

In this quick start, we’ll use the task of image classification to illustrate how to use MultiModalPredictor. Once the data is prepared in Pandas DataFrame format, a single call to MultiModalPredictor.fit() will take care of the model training for you.

Create Image Dataset

For demonstration purposes, we use a subset of the Shopee-IET dataset from Kaggle. Each image in this data depicts a clothing item and the corresponding label specifies its clothing category. Our subset of the data contains the following possible labels: BabyPants, BabyShirt, womencasualshoes, womenchiffontop.

We can load a dataset by downloading a url data automatically:

import warnings
warnings.filterwarnings('ignore')
import pandas as pd

from autogluon.multimodal.utils.misc import shopee_dataset
download_dir = './ag_automm_tutorial_imgcls'
train_data_path, test_data_path = shopee_dataset(download_dir)
print(train_data_path)
Downloading ./ag_automm_tutorial_imgcls/file.zip from https://automl-mm-bench.s3.amazonaws.com/vision_datasets/shopee.zip...
                                                 image  label
0    /home/ci/autogluon/docs/tutorials/multimodal/i...      0
1    /home/ci/autogluon/docs/tutorials/multimodal/i...      0
2    /home/ci/autogluon/docs/tutorials/multimodal/i...      0
3    /home/ci/autogluon/docs/tutorials/multimodal/i...      0
4    /home/ci/autogluon/docs/tutorials/multimodal/i...      0
..                                                 ...    ...
795  /home/ci/autogluon/docs/tutorials/multimodal/i...      3
796  /home/ci/autogluon/docs/tutorials/multimodal/i...      3
797  /home/ci/autogluon/docs/tutorials/multimodal/i...      3
798  /home/ci/autogluon/docs/tutorials/multimodal/i...      3
799  /home/ci/autogluon/docs/tutorials/multimodal/i...      3

[800 rows x 2 columns]
100%|██████████| 84.0M/84.0M [00:02<00:00, 31.6MiB/s]

We can see there are 800 rows and 2 columns in this training dataframe. The 2 columns are image and label, and the image column contains the absolute paths of the images. Each row represents a different training sample.

In addition to image paths, MultiModalPredictor also supports image bytearrays during training and inference. We can load the dataset with bytearrays with the option is_bytearray set to True:

import warnings
warnings.filterwarnings('ignore')

download_dir = './ag_automm_tutorial_imgcls'
train_data_byte, test_data_byte = shopee_dataset(download_dir, is_bytearray=True)

Use AutoMM to Fit Models

Now, we fit a classifier using AutoMM as follows:

from autogluon.multimodal import MultiModalPredictor
import uuid
model_path = f"./tmp/{uuid.uuid4().hex}-automm_shopee"
predictor = MultiModalPredictor(label="label", path=model_path)
predictor.fit(
    train_data=train_data_path,
    time_limit=30, # seconds
)
=================== System Info ===================
AutoGluon Version:  1.1.1b20240716
Python Version:     3.10.13
Operating System:   Linux
Platform Machine:   x86_64
Platform Version:   #1 SMP Fri May 17 18:07:48 UTC 2024
CPU Count:          8
Pytorch Version:    2.3.1+cu121
CUDA Version:       12.1
Memory Avail:       28.65 GB / 30.95 GB (92.6%)
Disk Space Avail:   191.71 GB / 255.99 GB (74.9%)
===================================================
AutoGluon infers your prediction problem is: 'multiclass' (because dtype of label-column == int, but few unique label-values observed).
	4 unique label values:  [0, 1, 2, 3]
	If 'multiclass' is not the correct problem_type, please manually specify the problem_type parameter during Predictor init (You may specify problem_type as one of: ['binary', 'multiclass', 'regression', 'quantile'])

AutoMM starts to create your model. ✨✨✨

To track the learning progress, you can open a terminal and launch Tensorboard:
    ```shell
    # Assume you have installed tensorboard
    tensorboard --logdir /home/ci/autogluon/docs/tutorials/multimodal/image_prediction/tmp/1ed2f44efb2a4205ad7f13b6f2d16da2-automm_shopee
    ```

Seed set to 0
GPU Count: 1
GPU Count to be Used: 1
GPU 0 Name: Tesla T4
GPU 0 Memory: 0.42GB/15.0GB (Used/Total)

Using 16bit Automatic Mixed Precision (AMP)
GPU available: True (cuda), used: True
TPU available: False, using: 0 TPU cores
HPU available: False, using: 0 HPUs
LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0]

  | Name              | Type                            | Params | Mode 
------------------------------------------------------------------------------
0 | model             | TimmAutoModelForImagePrediction | 95.7 M | train
1 | validation_metric | MulticlassAccuracy              | 0      | train
2 | loss_func         | CrossEntropyLoss                | 0      | train
------------------------------------------------------------------------------
95.7 M    Trainable params
0         Non-trainable params
95.7 M    Total params
382.772   Total estimated model params size (MB)
Epoch 0, global step 2: 'val_accuracy' reached 0.22500 (best 0.22500), saving model to '/home/ci/autogluon/docs/tutorials/multimodal/image_prediction/tmp/1ed2f44efb2a4205ad7f13b6f2d16da2-automm_shopee/epoch=0-step=2.ckpt' as top 3
Epoch 0, global step 5: 'val_accuracy' reached 0.81875 (best 0.81875), saving model to '/home/ci/autogluon/docs/tutorials/multimodal/image_prediction/tmp/1ed2f44efb2a4205ad7f13b6f2d16da2-automm_shopee/epoch=0-step=5.ckpt' as top 3
Time limit reached. Elapsed time is 0:00:30. Signaling Trainer to stop.
Start to fuse 2 checkpoints via the greedy soup algorithm.
AutoMM has created your model. 🎉🎉🎉

To load the model, use the code below:
    ```python
    from autogluon.multimodal import MultiModalPredictor
    predictor = MultiModalPredictor.load("/home/ci/autogluon/docs/tutorials/multimodal/image_prediction/tmp/1ed2f44efb2a4205ad7f13b6f2d16da2-automm_shopee")
    ```

If you are not satisfied with the model, try to increase the training time, 
adjust the hyperparameters (https://auto.gluon.ai/stable/tutorials/multimodal/advanced_topics/customization.html),
or post issues on GitHub (https://github.com/autogluon/autogluon/issues).
<autogluon.multimodal.predictor.MultiModalPredictor at 0x7f9bd8506350>

label is the name of the column that contains the target variable to predict, e.g., it is “label” in our example. path indicates the directory where models and intermediate outputs should be saved. We set the training time limit to 30 seconds for demonstration purpose, but you can control the training time by setting configurations. To customize AutoMM, please refer to Customize AutoMM.

Evaluate on Test Dataset

You can evaluate the classifier on the test dataset to see how it performs, the test top-1 accuracy is:

scores = predictor.evaluate(test_data_path, metrics=["accuracy"])
print('Top-1 test acc: %.3f' % scores["accuracy"])
Top-1 test acc: 0.800

You can also evaluate on test data with image bytearray using the model trained on training data with image path, and vice versa:

scores = predictor.evaluate(test_data_byte, metrics=["accuracy"])
print('Top-1 test acc: %.3f' % scores["accuracy"])
Top-1 test acc: 0.800

Predict on a New Image

Given an example image, let’s visualize it first,

image_path = test_data_path.iloc[0]['image']
from IPython.display import Image, display
pil_img = Image(filename=image_path)
display(pil_img)
../../../_images/cbf97c376c1390b8ec9915b951f92171265d7907bda59cdf411ce0068ae84ea2.jpg

We can easily use the final model to predict the label,

predictions = predictor.predict({'image': [image_path]})
print(predictions)
[0]

If probabilities of all categories are needed, you can call predict_proba:

proba = predictor.predict_proba({'image': [image_path]})
print(proba)
[[0.32565272 0.31218475 0.18480536 0.17735715]]

Similarly as predictor.evaluate, we can also parse image_bytearrays into .predict and .predict_proba:

image_byte = test_data_byte.iloc[0]['image']
predictions = predictor.predict({'image': [image_byte]})
print(predictions)

proba = predictor.predict_proba({'image': [image_byte]})
print(proba)
[0]
[[0.32565272 0.31218475 0.18480536 0.17735715]]

Extract Embeddings

Extracting representation from the whole image learned by a model is also very useful. We provide extract_embedding function to allow predictor to return the N-dimensional image feature where N depends on the model(usually a 512 to 2048 length vector)

feature = predictor.extract_embedding({'image': [image_path]})
print(feature[0].shape)
(768,)

You should expect the same result when extract embedding from image bytearray:

feature = predictor.extract_embedding({'image': [image_byte]})
print(feature[0].shape)
(768,)

Save and Load

The trained predictor is automatically saved at the end of fit(), and you can easily reload it.

Warning

MultiModalPredictor.load() uses pickle module implicitly, which is known to be insecure. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling. Never load data that could have come from an untrusted source, or that could have been tampered with. Only load data you trust.

loaded_predictor = MultiModalPredictor.load(model_path)
load_proba = loaded_predictor.predict_proba({'image': [image_path]})
print(load_proba)
Load pretrained checkpoint: /home/ci/autogluon/docs/tutorials/multimodal/image_prediction/tmp/1ed2f44efb2a4205ad7f13b6f2d16da2-automm_shopee/model.ckpt
[[0.32565272 0.31218475 0.18480536 0.17735715]]

We can see the predicted class probabilities are still the same as above, which means same model!

Other Examples

You may go to AutoMM Examples to explore other examples about AutoMM.

Customization

To learn how to customize AutoMM, please refer to Customize AutoMM.