🚀 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 个小批量进行一次优化器更新。