🚀 TrOCR-LaTeX(針對手寫數學內容微調)
TrOCR-LaTeX 能夠將手寫數學內容轉換為簡潔的 LaTeX 代碼。它是基於 microsoft/trocr-base-handwritten
微調的版本,這是一個基於 Transformer 的光學字符識別模型,經過調整後可處理手寫數學圖像和結構化數學語法。
✨ 主要特性
- 可將手寫數學內容轉換為 LaTeX 代碼。
- 基於預訓練的 Transformer 光學字符識別模型微調而來。
- 適配手寫數學圖像和結構化數學語法。
📦 安裝指南
文檔未提及具體安裝步驟,故跳過此章節。
💻 使用示例
基礎用法
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
from PIL import Image
def open_PIL_image(image_path: str) -> Image.Image:
image = Image.open(image_path)
if image_path.split('.')[-1].lower() == 'png':
image = Image.composite(image, PIL.Image.new('RGB', image.size, 'white'), image)
return image
processor = TrOCRProcessor.from_pretrained('tjoab/latex_finetuned')
model = VisionEncoderDecoderModel.from_pretrained('tjoab/latex_finetuned')
images = [open_PIL_image(path) for path in paths]
preproc_image = processor.image_processor(images=images, return_tensors="pt").pixel_values
pred_ids = model.generate(preproc_image, max_length=128)
latex_preds = processor.batch_decode(pred_ids, skip_special_tokens=True)
📚 詳細文檔
數據
該模型在 Google 的 MathWriting
數據集上進行了微調。該數據集包含超過 500,000 個手寫數學表達式的數字墨水,這些表達式通過手動標註或程序生成獲得。
預期用途和限制
你可以使用此模型對單個數學表達式進行 OCR。
對於非常長的表達式,性能會下降(由於圖像預處理,3:2 的寬高比似乎效果最佳)。
- 可以創建一個表達式分塊方案,將圖像分割成子圖像並分別處理,以繞過此限制。
- 為了處理多個表達式,你需要將它們分組為單個表達式。
評估
使用字符錯誤率(CER)評估性能,定義如下:
CER = (替換數 + 插入數 + 刪除數) / 真實標籤中的總字符數
-
✅ 為什麼使用 CER?
- 數學表達式對結構敏感。即使打亂一個字符也可能完全改變其含義。
- 例如
x^2
與 x_2
。
- 又如
\frac{a}{b}
與 \frac{b}{a}
。
- CER 會對語法中的小錯誤進行懲罰。
-
評估得出的 CER 為 14.9%。
BibTeX 和引用
原始的 TrORC 模型在以下論文中提出:
TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models 作者:Li 等人。
你可以在 他們的倉庫 中找到源代碼。
@misc{li2021trocr,
title={TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models},
author={Minghao Li and Tengchao Lv and Lei Cui and Yijuan Lu and Dinei Florencio and Cha Zhang and Zhoujun Li and Furu Wei},
year={2021},
eprint={2109.10282},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
🔧 技術細節
- 小批量大小:8
- 優化器:Adam
- 學習率調度器:餘弦
fp16
混合精度
- 使用
torch.cuda.amp
進行自動混合精度(AMP)訓練,以減少內存使用。
- 梯度累積
- 用於模擬更大的有效批量大小,同時保持每步的內存消耗較低。
- 每 8 個小批量進行一次優化器更新。