關(guān)鍵信息抽取【2】——體驗篇
基本原理可以先看下文
Damon,公眾號:人工智障與神經(jīng)病網(wǎng)絡(luò)研究所關(guān)鍵信息抽取【1】——初識篇
1. 環(huán)境準(zhǔn)備
- Python版本:3.10.12
- 硬件:win11,CPU
# 構(gòu)建Conda虛擬環(huán)境
conda create --name py310_paddle python=3.10.12
# 激活虛擬環(huán)境
conda activate py310_paddle
# 準(zhǔn)備paddlepaddle
python -m pip install paddlepaddle==2.5.2 -i https://pypi.tuna.tsinghua.edu.cn/simple
# 準(zhǔn)備PaddleOCR和PP-Structure環(huán)境
git clone https://github.com/PaddlePaddle/PaddleOCR.git
cd PaddleOCR
pip install -r requirements.txt
pip install -r ppstructure/kie/requirements.txt
pip install paddleocr -U
2. 下載預(yù)訓(xùn)練模型文件
在./PaddleOCR/ppstructure下,創(chuàng)建一個weights文件夾,
cd PaddleOCR/ppstructure
mkdir weights
cd weights
# 下載并解壓SER預(yù)訓(xùn)練模型
wget https://paddleocr.bj.bcebos.com/ppstructure/models/vi_layoutxlm/ser_vi_layoutxlm_xfund_pretrained.tar && tar -xf ser_vi_layoutxlm_xfund_pretrained.tar
# 下載并解壓RE預(yù)訓(xùn)練模型
wget https://paddleocr.bj.bcebos.com/ppstructure/models/vi_layoutxlm/re_vi_layoutxlm_xfund_pretrained.tar && tar -xf re_vi_layoutxlm_xfund_pretrained.tar
3. 基于動態(tài)圖預(yù)測(CPU)
- 更改一下
configs/kie/vi_layoutxlm中ser_vi_layoutxlm_xfund_zh.yml和re_vi_layoutxlm_xfund_zh.yml文件中,use_gpu參數(shù)改成False。
- 由于使用
XFUND數(shù)據(jù)集的預(yù)訓(xùn)練模型,因此需要用到一個類別列表文件;如果不想下載原始數(shù)據(jù),可以在PaddleOCR根目錄下新建train_data/XFUND/class_list_xfun.txt文件
class_list_xfun.txt文件內(nèi)容如下,
3.1 僅預(yù)測SER模型
cd PaddleOCR
python tools/infer_kie_token_ser.py -c configs/kie/vi_layoutxlm/ser_vi_layoutxlm_xfund_zh.yml -o Architecture.Backbone.checkpoints=ppstructure/weights/ser_vi_layoutxlm_xfund_pretrained/best_accuracy Global.infer_img=ppstructure/docs/kie/input/zh_val_0.jpg
3.2 SER + RE模型串聯(lián)
cd PaddleOCR
python tools/infer_kie_token_ser_re.py -c configs/kie/vi_layoutxlm/re_vi_layoutxlm_xfund_zh.yml -o Architecture.Backbone.checkpoints=ppstructure/weights/re_vi_layoutxlm_xfund_pretrained/best_accuracy Global.infer_img=ppstructure/docs/kie/input/zh_val_42.jpg -c_ser configs/kie/vi_layoutxlm/ser_vi_layoutxlm_xfund_zh.yml -o_ser Architecture.Backbone.checkpoints=ppstructure/weights/ser_vi_layoutxlm_xfund_pretrained/best_accuracy
- 踩坑 1:ValueError: (InvalidArgument) Currently, Tensor.indices() only allows indexing by Integers, Slices, Ellipsis, None, tuples of these types and list of Bool and Integers, but received bool in 1th slice item (at ..\paddle/fluid/pybind/slice_utils.h:298)
解決:pip install paddlenlp==2.5.2
4. 基于PaddleInference的預(yù)測(CPU)
4.1 SER和RE的推理模型下載
cd PaddleOCR/ppstructure
mkdir weights
cd weights
wget https://paddleocr.bj.bcebos.com/ppstructure/models/vi_layoutxlm/ser_vi_layoutxlm_xfund_infer.tar && tar -xf ser_vi_layoutxlm_xfund_infer.tar
wget https://paddleocr.bj.bcebos.com/ppstructure/models/vi_layoutxlm/re_vi_layoutxlm_xfund_infer.tar && tar -xf re_vi_layoutxlm_xfund_infer.tar
4.2 SER推理
cd ppstructure
python kie/predict_kie_token_ser.py --kie_algorithm=LayoutXLM --ser_model_dir=./weights/ser_vi_layoutxlm_xfund_infer --image_dir=./test_data/Property_Ownership_Certificate_1a89c71b554eaea39b547254a6b092cd_0.jpg --ser_dict_path=../train_data/XFUND/class_list_xfun.txt --vis_font_path=../doc/fonts/simfang.ttf --ocr_order_method="tb-yx"
4.3 SER+RE串聯(lián)推理
cd ppstructure
python kie/predict_kie_token_ser_re.py --kie_algorithm=LayoutXLM --re_model_dir=./weights/re_vi_layoutxlm_xfund_infer --ser_model_dir=./weights/ser_vi_layoutxlm_xfund_infer --use_visual_backbone=False --image_dir=./test_data/Property_Ownership_Certificate_bcefeb2c0e442e165554c7b381b1e024_0.jpg --ser_dict_path=../train_data/XFUND/class_list_xfun.txt --vis_font_path=../doc/fonts/simfang.ttf --ocr_order_method="tb-yx"
5. 模型查看
在PaddleOCR根目錄下,
from typing import Dict
from tools.program import load_config
# 導(dǎo)入關(guān)系抽取(RE)默認(rèn)配置re_configs
re_configs:Dict = load_config("configs/kie/vi_layoutxlm/re_vi_layoutxlm_xfund_zh.yml")
# 導(dǎo)入語義實體識別(SER)默認(rèn)配置ser_configs
ser_configs:Dict = load_config("configs/kie/vi_layoutxlm/ser_vi_layoutxlm_xfund_zh.yml")
# 修改配置,包括當(dāng)前預(yù)訓(xùn)練模型路徑
re_configs['Architecture']['Backbone']['checkpoints'] = 'ppstructure/weights/re_vi_layoutxlm_xfund_pretrained/best_accuracy'
ser_configs['Architecture']['Backbone']['checkpoints'] = 'ppstructure/weights/ser_vi_layoutxlm_xfund_pretrained/best_accuracy'
# 構(gòu)建模型
import copy
import importlib
from ppocr.modeling.architectures import BaseModel
def build_model(config):
# 創(chuàng)建了config的一個深拷貝。深拷貝意味著原始的config字典及其嵌套的字典都會被復(fù)制,
# 這樣在函數(shù)中對config的修改不會影響到外部的原始config對象
config = copy.deepcopy(config)
if not "name" in config:
arch = BaseModel(config)
else:
name = config.pop("name")
# 動態(tài)地導(dǎo)入當(dāng)前模塊(即包含build_model函數(shù)的模塊)
mod = importlib.import_module(__name__)
arch = getattr(mod, name)(config)
return arch
re_model = build_model(re_configs['Architecture'])
# print(re_model) # 查看re模型結(jié)構(gòu)
# re_model的骨架網(wǎng)絡(luò)為LayoutXLMForRe類 -> ppocr/modeling/backbones/vqa_layoutlm.py::line 208
ser_model = build_model(ser_configs['Architecture'])
# print(ser_model) # 查看ser模型結(jié)構(gòu)
# ser_model的骨架網(wǎng)絡(luò)為LayoutXLMForSer類 -> ppocr/modeling/backbones/vqa_layoutlm.py::line 142
5.1 RE模型結(jié)構(gòu)解讀
RE是一個基于LayoutXLM的模型,包括4個模塊:
- 嵌入層(LayoutXLMEmbeddings),包括幾種嵌入:
-
單詞嵌入: 將詞匯映射到768維的向量空間。 -
位置嵌入: 為了保留單詞的位置信息,使用位置嵌入,也是768維的。 -
視覺位置嵌入(x/y/h/w_position_embeddings): 分別為文檔中的視覺元素(如圖像塊或文本塊)的x坐標(biāo)、y坐標(biāo)、高度和寬度提供128維的嵌入表示。 -
類型嵌入(token_type_embeddings): 用于區(qū)分不同類型的標(biāo)記(例如區(qū)分單詞和視覺特征)。
- 自注意力機(jī)制 (LayoutXLMAttention): 用于捕捉序列內(nèi)不同元素之間的依賴關(guān)系,允許模型在處理一個元素時考慮序列中的其他元素,這對理解文本和視覺上下文非常重要。
- 前饋網(wǎng)絡(luò) (LayoutXLMIntermediate和LayoutXLMOutput): 對自注意力的輸出進(jìn)行進(jìn)一步的處理和轉(zhuǎn)換,包含線性變換和激活函數(shù)的網(wǎng)絡(luò)。
模塊之間的關(guān)系如下:
嵌入層首先將輸入文本和視覺信息轉(zhuǎn)換為嵌入向量。編碼器接收嵌入向量,并通過一系列的層來提取高級特征。池化層從編碼器的輸出中提取特征,以得到適合分類任務(wù)的表示。分類器使用池化層的輸出來預(yù)測最終的類別。
5.2 SER模型結(jié)構(gòu)解讀
- BaseModel: 這是模型的最外層,它包含了整個模型的架構(gòu)。
- backbone (LayoutXLMForSer): 這是模型的主干網(wǎng)絡(luò),負(fù)責(zé)特征提取的重要部分。
- model (LayoutXLMForTokenClassification): 這個子模塊是針對標(biāo)記分類任務(wù)定制的,它使用主干網(wǎng)絡(luò)輸出的特征來執(zhí)行分類。
- layoutxlm (LayoutXLMModel): 這是實現(xiàn)LayoutXLM模型架構(gòu)的核心模塊,它包含以下組件:
- (1) attention (LayoutXLMAttention): 使用自注意力機(jī)制來捕獲輸入序列內(nèi)不同元素之間的關(guān)系。
- (2) intermediate 和 output: 一個兩階段的前饋神經(jīng)網(wǎng)絡(luò),包括密集連接和規(guī)范化。
- (1) word_embeddings: 將文本輸入的單詞轉(zhuǎn)換為固定大小的向量。
- (2) position_embeddings: 提供單詞在序列中的位置信息。
- (3) x/y/h/w_position_embeddings: 提供文檔圖像中對象的位置(x坐標(biāo)和y坐標(biāo))和尺寸(高度h和寬度w)信息。
- (4) token_type_embeddings: 提供不同類型標(biāo)記的嵌入。
- (5) LayerNorm 和 dropout: 用于嵌入向量的規(guī)范化和正則化。
- 4.1 embeddings (LayoutXLMEmbeddings): 該模塊負(fù)責(zé)將輸入的文本和視覺特征轉(zhuǎn)換為嵌入向量,其中又包括以下細(xì)分的模型層:
- 4.2 encoder (LayoutXLMEncoder): 包括多個LayoutXLMLayer層,每個層都包含以下組件:
- 4.3 pooler (LayoutXLMPooler): 對編碼器的輸出進(jìn)行池化,通常用于提取分類任務(wù)所需的特征。
模塊之間的關(guān)系可以描述為以下流程:
- 輸入數(shù)據(jù)首先通過embeddings模塊,轉(zhuǎn)換成嵌入向量。
- 嵌入向量被傳遞到encoder模塊,進(jìn)行深層特征提取。
- encoder的輸出被pooler處理,以提取適合分類的特征。
- dropout層應(yīng)用于這些特征,以提供正則化。
- classifier層使用這些特征來預(yù)測每個標(biāo)記的分類。
備注
- LayoutXLMForRelationExtraction類 -> paddlenlp/transformers/layoutxlm/modeling.py::line 1265
- LayoutXLMModel類 -> paddlenlp/transformers/layoutxlm/modeling.py::line 598
評論
圖片
表情
