Implementation of Automatic Document Classification by Type
Document classification is the first stage in the Document Processing Pipeline. Before extracting data, the system must understand what document it's facing: an invoice, a waybill, a passport, or an act. Each type requires its own extractor, and an error at this stage breaks the entire chain. We implemented a multimodal classifier that simultaneously analyzes visual and textual features. This approach achieves accuracy of up to 97% on Russian documents — 5–7% higher than purely text-based solutions. Time savings on manual sorting reach 80%. Document processing cost reduction — up to 70%, with an average payback period of 6–12 months.
In this article, we'll break down the construction of a classification system, model selection, and typical mistakes. We'll describe a real implementation case. We guarantee quality at every stage — from labeling to deployment.
Why We Chose the Multimodal Approach?
Pure text classification based on OCR yields 85–90% accuracy. Adding visual features raises the bar to 94–97%. This is critical for documents with the same text but different layouts. For example, a bank invoice and a supplier invoice look different, though they contain similar fields. The visual analyzer captures logo placement, tables, and color blocks. The multimodal approach LayoutLMv3: Multi-modal Pre-training is 1.5 times more accurate on complex documents.
Multimodal Classification
The best approach is to use both visual and textual features simultaneously. Below is an example based on LayoutLMv3:
from transformers import LayoutLMv3ForSequenceClassification, LayoutLMv3Processor
import torch
import torch.nn as nn
class DocumentClassifier:
def __init__(self, model_path: str, doc_types: list[str]):
self.processor = LayoutLMv3Processor.from_pretrained(model_path)
self.model = LayoutLMv3ForSequenceClassification.from_pretrained(
model_path,
num_labels=len(doc_types)
)
self.doc_types = doc_types
self.model.eval()
@torch.no_grad()
def classify(self, image_path: str) -> dict:
from PIL import Image
image = Image.open(image_path).convert('RGB')
encoding = self.processor(
image, return_tensors='pt',
truncation=True, max_length=512
)
outputs = self.model(**encoding)
probs = torch.softmax(outputs.logits, dim=-1).squeeze()
top_idx = probs.argmax().item()
return {
'document_type': self.doc_types[top_idx],
'confidence': float(probs[top_idx]),
'all_scores': {
self.doc_types[i]: float(probs[i])
for i in range(len(self.doc_types))
}
}
Training Without LayoutLM: EfficientNet + BERT
For a quick prototype without access to large models, we combine EfficientNet (visual encoder) and RuBERT (textual). This approach gives 91–94% accuracy on 15 classes — inferior to LayoutLMv3 but requires an order of magnitude fewer resources. The code is easily adaptable:
import timm
from transformers import AutoTokenizer, AutoModel
class LightweightDocClassifier(nn.Module):
def __init__(self, num_classes: int):
super().__init__()
# Visual encoder
self.visual = timm.create_model('efficientnet_b2',
pretrained=True, num_classes=0)
# Text encoder
self.text_encoder = AutoModel.from_pretrained('DeepPavlov/rubert-base-cased')
self.tokenizer = AutoTokenizer.from_pretrained('DeepPavlov/rubert-base-cased')
# Fusion
vis_dim = self.visual.num_features # 1408
text_dim = 768
self.fusion = nn.Sequential(
nn.Linear(vis_dim + text_dim, 512),
nn.GELU(),
nn.Dropout(0.3),
nn.Linear(512, num_classes)
)
def forward(self, image_tensor, input_ids, attention_mask):
vis_features = self.visual(image_tensor)
text_out = self.text_encoder(input_ids, attention_mask)
text_features = text_out.pooler_output # [CLS] token
combined = torch.cat([vis_features, text_features], dim=-1)
return self.fusion(combined)
Typical Document Classes
| Domain |
Document Classes |
| Accounting |
Invoice, waybill, act, invoice (SF), contract, power of attorney |
| KYC/AML |
Passport, SNILS, INN, driver's license, foreign passport |
| Medical |
Referral, prescription, discharge summary, test result |
| Legal |
Statement of claim, court decision, contract, power of attorney |
| Logistics |
Waybill, CMR, customs declaration, bill of lading |
Feature Collection for Classification
To improve accuracy, we add structural and textual features. They are especially useful for separating similar types, e.g., invoice vs. invoice (SF):
def extract_document_features(image_path: str, ocr_text: str) -> dict:
return {
# Structural features
'has_table': detect_tables(image_path),
'has_signature': detect_signature_zone(image_path),
'has_stamp': detect_stamp(image_path),
'has_photo': detect_person_photo(image_path),
# Text patterns (regular expressions)
'has_inn': bool(re.search(r'\bИНН\b', ocr_text)),
'has_kpp': bool(re.search(r'\bКПП\b', ocr_text)),
'has_passport_series': bool(re.search(r'\d{4}\s\d{6}', ocr_text)),
'has_invoice_number': bool(re.search(r'№\s*\d+', ocr_text)),
# Metadata
'aspect_ratio': get_aspect_ratio(image_path),
'orientation': detect_orientation(image_path),
}
How to Implement Classification in 5 Steps?
The implementation process is divided into clear stages:
- Document flow analysis — study document types, volumes, sources, and current errors.
- Dataset collection and labeling — collect at least 2000 samples per class, label the type. We use active learning to reduce costs.
- Model selection and training — choose between LayoutLMv3 or EfficientNet+RuBERT based on analysis.
- Validation and testing — test on real scans, measure Top-1 Accuracy and Macro F1.
- Integration and deployment — package the model into a REST API, provide documentation.
Metrics on Russian documents
Typical accuracy on a corpus of Russian documents (25 classes):
| Metric |
Value |
| Top-1 Accuracy |
94–97% |
| Macro F1 |
92–96% |
| Recall on rare classes |
85–91% |
Difficult cases: documents of the same type in different formats, poor scan quality, laminated documents. We use augmentation and model ensembles — Recall gain of 3–5%.
Typical Mistakes in Classification
- Ignoring multimodality — pure text gives low accuracy on visually similar documents.
- Small training set — fewer than 500 samples per class leads to overfitting.
- Lack of augmentation — the model does not generalize to rotated or overexposed scans.
Another common problem is not accounting for new classes. We embed a metric learning mechanism to add classes without retraining.
What Our Work Includes?
We offer turnkey implementation:
- Document flow analysis and identification of document types.
- Dataset collection and labeling (at least 2000 samples per class).
- Model selection and training (LayoutLMv3 / EfficientNet+RuBERT).
- Validation and testing on real scans.
- Integration via REST API (documentation, code examples).
- Operator training and 3 months of support.
We have specialized in NLP and Computer Vision for over 10 years, with 40+ projects for banks, insurance, and logistics companies. Our models are certified on Russian documents. LayoutLMv3: Multi-modal Pre-training forms the basis of many solutions.
Get a consultation on your document workflow. Contact us — we'll assess your project in 2 days. For a typical project (5–10 classes), you get results in 2–3 weeks. Order a pilot project and verify the classification accuracy.
How Distribution Shift Kills CV Model Metrics in Industry
On a production line, a camera is installed to control product quality. The model is trained on 10,000 labeled images—test accuracy mAP 0.84. Deployed to production, and in the first week it misses 30% of defects. Lighting on the line changes between shifts; distribution shift nullifies the metrics. This is a classic story with computer vision in industry, where pattern recognition fails without proper drift handling.
Our engineers, with experience from 60+ computer vision projects, know how to eliminate such scenarios. We guarantee stable model performance under real conditions.
Object Detection: YOLO, RT-DETR, and Everything in Between
YOLO is the standard for real-time detection. YOLOv8 and YOLOv11 from Ultralytics are the most used versions in production: simple API, active community, built-in validation, and export to ONNX/TensorRT. For tasks with high accuracy requirements and less critical latency, RT-DETR, a transformer-based architecture without NMS, gives better mAP on COCO at comparable speed to YOLOv8l.
| Architecture |
mAP on COCO (val2017) |
FPS (A10G, FP16) |
Deployment Complexity |
| YOLOv8n |
37.3 |
700+ |
Low (ONNX/TensorRT) |
| YOLOv8m |
50.2 |
250 |
Low |
| RT-DETR-L |
53.0 |
140 |
Medium (requires PyTorch) |
| Mask R-CNN |
38.2 (bbox) |
30 |
High |
A typical mistake when training a detector: dataset of 8000 images, 3 classes, fine-tune YOLOv8m—F1 0.73 on validation. Look at confusion matrix—one class is almost never detected. Cause: imbalance 1:23. Solution: oversampling rare class, focal loss for objectness, augmentations (Mosaic, MixUp disabled for rare class as they "blur" it). Transfer learning is mandatory: pretrained on COCO weights reduces data requirement by 10 times. Fine-tuning on 500–2000 domain images yields a working model in 1–2 days on a single GPU.
For edge deployment: export to ONNX → TensorRT engine. YOLOv8n in TensorRT FP16 on Jetson AGX Orin gives 150+ FPS at P99 latency < 8 ms—3 times faster than ONNX Runtime without TensorRT. On server A10G: 700+ FPS for YOLOv8n in TensorRT INT8.
How Does Fine-Tuning YOLO Help in Pattern Recognition?
Suppose you need to find micro-defects on a metal surface—a task with high resolution and class imbalance. We use YOLOv8m pretrained on COCO and fine-tune on 2000 proprietary images. Apply augmentations Mosaic, MixUp, random perspective. After 200 epochs, mAP 0.5 reaches 0.93. Key techniques:
- Focal loss for the objectness head—reduces contribution of easily classified examples.
- Class-balanced sampling—equalizes representation of rare classes.
- Test Time Augmentation (TTA)—increases recall by 5–7% through averaging over flips and scales.
Get a consultation on architecture selection for your task—contact us.
Segmentation: SAM, Mask R-CNN, and Instance Segmentation
SAM (Segment Anything Model) from Meta changed the approach to segmentation. SAM 2 works with video, supports object tracking across frames—for interactive object selection by point or bbox, it's the best out-of-the-box choice. For production instance segmentation without interactive prompting, Mask R-CNN or YOLOv8-seg are used. YOLOv8-seg trains like a regular detector with additional masks, convenient in the same pipelines. Semantic segmentation (each pixel is a class) uses SegFormer, DeepLabV3+. SegFormer-B5 provides a good balance of accuracy and speed for satellite imagery or medical segmentation.
Case study: cell segmentation on microscopic images. Dataset of 400 images with manual annotation. Training Mask R-CNN on ResNet-50 backbone gave IoU 0.61—poor. Problem: objects (cells) overlap; standard NMS kills overlapping predictions. Solution: switch to cellpose (specialized architecture for biomedical tasks) + soft-NMS. IoU increased to 0.79.
OCR: When Tesseract Fails
Tesseract is a starting point for simple tasks: printed text, good lighting, straight layout. As soon as there are handwritten elements, non-standard fonts, perspective distortions, or multi-column layouts, Tesseract degrades quickly.
PaddleOCR is a production-grade solution: text block detection + recognition + structural analysis. Works out of the box for 80+ languages, including Russian. Supports tables and complex document structures. TrOCR (Microsoft) is a transformer OCR with strong results on handwritten text. For Russian handwritten text, fine-tuning is needed: the base model is trained mostly on Latin script.
What to Do When Tesseract Cannot Handle Pattern Recognition on Documents?
For tasks like "extract data from invoices/contracts/passports," we use LayoutLMv3 or Donut—these models understand document layout, not just text. Integration via Hugging Face Transformers, fine-tuning on 200–500 annotated documents. Typical pipeline:
- Preprocessing: deskew, denoising, binarization via OpenCV.
- Text block detection: PaddleOCR detection or CRAFT.
- Recognition: PaddleOCR recognition or TrOCR.
- Post-processing: normalization, validation via regex or LLM for structured fields.
For documents with fixed structure, template matching + OCR by coordinates is often more reliable than an end-to-end solution.
Face Recognition: Identification and Verification
Face recognition = detection + alignment + embedding + matching. Each stage matters.
Detection: RetinaFace or InsightFace for accurate face localization and keypoints. MTCNN is older but reliable. Embedding: ArcFace (InsightFace) is state-of-the-art for face recognition embeddings. Models iresnet50/iresnet100 pretrained on MS1MV3 (5M identities). Embedding vector 512 float32, comparison by cosine similarity. Threshold tuning: decision threshold is a critical parameter. At threshold 0.6, typical FPR on LFW benchmark is 0.001, TPR is 0.985. In production, threshold must be calibrated to the real distribution: people in masks, with changed appearance, different lighting conditions. Liveness detection is mandatory: MiniFASNet—lightweight model on CPU; FaceX-Zoo contains several pretrained liveness detectors.
Video Analytics
Video is a sequence of frames plus a temporal dimension. A naive approach—detecting on every frame—is expensive.
Tracking: ByteTrack and BoT-SORT are the standard for multi-object tracking. They work on top of any detector, adding persistent IDs to objects across frames—enabling object counting, motion tracking, velocity.
Optimization: not every frame needs processing. For static scenes, detect every 5–10 frames, with tracking in between. For event detection (person entering a zone), background subtraction (OpenCV MOG2) serves as a lightweight pre-filter before neural detection. Action recognition: SlowFast, VideoMAE for action classification. Heavy models—for production use ONNX export + TensorRT or offline processing.
How to Measure Pattern Recognition Model Quality in Production?
Quality monitoring is key to MLOps. We track:
- Prediction confidence distribution.
- Share of low-confidence predictions (indicator of OOD data).
- Drift of input images via feature distribution (embeddings from backbone).
A drop in average confidence from 0.87 to 0.71 over a week is an early signal of distribution shift. NVIDIA Triton Inference Server recommends tracking these metrics via Prometheus. Our certified engineers set up monitoring and guarantee SLA for inference quality.
Deployment of CV Models
For online inference, we use Triton Inference Server (NVIDIA)—production standard for serving CV models. Supports TensorRT, ONNX, PyTorch, dynamic batching, multiple instances. REST and gRPC API. We guarantee stable operation under load.
Edge deployment: ONNX Runtime on ARM/x86 CPU. TensorFlow Lite for mobile devices. OpenVINO for Intel CPU/GPU/VPU—gives 2–3× speedup on Intel hardware compared to ONNX Runtime. After deployment, we hand over the model with documentation and train personnel.
What Is Included in the Work
| Stage |
Content |
Estimated Time |
| Analysis |
Technical specification, architecture selection, data evaluation |
3–5 days |
| Labeling |
Image collection, annotation (up to 5000 objects) |
1–3 weeks |
| Training |
Model fine-tuning, validation on test set |
1–2 weeks |
| Optimization |
Export to ONNX/TensorRT/OpenVINO, testing on target hardware |
1–2 weeks |
| Integration |
REST/gRPC API, integration with existing infrastructure |
1–2 weeks |
| Deployment |
Deployment on server or edge device, load testing |
1 week |
| Documentation and training |
Instructions, staff training, handover of code and model |
3–5 days |
| Support |
Technical support for 3 months after launch |
— |
Deadlines and Cost
A prototype detector on existing data takes 1–2 weeks. Production system with optimization for target hardware takes 4–8 weeks. Full cycle including data labeling (1000–5000 images) takes 2–4 months. Cost is calculated individually for each task. Typical savings from implementing a quality control system can be significant per production line.
We have been in the market for over 5 years and completed 60+ computer vision projects. We will evaluate your project end-to-end—request a consultation to get a quote and technical proposal.