{ "cells": [ { "cell_type": "markdown", "id": "79f89c74", "metadata": {}, "source": [ "# AutoMM for Entity Extraction with Text and Image - 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/stable/docs/tutorials/multimodal/multimodal_prediction/multimodal_ner.ipynb)\n", "[![Open In SageMaker Studio Lab](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/autogluon/autogluon/blob/stable/docs/tutorials/multimodal/multimodal_prediction/multimodal_ner.ipynb)\n", "\n", "We have introduced how to train an entity extraction model with text data.\n", "Here, we move a step further by integrating data of other modalities.\n", "In many real-world applications, textual data usually comes with data of other modalities.\n", "For example, Twitter allows you to compose tweets with text, photos, videos, and GIFs. Amazon.com uses text, images, and videos to describe their products.\n", "These auxiliary modalities can be leveraged as additional context resolution of entities.\n", "Now, with AutoMM, you can easily exploit multimodal data to enhance entity extraction without worrying about the details." ] }, { "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": "80685b47", "metadata": {}, "outputs": [], "source": [ "import os\n", "import pandas as pd\n", "import warnings\n", "warnings.filterwarnings('ignore')" ] }, { "cell_type": "markdown", "id": "5c8f6601", "metadata": {}, "source": [ "## Get the Twitter Dataset\n", "In the following example, we will demonstrate how to build a multimodal named entity recognition model with a real-world [Twitter dataset](https://github.com/jefferyYu/UMT/tree/master).\n", "This dataset consists of scrapped tweets from 2016 to 2017, and each tweet was composed of one sentence and one image. Let's download the dataset." ] }, { "cell_type": "code", "execution_count": null, "id": "a013bbf9", "metadata": {}, "outputs": [], "source": [ "download_dir = './ag_automm_tutorial_ner'\n", "zip_file = 'https://automl-mm-bench.s3.amazonaws.com/ner/multimodal_ner.zip'\n", "from autogluon.core.utils.loaders import load_zip\n", "load_zip.unzip(zip_file, unzip_dir=download_dir)" ] }, { "cell_type": "markdown", "id": "5ad44931", "metadata": {}, "source": [ "Next, we will load the CSV files." ] }, { "cell_type": "code", "execution_count": null, "id": "0fb3833c", "metadata": {}, "outputs": [], "source": [ "dataset_path = download_dir + '/multimodal_ner'\n", "train_data = pd.read_csv(f'{dataset_path}/twitter17_train.csv')\n", "test_data = pd.read_csv(f'{dataset_path}/twitter17_test.csv')\n", "label_col = 'entity_annotations'" ] }, { "cell_type": "markdown", "id": "e59ecca6", "metadata": {}, "source": [ "We need to expand the image paths to load them in training." ] }, { "cell_type": "code", "execution_count": null, "id": "0953b861", "metadata": {}, "outputs": [], "source": [ "image_col = 'image'\n", "train_data[image_col] = train_data[image_col].apply(lambda ele: ele.split(';')[0]) # Use the first image for a quick tutorial\n", "test_data[image_col] = test_data[image_col].apply(lambda ele: ele.split(';')[0])\n", "\n", "def path_expander(path, base_folder):\n", "\tpath_l = path.split(';')\n", "\tp = ';'.join([os.path.abspath(base_folder+path) for path in path_l])\n", "\treturn p\n", "\n", "train_data[image_col] = train_data[image_col].apply(lambda ele: path_expander(ele, base_folder=dataset_path))\n", "test_data[image_col] = test_data[image_col].apply(lambda ele: path_expander(ele, base_folder=dataset_path))\n", "\n", "train_data[image_col].iloc[0]" ] }, { "cell_type": "markdown", "id": "1ad95b52", "metadata": {}, "source": [ "Each row consists of the text and image of a single tweet and the entity_annotataions which contains the named entity annotations for the text column.\n", "Let’s look at an example row and display the text and picture of the tweet." ] }, { "cell_type": "code", "execution_count": null, "id": "03948c9c", "metadata": {}, "outputs": [], "source": [ "example_row = train_data.iloc[0]\n", "\n", "example_row" ] }, { "cell_type": "markdown", "id": "3ab8c69a", "metadata": {}, "source": [ "Below is the image of this tweet." ] }, { "cell_type": "code", "execution_count": null, "id": "29095db8", "metadata": {}, "outputs": [], "source": [ "example_image = example_row[image_col]\n", "\n", "from IPython.display import Image, display\n", "pil_img = Image(filename=example_image, width =300)\n", "display(pil_img)" ] }, { "cell_type": "markdown", "id": "e90f5250", "metadata": {}, "source": [ "As you can see, this photo contains the logos of the Real Madrid football club, Manchester United football club, and the UEFA super cup. Clearly, the key information of the tweet sentence is coded here in a different modality.\n", "\n", "## Training\n", "Now let’s fit the predictor with the training data.\n", "Firstly, we need to specify the problem_type to **ner**. \n", "As our annotations are used for text columns, to ensure the model to locate the correct text column for entity extraction, \n", "we need to set the corresponding column type to `text_ner` using the **column_types** parameter in cases where multiple text columns are present.\n", "Here we set a tight time budget for a quick demo." ] }, { "cell_type": "code", "execution_count": null, "id": "96ffa40b", "metadata": {}, "outputs": [], "source": [ "from autogluon.multimodal import MultiModalPredictor\n", "import uuid\n", "\n", "label_col = \"entity_annotations\"\n", "model_path = f\"./tmp/{uuid.uuid4().hex}-automm_multimodal_ner\"\n", "predictor = MultiModalPredictor(problem_type=\"ner\", label=label_col, path=model_path)\n", "predictor.fit(\n", "\ttrain_data=train_data,\n", "\tcolumn_types={\"text_snippet\":\"text_ner\"},\n", "\ttime_limit=300, #second\n", ")" ] }, { "cell_type": "markdown", "id": "4dc5ed50", "metadata": {}, "source": [ "Under the hood, AutoMM automatically detects the data modalities, selects the related models from the multimodal model pools, and trains the selected models.\n", "If multiple backbones are available, AutoMM appends a late-fusion model on top of them.\n", "\n", "## Evaluation" ] }, { "cell_type": "code", "execution_count": null, "id": "1bad3166", "metadata": {}, "outputs": [], "source": [ "predictor.evaluate(test_data, metrics=['overall_recall', \"overall_precision\", \"overall_f1\"])" ] }, { "cell_type": "markdown", "id": "7fee31b5", "metadata": {}, "source": [ "## Prediction\n", "\n", "You can easily obtain the predictions by calling predictor.predict()." ] }, { "cell_type": "code", "execution_count": null, "id": "40d2e9d2", "metadata": {}, "outputs": [], "source": [ "prediction_input = test_data.drop(columns=label_col).head(1)\n", "predictions = predictor.predict(prediction_input)\n", "print('Tweet:', prediction_input.text_snippet[0])\n", "print('Image path:', prediction_input.image[0])\n", "print('Predicted entities:', predictions[0])\n", "\n", "for entity in predictions[0]:\n", "\tprint(f\"Word '{prediction_input.text_snippet[0][entity['start']:entity['end']]}' belongs to group: {entity['entity_group']}\")" ] }, { "cell_type": "markdown", "id": "a8098787", "metadata": {}, "source": [ "## Reloading and Continuous Training\n", "\n", "The trained predictor is automatically saved and you can easily reload it using the path.\n", "If you are not satisfied with the current model performance, you can continue training the loaded model with new data." ] }, { "cell_type": "code", "execution_count": null, "id": "be0fe2b1", "metadata": {}, "outputs": [], "source": [ "new_predictor = MultiModalPredictor.load(model_path)\n", "new_model_path = f\"./tmp/{uuid.uuid4().hex}-automm_multimodal_ner_continue_train\"\n", "new_predictor.fit(train_data, time_limit=60, save_path=new_model_path)\n", "test_score = new_predictor.evaluate(test_data, metrics=['overall_f1'])\n", "print(test_score)" ] }, { "cell_type": "markdown", "id": "90e10604", "metadata": {}, "source": [ "## 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 }