--- comments: true --- # Image Multi-Label Classification Module Tutorial ## I. Overview The image multi-label classification module is a crucial component in computer vision systems, responsible for assigning multiple labels to input images. Unlike traditional image classification tasks that assign a single category to an image, multi-label classification tasks require assigning multiple relevant categories to an image. The performance of this module directly impacts the accuracy and efficiency of the entire computer vision system. The image multi-label classification module typically takes an image as input and, through deep learning or other machine learning algorithms, classifies it into multiple predefined categories based on its characteristics and content. For example, an image containing both a cat and a dog might be labeled as both "cat" and "dog" by the image multi-label classification module. These classification labels are then output for subsequent processing and analysis by other modules or systems. ## II. Supported Model List > The inference time only includes the model inference time and does not include the time for pre- or post-processing.
ModelModel Download Link mAP(%) GPU Inference Time (ms)
[Normal Mode / High-Performance Mode]
CPU Inference Time (ms)
[Normal Mode / High-Performance Mode]
Model Storage Size (MB) Description
CLIP_vit_base_patch16_448_ML Inference Model/Training Model 89.15 48.87 / 8.10 275.33 / 188.48 325.6 CLIP_ML is an image multi-label classification model based on CLIP, which significantly improves accuracy on multi-label classification tasks by incorporating an ML-Decoder.
PP-HGNetV2-B0_ML Inference Model/Training Model 80.98 7.15 / 1.77 21.35 / 8.19 39.6 PP-HGNetV2_ML is an image multi-label classification model based on PP-HGNetV2, which significantly improves accuracy on multi-label classification tasks by incorporating an ML-Decoder.
PP-HGNetV2-B4_ML Inference Model/Training Model 87.96 8.11 / 2.82 44.76 / 29.38 88.5
PP-HGNetV2-B6_ML Inference Model/Training Model 91.25 34.54 / 8.22 189.17 / 189.17 286.5
PP-LCNet_x1_0_ML Inference Model/Training Model 77.96 5.28 / 1.62 13.16 / 5.61 29.4 PP-LCNet_ML is an image multi-label classification model based on PP-LCNet, which significantly improves accuracy on multi-label classification tasks by incorporating an ML-Decoder.
ResNet50_ML Inference Model/Training Model 83.50 10.54 / 2.97 55.39 / 35.52 108.9 ResNet50_ML is an image multi-label classification model based on ResNet50, which significantly improves accuracy on multi-label classification tasks by incorporating an ML-Decoder.
Test Environment Description:
Mode GPU Configuration CPU Configuration Acceleration Technology Combination
Normal Mode FP32 Precision / No TRT Acceleration FP32 Precision / 8 Threads PaddleInference
High-Performance Mode Optimal combination of pre-selected precision types and acceleration strategies FP32 Precision / 8 Threads Pre-selected optimal backend (Paddle/OpenVINO/TRT, etc.)
## III. Quick Integration > ❗ Before quick integration, please install the PaddleX wheel package. For detailed instructions, refer to the [PaddleX Local Installation Guide](../../../installation/installation.en.md) After installing the wheel package, you can complete multi-label classification module inference with just a few lines of code. You can switch between models in this module freely, and you can also integrate the model inference of the multi-label classification module into your project. Before running the following code, please download the [demo image](https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/multilabel_classification_005.png) to your local machine. ```bash from paddlex import create_model model = create_model(model_name="PP-LCNet_x1_0_ML") output = model.predict(input="multilabel_classification_005.png", batch_size=1) for res in output: res.print() res.save_to_img("./output/") res.save_to_json("./output/res.json") ``` After running, the result obtained is: ```bash {'res': {'input_path': 'multilabel_classification_005.png', 'class_ids': [46, 49, 47, 45, 60, 43, 39], 'scores': [0.99972, 0.99601, 0.99277, 0.65718, 0.56914, 0.56436, 0.52865], 'label_names': ['banana', 'orange', 'apple', 'bowl', 'dining table', 'knife', 'bottle']}} ``` The meanings of the running results parameters are as follows: - `input_path`: Indicates the path of the input multi-class image to be predicted. - `page_index`: If the input is a PDF file, it indicates which page of the PDF is currently being processed; otherwise, it is `None`. - `class_ids`: Indicates the predicted label IDs of the multi-class image. - `scores`: Indicates the confidence scores of the predicted labels of the multi-class image. - `label_names`: Indicates the predicted label names of the multi-class image. The visualization image is as follows: **Note:** Due to network issues, the above URL may not be accessible. If you need to access this link, please check the validity of the URL and try again. If the problem persists, it may be related to the link itself or the network connection. Related methods, parameters, and explanations are as follows: * `create_model` instantiates a multi-label classification model (here, `PP-LCNet_x1_0_ML` is used as an example), and the specific explanations are as follows:
Parameter Parameter Description Parameter Type Options Default Value
model_name Name of the model str None PP-LCNet_x1_0_ML
model_dir Path to store the model str None None
device The device used for model inference str It supports specifying specific GPU card numbers, such as "gpu:0", other hardware card numbers, such as "npu:0", or CPU, such as "cpu". gpu:0
use_hpip Whether to enable the high-performance inference plugin bool None False
hpi_config High-performance inference configuration dict | None None None
* The `model_name` must be specified. After specifying `model_name`, the default model parameters built into PaddleX are used. If `model_dir` is specified, the user-defined model is used. * The `predict()` method of the multi-label classification model is called for inference prediction. The `predict()` method has parameters `input` and `batch_size`, which are explained as follows:
Parameter Parameter Description Parameter Type Options Default Value
input Data to be predicted, supporting multiple input types Python Var/str/list
  • Python variable, such as image data represented by numpy.ndarray
  • File path, such as the local path of an image file: /root/data/img.jpg
  • URL link, such as the network URL of an image file: Example
  • Local directory, the directory should contain data files to be predicted, such as the local path: /root/data/
  • List, the elements of the list should be of the above-mentioned data types, such as [numpy.ndarray, numpy.ndarray], [\"/root/data/img1.jpg\", \"/root/data/img2.jpg\"], [\"/root/data1\", \"/root/data2\"]
None
batch_size Batch size int Any integer 1
* The prediction results are processed, and the prediction result for each sample is of type `dict`. It supports operations such as printing, saving as an image, and saving as a `json` file:
Method Method Description Parameter Parameter Type Parameter Description Default Value
print() Print the results to the terminal format_json bool Whether to format the output content using JSON indentation True
indent int Specify the indentation level to beautify the output JSON data, making it more readable, only effective when format_json is True 4
ensure_ascii bool Control whether to escape non-ASCII characters to Unicode. If set to True, all non-ASCII characters will be escaped; False retains the original characters, only effective when format_json is True False
save_to_json() Save the results as a JSON file save_path str The path to save the file. If it is a directory, the saved file name will be consistent with the input file name None
indent int Specify the indentation level to beautify the output JSON data, making it more readable, only effective when format_json is True 4
ensure_ascii bool Control whether to escape non-ASCII characters to Unicode. If set to True, all non-ASCII characters will be escaped; False retains the original characters, only effective when format_json is True False
save_to_img() Save the results as an image file save_path str The path to save the file. If it is a directory, the saved file name will be consistent with the input file name None
* Additionally, it supports obtaining the visualization image with results and the prediction results through attributes, as follows:
Attribute Attribute Description
json Get the prediction result in json format
img Get the visualization image in dict format
For more information on using PaddleX's single-model inference APIs, please refer to the [PaddleX Single-Model Python Script Usage Instructions](../../instructions/model_python_API.en.md). ## IV. Custom Development If you are seeking higher accuracy from existing models, you can use PaddleX's custom development capabilities to develop better multi-label classification models. Before using PaddleX to develop multi-label classification models, please ensure that you have installed the relevant model training plugins for image classification in PaddleX. The installation process can be found in the custom development section of the [PaddleX Local Installation Guide](../../../installation/installation.en.md). ### 4.1 Data Preparation Before model training, you need to prepare the dataset for the corresponding task module. PaddleX provides data validation functionality for each module, and only data that passes data validation can be used for model training. Additionally, PaddleX provides demo datasets for each module, which you can use to complete subsequent development. If you wish to use your own private dataset for subsequent model training, please refer to the [PaddleX Image Multi-Label Classification Task Module Data Annotation Guide](../../../data_annotations/cv_modules/ml_classification.en.md). #### 4.1.1 Demo Data Download You can use the following command to download the demo dataset to a specified folder: ```bash wget https://paddle-model-ecology.bj.bcebos.com/paddlex/data/mlcls_nus_examples.tar -P ./dataset tar -xf ./dataset/mlcls_nus_examples.tar -C ./dataset/ ``` #### 4.1.2 Data Validation A single command can complete data validation: ```bash python main.py -c paddlex/configs/modules/image_multilabel_classification/PP-LCNet_x1_0_ML.yaml \ -o Global.mode=check_dataset \ -o Global.dataset_dir=./dataset/mlcls_nus_examples ``` After executing the above command, PaddleX will validate the dataset and summarize its basic information. If the command runs successfully, it will print `Check dataset passed !` in the log. The validation results file is saved in `./output/check_dataset_result.json`, and related outputs are saved in the `./output/check_dataset` directory in the current directory, including visual examples of sample images and sample distribution histograms.
πŸ‘‰ Details of Validation Results (Click to Expand)

The specific content of the validation result file is:

{
  "done_flag": true,
  "check_pass": true,
  "attributes": {
    "label_file": "../../dataset/mlcls_nus_examples/label.txt",
    "num_classes": 33,
    "train_samples": 17463,
    "train_sample_paths": [
      "check_dataset/demo_img/0543_4338693.jpg",
      "check_dataset/demo_img/0272_347806939.jpg",
      "check_dataset/demo_img/0069_2291994812.jpg",
      "check_dataset/demo_img/0012_1222850604.jpg",
      "check_dataset/demo_img/0238_53773041.jpg",
      "check_dataset/demo_img/0373_541261977.jpg",
      "check_dataset/demo_img/0567_519506868.jpg",
      "check_dataset/demo_img/0023_289621557.jpg",
      "check_dataset/demo_img/0581_484524659.jpg",
      "check_dataset/demo_img/0325_120753036.jpg"
    ],
    "val_samples": 17463,
    "val_sample_paths": [
      "check_dataset/demo_img/0546_130758157.jpg",
      "check_dataset/demo_img/0284_2230710138.jpg",
      "check_dataset/demo_img/0090_1491261559.jpg",
      "check_dataset/demo_img/0013_392798436.jpg",
      "check_dataset/demo_img/0246_2248376356.jpg",
      "check_dataset/demo_img/0377_1349296474.jpg",
      "check_dataset/demo_img/0570_2457645006.jpg",
      "check_dataset/demo_img/0027_309333946.jpg",
      "check_dataset/demo_img/0584_132639537.jpg",
      "check_dataset/demo_img/0329_206031527.jpg"
    ]
  },
  "analysis": {
    "histogram": "check_dataset/histogram.png"
  },
  "dataset_path": "mlcls_nus_examples",
  "show_type": "image",
  "dataset_type": "MLClsDataset"
}

In the above validation results, check_pass being True indicates that the dataset format meets the requirements. Explanations for other indicators are as follows:

Additionally, the dataset validation analyzes the sample number distribution across all classes in the dataset and generates a distribution histogram (histogram.png):

#### 4.1.3 Dataset Format Conversion/Dataset Splitting (Optional) After completing data validation, you can convert the dataset format or re-split the training/validation ratio of the dataset by modifying the configuration file or appending hyperparameters.
πŸ‘‰ Dataset Format Conversion/Dataset Splitting Details (Click to Expand)

(1) Dataset Format Conversion

The multi-label image classification supports the conversion of COCO format datasets to MLClsDataset format. The parameters for dataset format conversion can be set by modifying the fields under CheckDataset in the configuration file. Examples of some parameters in the configuration file are as follows:

For example, if you want to convert a COCO format dataset to MLClsDataset format, you need to modify the configuration file as follows:

cd /path/to/paddlex
wget https://paddle-model-ecology.bj.bcebos.com/paddlex/data/det_coco_examples.tar -P ./dataset
tar -xf ./dataset/det_coco_examples.tar -C ./dataset/
......
CheckDataset:
  ......
  convert:
    enable: True
    src_dataset_type: COCO
  ......

Then execute the command:

python main.py -c paddlex/configs/modules/image_multilabel_classification/PP-LCNet_x1_0_ML.yaml \
    -o Global.mode=check_dataset \
    -o Global.dataset_dir=./dataset/det_coco_examples

After the data conversion is executed, the original annotation files will be renamed to xxx.bak in the original path.

The above parameters also support being set by appending command line arguments:

python main.py -c paddlex/configs/modules/image_multilabel_classification/PP-LCNet_x1_0_ML.yaml \
    -o Global.mode=check_dataset \
    -o Global.dataset_dir=./dataset/det_coco_examples \
    -o CheckDataset.convert.enable=True \
    -o CheckDataset.convert.src_dataset_type=COCO

(2) Dataset Splitting

The dataset splitting parameters can be set by modifying the fields under CheckDataset in the configuration file. An example of part of the configuration file is shown below:

For example, if you want to re-split the dataset with a 90% training set and a 10% validation set, modify the configuration file as follows:

......
CheckDataset:
  ......
  split:
    enable: True
    train_percent: 90
    val_percent: 10
  ......

Then execute the command:

python main.py -c paddlex/configs/modules/image_multilabel_classification/PP-LCNet_x1_0_ML.yaml \
    -o Global.mode=check_dataset \
    -o Global.dataset_dir=./dataset/det_coco_examples

After the data splitting is executed, the original annotation files will be renamed to xxx.bak in the original path.

These parameters can also be set by appending command-line arguments:

python main.py -c paddlex/configs/modules/image_multilabel_classification/PP-LCNet_x1_0_ML.yaml \
    -o Global.mode=check_dataset \
    -o Global.dataset_dir=./dataset/det_coco_examples \
    -o CheckDataset.split.enable=True \
    -o CheckDataset.split.train_percent=90 \
    -o CheckDataset.split.val_percent=10
### 4.2 Model Training A single command can complete the model training. Taking the training of the image multi-label classification model PP-LCNet_x1_0_ML as an example: ```bash python main.py -c paddlex/configs/modules/image_multilabel_classification/PP-LCNet_x1_0_ML.yaml \ -o Global.mode=train \ -o Global.dataset_dir=./dataset/mlcls_nus_examples ``` the following steps are required: * Specify the path of the model's `.yaml` configuration file (here it is `PP-LCNet_x1_0_ML.yaml`,When training other models, you need to specify the corresponding configuration files. The relationship between the model and configuration files can be found in the [PaddleX Model List (CPU/GPU)](../../../support_list/models_list.en.md)) * Specify the mode as model training: `-o Global.mode=train` * Specify the path of the training dataset: `-o Global.dataset_dir`. Other related parameters can be set by modifying the fields under `Global` and `Train` in the `.yaml` configuration file, or adjusted by appending parameters in the command line. For example, to specify training on the first 2 GPUs: `-o Global.device=gpu:0,1`; to set the number of training epochs to 10: `-o Train.epochs_iters=10`. For more modifiable parameters and their detailed explanations, refer to the configuration file parameter instructions for the corresponding task module of the model [PaddleX Common Model Configuration File Parameters](../../instructions/config_parameters_common.en.md).
πŸ‘‰ More Details (Click to Expand)
## 4.3 Model Evaluation After completing model training, you can evaluate the specified model weights file on the validation set to verify the model's accuracy. Using PaddleX for model evaluation can be done with a single command: ```bash python main.py -c paddlex/configs/modules/image_multilabel_classification/PP-LCNet_x1_0_ML.yaml \ -o Global.mode=evaluate \ -o Global.dataset_dir=./dataset/mlcls_nus_examples ``` Similar to model training, the following steps are required: * Specify the `.yaml` configuration file path for the model (here it's `PP-LCNet_x1_0_ML.yaml`) * Specify the mode as model evaluation: `-o Global.mode=evaluate` * Specify the path to the validation dataset: `-o Global.dataset_dir` * Other related parameters can be set by modifying the `Global` and `Evaluate` fields in the `.yaml` configuration file. For details, refer to [PaddleX Common Model Configuration File Parameter Description](../../instructions/config_parameters_common.en.md). * New Feature: Paddle 3.0 support CINN (Compiler Infrastructure for Neural Networks) to accelerate training speed when using GPU device. Please specify `-o Train.dy2st=True` to enable it.
πŸ‘‰ More Details (Click to Expand)

When evaluating the model, you need to specify the model weights file path. Each configuration file has a default weight save path. If you need to change it, simply append the command line parameter to set it, such as -o Evaluate.weight_path=./output/best_model/best_model.pdparams.

After completing the model evaluation, an evaluate_result.json file will be produced, which records the evaluation results, specifically, whether the evaluation task was completed successfully and the model's evaluation metrics, including MultiLabelMAP;

### 4.4 Model Inference and Model Integration After completing model training and evaluation, you can use the trained model weights for inference predictions or Python integration. #### 4.4.1 Model Inference * Inference predictions can be performed through the command line with just one command. Before running the following code, please download the [demo image](https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/multilabel_classification_005.png) to your local machine. ```bash python main.py -c paddlex/configs/modules/image_multilabel_classification/PP-LCNet_x1_0_ML.yaml \ -o Global.mode=predict \ -o Predict.model_dir="./output/best_model/inference" \ -o Predict.input="multilabel_classification_005.png" ``` Similar to model training and evaluation, the following steps are required: * Specify the `.yaml` configuration file path for the model (here it's `PP-LCNet_x1_0_ML.yaml`) * Specify the mode as model inference prediction: `-o Global.mode=predict` * Specify the model weights path: `-o Predict.model_dir="./output/best_model/inference"` * Specify the input data path: `-o Predict.input="..."` Other related parameters can be set by modifying the `Global` and `Predict` fields in the `.yaml` configuration file. For details, refer to [PaddleX Common Model Configuration File Parameter Description](../../instructions/config_parameters_common.en.md). #### 4.4.2 Model Integration The model can be directly integrated into the PaddleX pipeline or directly into your own project. 1.Pipeline Integration The image multi-label classification module can be integrated into the [General Image Multi-label Classification Pipeline](../../../pipeline_usage/tutorials/cv_pipelines/image_multi_label_classification.en.md) of PaddleX. Simply replace the model path to update the image multi-label classification module of the relevant pipeline. In pipeline integration, you can use high-performance inference and serving deployment to deploy your model. 2.Module Integration The weights you produce can be directly integrated into the image multi-label classification module. Refer to the Python example code in [Quick Integration](#iii-quick-integration) and simply replace the model with the path to your trained model. You can also use the PaddleX high-performance inference plugin to optimize the inference process of your model and further improve efficiency. For detailed procedures, please refer to the [PaddleX High-Performance Inference Guide](../../../pipeline_deploy/high_performance_inference.en.md).