PaddleOCR PP-Structure 版面分析模型训练全攻略:从 PubLayNet 数据准备到 FGD 蒸馏、评估与推理部署
【免费下载链接】PaddleOCRTurn any PDF or image document into structured data for your AI. A powerful, lightweight OCR toolkit that bridges the gap between images/PDFs and LLMs. Supports 100+ languages.项目地址: https://gitcode.com/GitHub_Trending/pa/PaddleOCR
版面分析(Layout Analysis)是文档结构化理解的第一环:它把一张文档图片切分为 Text、Title、Table、Figure 等语义区域,为后续 OCR、表格识别与关键信息抽取提供定位基础。本文以 PaddleOCR 仓库中 train_layout.en.md 文档为主体,系统讲解基于 PP-PicoDet 的版面分析模型从环境安装、数据集准备、单卡/多卡训练、FGD 蒸馏训练,到指标评估、可视化预测、模型导出与推理的完整链路。读完本文,你将能够基于 PubLayNet、CDLA 等公开数据集训练自己的中英文与表格版面分析模型,并把它固化为推理模型集成到实际系统中。
1. 版面分析是什么:任务定义与模型家族
版面分析指的是对图片形式的文档进行区域划分,定位其中的关键区域,如文字、标题、表格、图片等。在 PP-Structure 的整套文档解析流程中,版面分析处于最前端,其输出的区域框直接决定了后续 OCR 与表格识别的作用范围。
从实现上看,版面分析算法基于 PaddleDetection 的轻量检测模型 PP-PicoDet 开发,目前提供三类模型:
| 模型类别 | 可检测区域 | 典型数据集 |
|---|---|---|
| 英文版面分析 | Text、Title、Table、Figure、List 共 5 类 | PubLayNet |
| 中文版面分析 | Text、Title、Figure、Figure caption、Table、Table caption、Header、Footer、Reference、Equation 共 10 类 | CDLA |
| 表格版面分析 | Table(表格区域) | TableBank / cTDaR 等 |
这三类模型的识别效果可参考 layout.jpg,其中 (a) 为英文版面分析、(b) 为中文版面分析、(c) 为表格版面分析的示意结果。
在 PaddleOCR 仓库中,版面分析模型的推理侧实现位于 ppstructure/layout/predict_layout.py,其中LayoutPredictor类完成了从图片预处理、PicoDet 推理到后处理的全过程:
- 预处理阶段对输入图片依次执行
Resize(缩放到 800×608)、NormalizeImage(ImageNet 均值方差归一化)、ToCHWImage与KeepKeys操作; - 推理阶段读取模型输出并拆分为 scores 与 boxes 两部分;
- 后处理阶段交由
PicoDetPostProcess(位于 ppocr/postprocess/picodet_postprocess.py)完成,包括多尺度特征解码、hard_nms去重、坐标回映射到原图,以及重复框合并等逻辑。
类别标签则通过字典文件加载,例如 layout_publaynet_dict.txt 依次包含text / title / list / table / figure5 个类别,与 PubLayNet 的 5 类标注一一对应。
2. 快速开始与模型清单
PP-Structure 目前提供了中文、英文、表格三类文档版面分析模型,完整模型清单见 models_list.en.md,其中与版面分析直接相关的模型包括:
| 模型名 | 说明 | 推理模型大小 |
|---|---|---|
| picodet_lcnet_x1_0_fgd_layout | 基于 PicoDet LCNet_x1_0 + FGD 在 PubLayNet 上训练的英文模型,识别 Text、Title、Table、Figure、List | 9.7M |
| picodet_lcnet_x1_0_fgd_layout_cdla | 基于 CDLA 数据集训练的中文模型,识别 10 类中文文献区域 | 9.7M |
| picodet_lcnet_x1_0_fgd_layout_table | 基于表格数据集训练的模型,可检测中英文文档中的表格区域 | 9.7M |
| ppyolov2_r50vd_dcn_365e_publaynet | 基于 PP-YOLOv2 的英文版面分析模型(精度优先) | 221.0M |
如果你只想快速体验而不训练,官方还提供了 whl 包形式,安装paddleocr<3.0后即可通过命令行或 Python 脚本直接调用,详见 quick_start.en.md。例如仅做版面分析(关闭表格与 OCR)的命令为:
paddleocr --image_dir=ppstructure/docs/table/1.png --type=structure --table=false --ocr=false对应 Python 调用方式:
import os import cv2 from paddleocr import PPStructure, save_structure_res table_engine = PPStructure(table=False, ocr=False, show_log=True) save_folder = './output' img_path = 'ppstructure/docs/table/1.png' img = cv2.imread(img_path) result = table_engine(img) save_structure_res(result, save_folder, os.path.basename(img_path).split('.')[0]) for line in result: line.pop('img') print(line)3. 环境安装:PaddlePaddle 与 PaddleDetection
3.1 安装 PaddlePaddle
python3 -m pip install --upgrade pip # GPU 安装 python3 -m pip install "paddlepaddle-gpu>=2.3" -i https://mirror.baidu.com/pypi/simple # CPU 安装 python3 -m pip install "paddlepaddle>=2.3" -i https://mirror.baidu.com/pypi/simple更多版本需求(如特定 CUDA 版本),请参照 PaddlePaddle 安装文档 中的说明进行操作。若通过 whl 包快速体验,也可参照 quick_start.en.md 使用paddlepaddle-gpu<=2.6或 CPU 版本安装。
3.2 安装 PaddleDetection
版面分析模型的训练、评估与动转静脚本来自 PaddleDetection 仓库:
# (1)下载 PaddleDetection 源码 git clone https://github.com/PaddlePaddle/PaddleDetection.git # (2)安装其他依赖 cd PaddleDetection python3 -m pip install -r requirements.txt4. 数据准备:PubLayNet 与更多版面数据集
如果希望直接体验预测过程,可以跳过数据准备,直接下载预训练模型(见第 5 节)。若要训练自己的模型,则需要准备 COCO 格式的标注数据。
4.1 英文数据集 PubLayNet
PubLayNet 是目前最大的文档版面分析数据集(约 96G),包含 5 个类别:{0: "Text", 1: "Title", 2: "List", 3: "Table", 4: "Figure"}。
# 下载数据 wget https://dax-cdn.cdn.appdomain.cloud/dax-publaynet/1.0.0/publaynet.tar.gz # 解压数据 tar -xvf publaynet.tar.gz解压之后的目录结构:
|-publaynet |- test |- PMC1277013_00004.jpg |- PMC1291385_00002.jpg | ... |- train.json |- train |- PMC1291385_00002.jpg |- PMC1277013_00004.jpg | ... |- val.json |- val |- PMC538274_00004.jpg |- PMC539300_00004.jpg | ...数据分布如下:
| 文件或目录 | 说明 | 数量 |
|---|---|---|
train/ | 训练集图片 | 335,703 |
val/ | 验证集图片 | 11,245 |
test/ | 测试集图片 | 11,405 |
train.json | 训练集标注文件 | - |
val.json | 验证集标注文件 | - |
标注格式:JSON 文件包含所有图像的标注,数据以字典嵌套的方式存放,包含以下 key:
info:标注文件信息;licenses:标注文件许可信息;images:标注文件中图像信息列表,每个元素是一张图像的信息,例如:
{ "file_name": "PMC4055390_00006.jpg", "height": 601, "width": 792, "id": 341427 }annotations:标注文件中目标物体的标注信息列表,每个元素是一个目标物体的标注信息,例如:
{ "segmentation": [], "area": 60518.099043117836, "iscrowd": 0, "image_id": 341427, "bbox": [50.58, 490.86, 240.15, 252.16], "category_id": 1, "id": 3322348 }其中bbox的格式为[x1, y1, w, h](左上角坐标 + 宽高),category_id与类别字典中的序号对应。
4.2 更多可选数据集
除 PubLayNet 外,官方还提供了多个版面分析数据集,将其标注处理为上述 JSON 格式后,即可按相同方式训练:
| 数据集 | 简介 |
|---|---|
| cTDaR2019_cTDaR | 用于表格检测(TRACKA)和表格识别(TRACKB),图片类型包含历史数据集(以 cTDaR_t0 开头)和现代数据集(以 cTDaR_t1 开头) |
| IIIT-AR-13K | 手动注释公开年度报告中的图形或页面构建,包含 table、figure、natural image、logo、signature 5 类 |
| CDLA | 中文文档版面分析数据集,面向中文文献(论文)场景,包含 10 类区域 |
| TableBank | 用于表格检测和识别的大型数据集,包含 Word 和 LaTeX 两种文档格式 |
| DocBank | 使用弱监督方法构建的大规模数据集(500K 文档页面),包含 12 类区域 |
5. 开始训练
官方提供了训练脚本、评估脚本和预测脚本,本节以 PubLayNet 预训练模型为例。如果不希望训练,可以直接下载预训练模型体验后面的评估、预测、动转静与推理流程,并跳过 5.1 与 5.2 节:
mkdir pretrained_model cd pretrained_model # 下载 PubLayNet 预训练模型(直接体验模型评估、预测、动转静) wget https://paddleocr.bj.bcebos.com/ppstructure/models/layout/picodet_lcnet_x1_0_fgd_layout.pdparams # 下载 PubLayNet 推理模型(直接体验模型推理) wget https://paddleocr.bj.bcebos.com/ppstructure/models/layout/picodet_lcnet_x1_0_fgd_layout_infer.tar如果测试图片为中文,可以下载中文 CDLA 数据集的预训练模型,识别 10 类文档区域;如果只检测图片中的表格区域,可以下载表格数据集的预训练模型。两类模型(picodet_lcnet_x1_0_fgd_layout_cdla与picodet_lcnet_x1_0_fgd_layout_table)的训练模型与推理模型均可在 models_list.en.md 中获取。
5.1 启动训练
使用 PaddleDetection 的版面分析配置文件启动训练(以configs/picodet/legacy_model/application/layout_analysis/picodet_lcnet_x1_0_layout.yml为例)。
修改配置文件:训练自己的数据集时,需要修改配置文件中的数据配置与类别数:
metric: COCO # 类别数 num_classes: 5 TrainDataset: !COCODataSet # 修改为你自己的训练数据目录 image_dir: train # 修改为你自己的训练数据标签文件 anno_path: train.json # 修改为你自己的训练数据根目录 dataset_dir: /root/publaynet/ data_fields: ['image', 'gt_bbox', 'gt_class', 'is_crowd'] EvalDataset: !COCODataSet # 修改为你自己的验证数据目录 image_dir: val # 修改为你自己的验证数据标签文件 anno_path: val.json # 修改为你自己的验证数据根目录 dataset_dir: /root/publaynet/ TestDataset: !ImageFolder # 修改为你自己的测试数据标签文件 anno_path: /root/publaynet/val.json开始训练:训练时会默认下载 PP-PicoDet 预训练模型,无需预先下载。GPU 训练支持单卡与多卡:
# 单卡训练 export CUDA_VISIBLE_DEVICES=0 python3 tools/train.py \ -c configs/picodet/legacy_model/application/layout_analysis/picodet_lcnet_x1_0_layout.yml \ --eval # 多卡训练,通过 --gpus 参数指定卡号 export CUDA_VISIBLE_DEVICES=0,1,2,3 python3 -m paddle.distributed.launch --gpus '0,1,2,3' tools/train.py \ -c configs/picodet/legacy_model/application/layout_analysis/picodet_lcnet_x1_0_layout.yml \ --eval正常启动训练后会看到类似如下的日志输出:
[08/15 04:02:30] ppdet.utils.checkpoint INFO: Finish loading model weights: /root/.cache/paddle/weights/LCNet_x1_0_pretrained.pdparams [08/15 04:02:46] ppdet.engine INFO: Epoch: [0] [ 0/1929] learning_rate: 0.040000 loss_vfl: 1.216707 loss_bbox: 1.142163 loss_dfl: 0.544196 loss: 2.903065 eta: 17 days, 13:50:26 batch_cost: 15.7452 data_cost: 2.9112 ips: 1.5243 images/s [08/15 04:03:19] ppdet.engine INFO: Epoch: [0] [ 20/1929] learning_rate: 0.064000 loss_vfl: 1.180627 loss_bbox: 0.939552 loss_dfl: 0.442436 loss: 2.628206 eta: 2 days, 12:18:53 batch_cost: 1.5770 data_cost: 0.0008 ips: 15.2184 images/s其中loss_vfl、loss_bbox、loss_dfl分别对应 PicoDet 的 Varifocal Loss 分类损失、回归损失与 Distribution Focal Loss,--eval表示训练的同时进行评估,评估过程中默认将最佳模型保存为output/picodet_lcnet_x1_0_layout/best_accuracy。
注意:
- 如果训练时显存 OOM,应将
TrainReader中batch_size调小,同时将LearningRate中base_lr等比例减小; - 官方发布的 config 均由 8 卡训练得到,如果改为 1 卡训练,
base_lr需要减小 8 倍; - 预测/评估时的配置文件务必与训练保持一致。
5.2 FGD 蒸馏训练
PaddleDetection 支持基于 FGD(Focal and Global Knowledge Distillation for Detectors,论文见 arXiv:2111.11837)的目标检测模型蒸馏训练。FGD 蒸馏分为两个部分:
- Focal 蒸馏:分离图像的前景和背景,让学生模型分别关注教师模型前景和背景部分特征的关键像素;
- Global 蒸馏:重建不同像素之间的关系并将其从教师转移到学生,以补偿 Focal 蒸馏中丢失的全局信息。
更换数据集并修改配置中的数据配置与类别数(参考 4.1 节)后,启动蒸馏训练:
# 单卡训练 export CUDA_VISIBLE_DEVICES=0 python3 tools/train.py \ -c configs/picodet/legacy_model/application/layout_analysis/picodet_lcnet_x1_0_layout.yml \ --slim_config configs/picodet/legacy_model/application/layout_analysis/picodet_lcnet_x2_5_layout.yml \ --eval-c:指定模型配置文件;--slim_config:指定压缩策略(蒸馏)配置文件。
picodet_lcnet_x1_0_fgd_layout正是以lcnet_x2_5为教师、lcnet_x1_0为学生进行 FGD 蒸馏得到的官方模型,这也是该模型在 9.7M 的轻量体积下仍能取得高精度的原因。
6. 模型评估与预测
6.1 指标评估
训练中模型参数默认保存在output/picodet_lcnet_x1_0_layout目录下。评估时,需要设置weights指向保存的参数文件;评估数据集可通过配置文件修改EvalDataset中的image_dir、anno_path和dataset_dir设置。
# GPU 评估,weights 为待测权重 python3 tools/eval.py \ -c configs/picodet/legacy_model/application/layout_analysis/picodet_lcnet_x1_0_layout.yml \ -o weights=./output/picodet_lcnet_x1_0_layout/best_model评估完成后会打印 COCO 风格的目标检测指标,包括 mAP(IoU=0.50:0.95)、AP0.5、AP0.75 以及不同尺寸目标的 AP/AR:
Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.935 Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.979 Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.956 Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.404 Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.782 Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.969 Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.539 Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.938 Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.949 Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.495 Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.818 Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.978 [08/15 07:07:09] ppdet.engine INFO: Total sample number: 11245, averge FPS: 24.405059207157436 [08/15 07:07:09] ppdet.engine INFO: Best test bbox ap is 0.935.若使用官方提供的预训练模型进行评估,或评估 FGD 蒸馏训练的模型,更换weights模型路径并带上--slim_config即可:
python3 tools/eval.py \ -c configs/picodet/legacy_model/application/layout_analysis/picodet_lcnet_x1_0_layout.yml \ --slim_config configs/picodet/legacy_model/application/layout_analysis/picodet_lcnet_x2_5_layout.yml \ -o weights=output/picodet_lcnet_x2_5_layout/best_model-c:指定模型配置文件;--slim_config:指定蒸馏策略配置文件;-o weights:指定蒸馏算法训练好的模型路径。
6.2 测试版面分析结果
预测使用的配置文件必须与训练一致。使用 PaddleDetection 训练好的模型进行预测:
python3 tools/infer.py \ -c configs/picodet/legacy_model/application/layout_analysis/picodet_lcnet_x1_0_layout.yml \ -o weights='output/picodet_lcnet_x1_0_layout/best_model.pdparams' \ --infer_img='docs/images/layout.jpg' \ --output_dir=output_dir/ \ --draw_threshold=0.5--infer_img:推理单张图片,也可以通过--infer_dir推理目录中的所有图片;--output_dir:指定可视化结果保存路径;--draw_threshold:指定绘制结果框的 NMS 阈值。
若使用官方提供的预训练模型或 FGD 蒸馏训练模型进行预测,更换weights路径并增加--slim_config即可。预测完成后,会生成类似下图的版面分析可视化结果——每个区域被绘制为不同颜色的框,并标注其类别名称与置信度:
7. 模型导出与推理
7.1 模型导出
这里需要区分两类模型文件:
- checkpoints 模型:训练过程中保存的模型,只保存模型参数,多用于恢复训练;
- inference 模型(
paddle.jit.save保存的模型):把模型结构和模型参数一并固化到文件中的模型,在预测部署、加速推理上性能优越,灵活方便,适合实际系统集成。
版面分析模型转 inference 模型的步骤如下:
python3 tools/export_model.py \ -c configs/picodet/legacy_model/application/layout_analysis/picodet_lcnet_x1_0_layout.yml \ -o weights=output/picodet_lcnet_x1_0_layout/best_model \ --output_dir=output_inference/- 如无需导出后处理,请指定:
-o export.benchmark=True(如果-o已出现过,此处删除-o); - 如无需导出 NMS,请指定:
-o export.nms=False。
转换成功后,目录下会出现三个文件:
output_inference/picodet_lcnet_x1_0_layout/ ├── model.pdiparams # inference 模型的参数文件 ├── model.pdiparams.info # inference 模型的参数信息,可忽略 └── model.pdmodel # inference 模型的模型结构文件若使用官方提供的预训练模型或 FGD 蒸馏训练的模型导出,同样更换weights路径并增加--slim_config:
python3 tools/export_model.py \ -c configs/picodet/legacy_model/application/layout_analysis/picodet_lcnet_x1_0_layout.yml \ --slim_config configs/picodet/legacy_model/application/layout_analysis/picodet_lcnet_x2_5_layout.yml \ -o weights=./output/picodet_lcnet_x2_5_layout/best_model \ --output_dir=output_inference/7.2 模型推理
使用导出的推理模型进行推理,model_dir指向推理模型目录,--device指定 GPU 或 CPU 设备:
python3 deploy/python/infer.py \ --model_dir=output_inference/picodet_lcnet_x1_0_layout/ \ --image_file=docs/images/layout.jpg \ --device=CPU推理完成后,会输出以下日志:
------------------------------------------ ----------- Model Configuration ----------- Model Arch: PicoDet Transform Order: --transform op: Resize --transform op: NormalizeImage --transform op: Permute --transform op: PadStride -------------------------------------------- class_id:0, confidence:0.9921, left_top:[20.18,35.66],right_bottom:[341.58,600.99] class_id:0, confidence:0.9914, left_top:[19.77,611.42],right_bottom:[341.48,901.82] class_id:0, confidence:0.9904, left_top:[369.36,375.10],right_bottom:[691.29,600.59] class_id:0, confidence:0.9835, left_top:[369.60,608.60],right_bottom:[691.38,736.72] class_id:0, confidence:0.9830, left_top:[369.58,805.38],right_bottom:[690.97,901.80] class_id:0, confidence:0.9716, left_top:[383.68,271.44],right_bottom:[688.93,335.39] class_id:0, confidence:0.9452, left_top:[370.82,34.48],right_bottom:[688.10,63.54] class_id:1, confidence:0.8712, left_top:[370.84,771.03],right_bottom:[519.30,789.13] class_id:3, confidence:0.9856, left_top:[371.28,67.85],right_bottom:[685.73,267.72] save result to: output/layout.jpg Test iter 0 ------------------ Inference Time Info ---------------------- total_time(ms): 2196.0, img_num: 1 average latency time(ms): 2196.00, QPS: 0.455373 preprocess_time(ms): 2172.50, inference_time(ms): 11.90, postprocess_time(ms): 11.60日志字段含义:
- Model:模型结构(此处为 PicoDet);
- Transform Order:预处理操作链(Resize → NormalizeImage → Permute → PadStride);
- class_id、confidence、left_top、right_bottom:分别表示类别 id、置信度、左上角坐标、右下角坐标;
- save result to:可视化版面分析结果保存路径,默认保存到
./output文件夹; - Inference Time Info:推理耗时,其中
preprocess_time表示预处理耗时,inference_time表示模型预测耗时,postprocess_time表示后处理耗时。
从示例日志可以看到,纯模型推理(inference_time)仅 11.90ms,说明导出后的 PicoDet 推理模型具备很高的实时性,适合作为文档解析流水线中的前置检测组件。
8. 与 PP-Structure 流水线的衔接
训练并导出的版面分析模型可以无缝接入 PP-Structure 的文档结构化流水线。在 ppstructure/utility.py 中定义了布局相关参数,例如:
--layout_model_dir:版面分析模型推理模型路径;--layout_dict_path:版面分析模型字典路径(默认指向 layout_publaynet_dict.txt);--layout_score_threshold:得分阈值,默认 0.5,过滤置信度低于该值的候选框;--layout_nms_threshold:NMS 阈值,默认 0.5,控制重叠框的抑制强度。
这些参数与 predict_layout.py 中的LayoutPredictor后处理逻辑直接对应:PicoDetPostProcess(picodet_postprocess.py)在解码每个类别得分时使用score_threshold过滤低分框,再通过hard_nms以nms_threshold完成类内去重,最后还会基于 IoU containment 对同时命中多个类别的重叠框做一次合并(优先保留 table 类别)。
在PPStructure完整流水线中,版面分析输出的区域类型会分流到不同处理分支:Text/Title 等区域交给 OCR 识别,Table 区域交给表格结构识别,从而完成"版面分析 → OCR / 表格识别 → 版面恢复"的完整文档解析。更详细的 whl 包调用方式与参数说明可参见 quick_start.en.md。
9. 引用
@inproceedings{zhong2019publaynet, title={PubLayNet: largest dataset ever for document layout analysis}, author={Zhong, Xu and Tang, Jianbin and Yepes, Antonio Jimeno}, booktitle={2019 International Conference on Document Analysis and Recognition (ICDAR)}, year={2019}, volume={}, number={}, pages={1015-1022}, doi={10.1109/ICDAR.2019.00166}, ISSN={1520-5363}, month={Sep.}, organization={IEEE} } @inproceedings{yang2022focal, title={Focal and global knowledge distillation for detectors}, author={Yang, Zhendong and Li, Zhe and Jiang, Xiaohu and Gong, Yuan and Yuan, Zehuan and Zhao, Danpei and Yuan, Chun}, booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, pages={4643--4652}, year={2022} }【免费下载链接】PaddleOCRTurn any PDF or image document into structured data for your AI. A powerful, lightweight OCR toolkit that bridges the gap between images/PDFs and LLMs. Supports 100+ languages.项目地址: https://gitcode.com/GitHub_Trending/pa/PaddleOCR
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考