{ "cells": [ { "cell_type": "markdown", "id": "da3518b0-c8a6-4087-a038-427e133f8b98", "metadata": {}, "source": [ "# AutoMM for Scanned Document Classification\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/document_prediction/document_classification.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/document_prediction/document_classification.ipynb)\n", "\n", "\n", "\n", "Paper documents in an organization are a crucial source of information, regardless of industry. \n", "Dealing with paper documents is a headache because they can occupy a significant amount of space, can easily wear or fade with time, and are difficult to keep track of. \n", "As such, there is a growing trend to digitizing paper documents via scanners, cameras, etc. \n", "However, digitization does not necessarily bring automation, and identifying, categorizing, and analyzing digital documents can still be a labor-intensive process. \n", "For example, classifying digital books into different genres, and categorizing scanned receipts into *utilities*, *transportation*, *insurance*, *rent*, *supplies*, etc. are time-consuming and tiresome if done manually. \n", "With newer AI technologies, automating digital document processing becomes easier and more effective. \n", "It’s fair to say that AI has been the bedrock of modern digital document processing systems.\n", "\n", "In this tutorial, we show how you can build a scanned document classifier with Autogluon Multimodal using a few lines of code. Let’s get started!" ] }, { "cell_type": "markdown", "id": "ad59ee0e-bb1d-46a6-a815-b1d7c5c20e4c", "metadata": {}, "source": [ "## Get a Document Dataset\n", "Now let's download a scanned document dataset. \n", "This dataset is a sample of [RVL-CDIP](https://huggingface.co/datasets/rvl_cdip) which originally consists of 400,000 grayscale images in 16 classes, with 25,000 images per class. \n", "Here, we sampled around 100 documents and three categories of document including budget (labelled as 0), email (labelled as 1), and form (labelled as 2)." ] }, { "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": "7c43dcaf-0cc7-4b0c-b8d3-87982dabd383", "metadata": {}, "outputs": [], "source": [ "import warnings\n", "warnings.filterwarnings('ignore')\n", "\n", "import os\n", "import pandas as pd\n", "from autogluon.core.utils.loaders import load_zip\n", "\n", "download_dir = './ag_automm_tutorial_doc_classifier'\n", "zip_file = \"https://automl-mm-bench.s3.amazonaws.com/doc_classification/rvl_cdip_sample.zip\"\n", "load_zip.unzip(zip_file, unzip_dir=download_dir)" ] }, { "cell_type": "markdown", "id": "fd12413b-9ae7-4333-841f-bcf1b38edde4", "metadata": {}, "source": [ "We load the training and test data below." ] }, { "cell_type": "code", "execution_count": null, "id": "3a65a189-481b-48bd-88ae-0238e44eb22f", "metadata": {}, "outputs": [], "source": [ "dataset_path = os.path.join(download_dir, \"rvl_cdip_sample\")\n", "rvl_cdip_data = pd.read_csv(f\"{dataset_path}/rvl_cdip_train_data.csv\")\n", "train_data = rvl_cdip_data.sample(frac=0.8, random_state=200)\n", "test_data = rvl_cdip_data.drop(train_data.index)" ] }, { "cell_type": "markdown", "id": "81322085-a6fc-45d3-8b3e-c5a2487d90dc", "metadata": {}, "source": [ "We need to expand the document paths to load them in training." ] }, { "cell_type": "code", "execution_count": null, "id": "dbf0f128-8f74-4537-82be-caa0b71de068", "metadata": {}, "outputs": [], "source": [ "from autogluon.multimodal.utils.misc import path_expander\n", "\n", "DOC_PATH_COL = \"doc_path\"\n", "\n", "train_data[DOC_PATH_COL] = train_data[DOC_PATH_COL].apply(lambda ele: path_expander(ele, base_folder=download_dir))\n", "test_data[DOC_PATH_COL] = test_data[DOC_PATH_COL].apply(lambda ele: path_expander(ele, base_folder=download_dir))\n", "print(test_data.head())" ] }, { "cell_type": "markdown", "id": "07943034-1f1f-449d-b696-1bf6026690e6", "metadata": {}, "source": [ "Let's display one of the document. \n", "As you can see, this is a budget document consisting of account number, account name, budgeted fund, expenditures, and etc." ] }, { "cell_type": "code", "execution_count": null, "id": "c4272ab9-058c-4e64-bc55-a260dd49e75f", "metadata": {}, "outputs": [], "source": [ "from IPython.display import Image, display\n", "\n", "example_image = train_data.iloc[0][DOC_PATH_COL]\n", "pil_img = Image(filename=example_image, width=500)\n", "display(pil_img)" ] }, { "cell_type": "markdown", "id": "1ae832ac-4de4-4741-a7f1-5115cbcf2c14", "metadata": {}, "source": [ "## Build a Scanned Document Classifier with AutoMM\n", "\n", "You can build a scanned document classifier with our MultiModalPredictor. \n", "All you need to do is to create a predictor and fit it with the above training dataset. \n", "Under the hood, AutoMM will automatically recognize handwritten or typed text, and make use of the recognized text, layout information, as well as the visual features for document classification. \n", "Model customization is also quite simple, you can specify the underline foundation model using the `model.document_transformer.checkpoint_name` hyperparameter and AutoMM support document foundation models such as [layoutlmv3](https://huggingface.co/microsoft/layoutlmv3-base), [layoutlmv2](https://huggingface.co/microsoft/layoutlmv2-base-uncased), [layoutlm-base](https://huggingface.co/microsoft/layoutlm-base-uncased), [layoutxlm](https://huggingface.co/docs/transformers/model_doc/layoutxlm), etc., \n", "as well as pure text models like [bert](https://huggingface.co/bert-base-uncased), [deberta](https://huggingface.co/microsoft/deberta-v3-base), just to name a few.\n", "\n", "Here, `label` is the name of the column that contains the target variable to predict, e.g., it is “label” in our example. \n", "We set the training time limit to 120 seconds for demonstration purposes." ] }, { "cell_type": "code", "execution_count": null, "id": "58e661fa-3de8-42f9-9ea1-ef4a4c6ad9ca", "metadata": {}, "outputs": [], "source": [ "from autogluon.multimodal import MultiModalPredictor\n", "\n", "predictor = MultiModalPredictor(label=\"label\")\n", "predictor.fit(\n", " train_data=train_data,\n", " hyperparameters={\"model.document_transformer.checkpoint_name\":\"microsoft/layoutlm-base-uncased\",\n", " \"optim.top_k_average_method\":\"best\",\n", " },\n", " time_limit=120,\n", ")" ] }, { "cell_type": "markdown", "id": "2fd8480a-ed58-4f2a-853a-a61eb5615d62", "metadata": {}, "source": [ "## Evaluate on Test Dataset\n", "\n", "You can evaluate the classifier on the test dataset to see how it performs:" ] }, { "cell_type": "code", "execution_count": null, "id": "a17cff5d-a55b-4edd-af66-cc64fb7246de", "metadata": {}, "outputs": [], "source": [ "scores = predictor.evaluate(test_data, metrics=[\"accuracy\"])\n", "print('The test acc: %.3f' % scores[\"accuracy\"])" ] }, { "cell_type": "markdown", "id": "92df3f92-b2c4-4965-b18e-e244d3296d8f", "metadata": {}, "source": [ "## Predict on a New Document\n", "\n", "Given an example document, let’s visualize it first," ] }, { "cell_type": "code", "execution_count": null, "id": "c1189633-17f2-4b42-ae42-a58fbc6905d3", "metadata": {}, "outputs": [], "source": [ "doc_path = test_data.iloc[1][DOC_PATH_COL]\n", "from IPython.display import Image, display\n", "pil_img = Image(filename=doc_path, width=500)\n", "display(pil_img)" ] }, { "cell_type": "markdown", "id": "6d096b5d-11a0-4f5f-9819-f1c6520c673a", "metadata": {}, "source": [ "We can easily use the final model to predict the label," ] }, { "cell_type": "code", "execution_count": null, "id": "28510ec8-e487-4739-8794-b694b7383f55", "metadata": {}, "outputs": [], "source": [ "predictions = predictor.predict({DOC_PATH_COL: [doc_path]})\n", "print(predictions)" ] }, { "cell_type": "markdown", "id": "675645cc-4905-46e9-9fdd-50439705b909", "metadata": {}, "source": [ "The above output shows that the trained model correctly classifies the given document into the *budget* category.\n", "\n", "If probabilities of all categories are needed, you can call predict_proba:" ] }, { "cell_type": "code", "execution_count": null, "id": "4da900c3-6402-4ff2-b8dd-6ff9374ef575", "metadata": {}, "outputs": [], "source": [ "proba = predictor.predict_proba({DOC_PATH_COL: [doc_path]})\n", "print(proba)" ] }, { "cell_type": "markdown", "id": "9d70788b-d460-42f2-a1eb-a5657a6930e1", "metadata": {}, "source": [ "## Extract Embeddings\n", "\n", "Extracting representation from the whole document learned by a model is also very useful. \n", "We provide extract_embedding function to allow predictor to return the N-dimensional document feature where N depends on the model." ] }, { "cell_type": "code", "execution_count": null, "id": "4a00e91c-31c0-4859-91ed-a78fea4d5d34", "metadata": {}, "outputs": [], "source": [ "feature = predictor.extract_embedding({DOC_PATH_COL: [doc_path]})\n", "print(feature[0].shape)" ] }, { "cell_type": "markdown", "id": "58ad7b77-0bb1-43a0-b0e6-f6918698a35c", "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." ] }, { "cell_type": "markdown", "id": "16fc7bb4-d15b-4bdb-8231-b3e142b7f2b5", "metadata": {}, "source": [ "## Customization\n", "\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 }