{ "cells": [ { "cell_type": "markdown", "id": "a4292c3b", "metadata": {}, "source": [ "# AutoMM for Image Classification - Quick Start\n", "\n", "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/autogluon/autogluon/blob/master/docs/tutorials/multimodal/image_prediction/beginner_image_cls.ipynb)\n", "[![Open In SageMaker Studio Lab](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/autogluon/autogluon/blob/master/docs/tutorials/multimodal/image_prediction/beginner_image_cls.ipynb)\n", "\n", "\n", "\n", "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](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) format, a single call to `MultiModalPredictor.fit()` will take care of the model training for you.\n", "\n", "\n", "## Create Image Dataset\n", "\n", "For demonstration purposes, we use a subset of the [Shopee-IET dataset](https://www.kaggle.com/competitions/demo-shopee-iet-competition/data) from Kaggle.\n", "Each image in this data depicts a clothing item and the corresponding label specifies its clothing category.\n", "Our subset of the data contains the following possible labels: `BabyPants`, `BabyShirt`, `womencasualshoes`, `womenchiffontop`.\n", "\n", "We can load a dataset by downloading a url data automatically:" ] }, { "cell_type": "code", "execution_count": null, "id": "aa00faab-252f-44c9-b8f7-57131aa8251c", "metadata": { "tags": [ "remove-cell" ] }, "outputs": [], "source": [ "!pip install autogluon.multimodal\n" ] }, { "cell_type": "code", "execution_count": null, "id": "95ca4f2e", "metadata": {}, "outputs": [], "source": [ "import warnings\n", "warnings.filterwarnings('ignore')\n", "import pandas as pd\n", "\n", "from autogluon.multimodal.utils.misc import shopee_dataset\n", "download_dir = './ag_automm_tutorial_imgcls'\n", "train_data_path, test_data_path = shopee_dataset(download_dir)\n", "print(train_data_path)" ] }, { "cell_type": "markdown", "id": "77034c07", "metadata": {}, "source": [ "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.\n", "\n", "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`:" ] }, { "cell_type": "code", "execution_count": null, "id": "bd2f15e7", "metadata": {}, "outputs": [], "source": [ "import warnings\n", "warnings.filterwarnings('ignore')\n", "\n", "download_dir = './ag_automm_tutorial_imgcls'\n", "train_data_byte, test_data_byte = shopee_dataset(download_dir, is_bytearray=True)" ] }, { "cell_type": "markdown", "id": "b6640353", "metadata": {}, "source": [ "## Use AutoMM to Fit Models\n", "\n", "Now, we fit a classifier using AutoMM as follows:" ] }, { "cell_type": "code", "execution_count": null, "id": "96e31052", "metadata": {}, "outputs": [], "source": [ "from autogluon.multimodal import MultiModalPredictor\n", "import uuid\n", "model_path = f\"./tmp/{uuid.uuid4().hex}-automm_shopee\"\n", "predictor = MultiModalPredictor(label=\"label\", path=model_path)\n", "predictor.fit(\n", " train_data=train_data_path,\n", " time_limit=30, # seconds\n", ")" ] }, { "cell_type": "markdown", "id": "199ced03", "metadata": {}, "source": [ "**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](../advanced_topics/customization.ipynb).\n", "\n", "\n", "## Evaluate on Test Dataset\n", "\n", "You can evaluate the classifier on the test dataset to see how it performs, the test top-1 accuracy is:" ] }, { "cell_type": "code", "execution_count": null, "id": "4e4078bd", "metadata": {}, "outputs": [], "source": [ "scores = predictor.evaluate(test_data_path, metrics=[\"accuracy\"])\n", "print('Top-1 test acc: %.3f' % scores[\"accuracy\"])" ] }, { "cell_type": "markdown", "id": "7f00b3ec", "metadata": {}, "source": [ "You can also evaluate on test data with image bytearray using the model trained on training data with image path, and vice versa:" ] }, { "cell_type": "code", "execution_count": null, "id": "246b751d", "metadata": {}, "outputs": [], "source": [ "scores = predictor.evaluate(test_data_byte, metrics=[\"accuracy\"])\n", "print('Top-1 test acc: %.3f' % scores[\"accuracy\"])" ] }, { "cell_type": "markdown", "id": "9c60aa65", "metadata": {}, "source": [ "## Predict on a New Image\n", "\n", "Given an example image, let's visualize it first," ] }, { "cell_type": "code", "execution_count": null, "id": "f08caa07", "metadata": {}, "outputs": [], "source": [ "image_path = test_data_path.iloc[0]['image']\n", "from IPython.display import Image, display\n", "pil_img = Image(filename=image_path)\n", "display(pil_img)" ] }, { "cell_type": "markdown", "id": "3ddc4aa7", "metadata": {}, "source": [ "We can easily use the final model to `predict` the label," ] }, { "cell_type": "code", "execution_count": null, "id": "f21c9030", "metadata": {}, "outputs": [], "source": [ "predictions = predictor.predict({'image': [image_path]})\n", "print(predictions)" ] }, { "cell_type": "markdown", "id": "fee61517", "metadata": {}, "source": [ "If probabilities of all categories are needed, you can call `predict_proba`:" ] }, { "cell_type": "code", "execution_count": null, "id": "ca205a5c", "metadata": {}, "outputs": [], "source": [ "proba = predictor.predict_proba({'image': [image_path]})\n", "print(proba)" ] }, { "cell_type": "markdown", "id": "26e93609", "metadata": {}, "source": [ "Similarly as `predictor.evaluate`, we can also parse image_bytearrays into `.predict` and `.predict_proba`:" ] }, { "cell_type": "code", "execution_count": null, "id": "b2a193b3", "metadata": {}, "outputs": [], "source": [ "image_byte = test_data_byte.iloc[0]['image']\n", "predictions = predictor.predict({'image': [image_byte]})\n", "print(predictions)\n", "\n", "proba = predictor.predict_proba({'image': [image_byte]})\n", "print(proba)" ] }, { "cell_type": "markdown", "id": "2f6747d2", "metadata": {}, "source": [ "## Extract Embeddings\n", "\n", "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)" ] }, { "cell_type": "code", "execution_count": null, "id": "8f0e4f60", "metadata": {}, "outputs": [], "source": [ "feature = predictor.extract_embedding({'image': [image_path]})\n", "print(feature[0].shape)" ] }, { "cell_type": "markdown", "id": "6e354734", "metadata": {}, "source": [ "You should expect the same result when extract embedding from image bytearray:" ] }, { "cell_type": "code", "execution_count": null, "id": "b17a240a", "metadata": {}, "outputs": [], "source": [ "feature = predictor.extract_embedding({'image': [image_byte]})\n", "print(feature[0].shape)" ] }, { "cell_type": "markdown", "id": "67728302", "metadata": {}, "source": [ "## Save and Load\n", "\n", "The trained predictor is automatically saved at the end of `fit()`, and you can easily reload it.\n", "\n", "```{warning}\n", "\n", "`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.**\n", "\n", "```" ] }, { "cell_type": "code", "execution_count": null, "id": "6df38a6e", "metadata": {}, "outputs": [], "source": [ "loaded_predictor = MultiModalPredictor.load(model_path)\n", "load_proba = loaded_predictor.predict_proba({'image': [image_path]})\n", "print(load_proba)" ] }, { "cell_type": "markdown", "id": "f650eda5", "metadata": {}, "source": [ "We can see the predicted class probabilities are still the same as above, which means same model!\n", "\n", "## Other Examples\n", "\n", "You may go to [AutoMM Examples](https://github.com/autogluon/autogluon/tree/master/examples/automm) to explore other examples about AutoMM.\n", "\n", "## Customization\n", "To learn how to customize AutoMM, please refer to [Customize AutoMM](../advanced_topics/customization.ipynb)." ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }