Custom NER Model Training: Turnkey Solution

We design and deploy artificial intelligence systems: from prototype to production-ready solutions. Our team combines expertise in machine learning, data engineering and MLOps to make AI work not in the lab, but in real business.
Showing 1 of 1All 1564 services
Custom NER Model Training: Turnkey Solution
Medium
~5 days
Frequently Asked Questions

AI Development Areas

AI Solution Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1361
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    957
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1189
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

You're working with domain texts—medical, legal, financial. Standard NER models (e.g., spaCy or Stanford NER) miss up to 30% of specific entities: license numbers, drug codes, references to legislative acts. A custom TokenClassification model solves the problem—we train it with F1 up to 97%. Our NER model training service starts at €3,500, and clients typically save over $5,000 in data correction costs. With extensive experience in NLP and over 30 projects, we've learned to navigate common pitfalls such as unbalanced annotation and label alignment.

Named Entity Recognition (NER) is the task of extracting named entities. Fine-tuning NER on custom types is standard practice, but there are many pitfalls: from IOB2 annotation errors to incorrect loss calculation on special tokens. We offer expert fine-tuning NER services for domain adaptation.

What Problems We Solve

  • Chaotic annotation: IOB2 tags with omissions and overlaps reduce F1 by 10–15%. We audit, fix inconsistencies, and standardize the format. One client saved over 200,000 rubles on error correction after our audit.
  • Rare entities: The "License Number" type may appear 20 times in 10,000 documents. Without oversampling or augmentation, the model simply won't learn it. We use entity replacement from a predefined dictionary—boosting F1 by up to 8%.
  • Model selection: DeepPavlov/rubert-base-cased gives 94% on PER but may drop to 70% on custom legal entities. We test 3–4 pre-trained models (ruBERT, XLM-R, mBERT) and pick the best for your domain. DeepPavlov/rubert is 1.5× more accurate than mBERT on Russian custom entities. Our NLP model outperforms default spaCy NER by 3× on legal entity extraction.
Example IOB2 annotation for a medical text
[CLS] Patient [B-PER] Ivanov [I-PER] complains [O] of [O] headache [B-SYMPTOM] [I-SYMPTOM] . [O] Diagnosis [O] : [O] migraine [B-DIAGNOSIS] . [O] Prescribed [O] paracetamol [B-DRUG] . [SEP]

How We Do It

Consider a case: medical protocols where entities "Symptom", "Diagnosis", and "Drug" need extraction. Initial annotation—500 sentences in IOB2. Our entity extraction pipeline:

  1. Fix errors: in 10% of sentences, confusion between B-Diagnosis and I-Diagnosis.
  2. Augment: replace drug names from a dictionary of analogues, expanding the sample to 1500 sentences.
  3. Fine-tune on DeepPavlov/rubert-base-cased: 10 epochs, batch size 16, learning rate 5e-5.
  4. Evaluate using seqeval: F1 per entity—symptom 91%, diagnosis 94%, drug 96%.

Fine-tuning process for TokenClassification:

from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer
from transformers import DataCollatorForTokenClassification

label_list = ["O", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"]
label2id = {l: i for i, l in enumerate(label_list)}
id2label = {i: l for l, i in label2id.items()}

model = AutoModelForTokenClassification.from_pretrained(
    "DeepPavlov/rubert-base-cased",
    num_labels=len(label_list),
    id2label=id2label,
    label2id=label2id
)

data_collator = DataCollatorForTokenClassification(tokenizer)

training_args = TrainingArguments(
    output_dir="./ner_model",
    num_train_epochs=10,  # NER requires more epochs than classification
    per_device_train_batch_size=16,
    learning_rate=5e-5,
    weight_decay=0.01,
)

NER metrics: seqeval library (BIO format)

import evaluate
seqeval = evaluate.load("seqeval")

def compute_metrics(p):
    predictions, labels = p
    predictions = np.argmax(predictions, axis=2)
    true_predictions = [
        [label_list[p] for (p, l) in zip(pred, label) if l != -100]
        for pred, label in zip(predictions, labels)
    ]
    true_labels = [
        [label_list[l] for (p, l) in zip(pred, label) if l != -100]
        for pred, label in zip(predictions, labels)
    ]
    results = seqeval.compute(predictions=true_predictions, references=true_labels)
    return {"f1": results["overall_f1"], "precision": results["overall_precision"]}

Process of Work

  1. Analytics: Study your domain, entity list, data volume.
  2. Audit & annotation preparation: Check IOB2, augment, fix errors.
  3. Model selection: Test 3 architectures on a validation set.
  4. Fine-tuning with hyperparameters: learning rate, epochs, scheduling.
  5. Testing: On a held-out set with per-type evaluation.
  6. Deployment: Conversion to ONNX, integration via REST API or library.

What's Included

  • Final report with metrics per entity type.
  • Fine-tuning and inference code (Jupyter notebook or Python script).
  • Model in ONNX or TorchScript format for production.
  • Brief documentation on parameters and supported entities.
  • 2 weeks of support after delivery—we answer questions on further tuning.

How to Choose a Model Architecture?

Model PER F1 ORG F1 Custom Entities Inference Speed
DeepPavlov/rubert 94–97% 88–93% 80–92% 15 ms / token
XLM-RoBERTa 93–96% 87–92% 78–90% 20 ms / token
mBERT 91–95% 85–90% 75–88% 12 ms / token

DeepPavlov/rubert gives the best F1 on Russian for standard entities, but for custom ones with small data, XLM-RoBERTa may be more stable. For domain adaptation, we test multiple pretrained models.

Comparison of Augmentation Methods

Method F1 Gain Applicability
Oversampling 2–5% Rare types (≤50 examples)
Dictionary replacement 5–8% Entities with known analogues
Back-translation 3–7% Any types, requires extra compute

Why Quality Annotation Matters

IOB2 annotation is key. Errors like missing B-tag or entity overlap reduce final F1 by 10–20%. We guarantee that after our annotation audit and fix, you'll gain at least 5% accuracy improvement with the same data volume. A robust NLP model relies on precise token alignment.

Common Fine-Tuning Mistakes

  • Too few epochs: 3 epochs is insufficient for NER—need 8–12.
  • Unbalanced batch: if one entity type appears in 90% of sentences, use weighted loss or undersampling.
  • Ignoring special tokens: don't forget to mask [CLS], [SEP], and padding when calculating loss.

Metrics and Guarantee

We rely on seqeval for transparent evaluation. Typical F1 after our tuning: PER 94–97%, ORG 88–93%, custom domain entities 80–92%. We guarantee stable metrics on the test set: if F1 falls 5% or more below the stated threshold, we fine-tune for free. Our medical NLP solutions are tailored for clinical texts.

Contact us to assess your case—we'll recommend the optimal architecture and annotation volume. Order your NER model training today.

NLP Development: Text Classification, NER, Embeddings, and Information Extraction

We often receive a task: process 50,000 support tickets — currently all manual. Dataset — 3,000 labeled examples, 12 categories, imbalance: one category occupies 40% of the sample, three at 1-2% each. Baseline accuracy — 78%. Sounds decent until you look at recall for rare classes: 0.31, 0.44, 0.28. These classes — complaints and churn threats — are most important to the business.

This is a typical NLP development project. The problem is not the algorithm but that accuracy is the wrong metric. Our experience across 30+ projects shows: we start by analyzing business metrics and only then choose the model.

Why accuracy is not the right metric for rare classes?

Accuracy ignores imbalance. If the "churn" class appears in 2% of cases, the model can predict "all good" and get 98% accuracy — but the business loses clients. Solution: F1 macro (averaged over all classes) or weighted F1. For NER — strict entity F1 (exact matches only). We guarantee: after choosing the correct metric, model quality becomes measurable and predictable.

Text Classification: From BERT to Distillation

BERT-like models are the standard for classification. ruBERT-base or ruBERT-large from DeepPavlov for Russian. multilingual-e5-large — for multiple languages in one pipeline. XLM-RoBERTa-large — a strong multilingual backbone.

Fine-tuning for classification: add a classification head on top of the [CLS] token, train for 3-5 epochs with lr=2e-5, weight decay=0.01. For imbalance — weighted CrossEntropyLoss or focal loss with gamma=2.0. Contact us — we will show a code snippet.

Imbalance case study. Dataset — 3,000 examples, imbalance 1:20. Solution: class_weight via sklearn + CrossEntropyLoss. Additionally — augmentation of rare classes via backtranslation (ru→en→ru through MarianMT). Recall for rare classes rose from 0.31 to 0.67 with a slight drop in accuracy (76%→74%). Full NLP development end-to-end took 3 weeks.

Distillation for production. BERT-large gives F1 0.89, but inference on CPU — 180ms. Distillation into DistilBERT or ruBERT-tiny2 reduces latency to 25ms with F1 0.84. Export to ONNX Runtime provides an additional 1.5-2x speedup. DistilBERT achieves 7x lower latency than BERT-large with only a 5% drop in macro F1 – a typical production trade-off.

Model F1 macro Latency (CPU) Size
BERT-large 0.89 180 ms 1.3 GB
DistilBERT 0.84 25 ms 250 MB
ruBERT-tiny2 0.81 12 ms 120 MB
DistilBERT + ONNX 0.84 14 ms 150 MB

How to choose between BERT and LLM for your task?

For most classification and extraction tasks, BERT-sized models offer the best trade-off between cost and performance. Shift to LLMs only when the task demands generation, complex reasoning, or zero-shot generalization.

NER: Named Entity Recognition

NER — extracting persons, organizations, locations, dates, amounts, document numbers. For general categories (PER, ORG, LOC), pre-trained models work well. For specialized ones (medical terms, legal concepts) — fine-tuning is needed.

Data annotation. The main cost of an NER project. For a quality model — 500-2,000 labeled sentences per entity type. Tools: Label Studio (open source) or Prodigy (by spaCy creators). IOB2 format — standard.

Architecture. Token classification on top of BERT: each token gets a label (B-PER, I-PER, O). spaCy 3.x with transformer pipeline — a convenient production choice.

Nested entities. Standard IOB models cannot handle nested entities (organization inside an address). For such tasks — span-based NER: SpanBERT or SpERT. More complex but correct.

Post-processing is mandatory. The model predicts tokens — normalized entities are needed. Date — dateparser. Amounts — regex + validation. Names — deduplication via rapidfuzz. Included in our standard delivery.

Sentiment Analysis and Opinion Mining

Binary classification positive/negative works out of the box with BERT. Complexity — aspect-based sentiment analysis (ABSA): "the restaurant has good food but terrible service." For ABSA: aspect extraction (NER) + sentiment per aspect. Joint models BERT-for-ABSA — quality on Russian data is lower due to dataset scarcity. RuSentiment, SentiRuEval — main resources.

For production with simple positive/negative/neutral: distil models are enough. Three classes, balanced dataset, 2,000+ examples — F1 macro 0.82-0.87 in 1-2 days.

Text Summarization

Extractive summarization (select sentences) — TextRank or BM25 without training. Fast, no hallucinations. Good for long documents.

Abstractive (generates new text) — seq2seq: mT5, mBART, FRED-T5, ruT5-large. For production via LLM API (GPT-4, Claude) — often the best cost/quality/speed trade-off.

Embeddings: Vector Representations of Text

Embeddings are the foundation of semantic search, deduplication, clustering, RAG. Quality critically affects downstream tasks.

Models. E5-large-v2, BGE-M3, multilingual-e5-large — strong multilingual embedders. sentence-transformers/paraphrase-multilingual-mpnet-base-v2 — fast option. For Russian: ru-en-RoSBERTa (Skoltech) performs well on semantic textual similarity.

Embedding quality evaluation uses the MTEB benchmark as standard. But top results on MTEB don't guarantee success on a domain dataset — we build domain-specific eval.

Fine-tuning embeddings. If standard models don't give the required Recall@k — contrastive learning on domain pairs with MultipleNegativesRankingLoss. How to perform this for domain data:

  1. Collect 500–2,000 semantically similar pairs from your domain.
  2. Apply MultipleNegativesRankingLoss with a batch size of 32–64.
  3. Train for 1–3 epochs using AdamW (lr=2e-5).
  4. Evaluate Recall@k on a held-out domain test set.

This approach yields a 5–15% improvement in Recall@k in practice.

Dimensionality and storage. E5-large: 1024 dim, float32 — 4KB per vector. For 10M documents — 40GB. Quantization int8 reduces to 10GB. FAISS IVF_PQ — more compact but with losses. Included in our deployment recommendations.

Information Extraction

Structured extraction is a frequent task. Examples: key contract terms, technical characteristics, dates and amounts from invoices.

  1. Regex + rule-based. For INN, OGRN, amounts, dates — more reliable than neural networks. No data required.
  2. NER + post-processing. For variable formats.
  3. LLM with structured output. GPT‑4 / Claude with JSON schema — for complex documents. Cost: minimal per document. For 10k+ documents/day — we calculate the economics.

We guarantee a hybrid: regex/NER for typical fields + LLM for edge cases. Our guarantee is backed by years of production experience and more than 30 projects.

Work Stages

Stage Duration What's included
Data and metric analysis 3-5 days Class distribution, text lengths, baseline
Baseline (TF‑IDF + LogReg) 1 day Quick estimate of gap with deep models
Training and validation 1-2 weeks k‑fold, early stopping, error analysis
Deployment (ONNX + FastAPI) 1-2 weeks REST API, batching, monitoring
Documentation and training 2-3 days Model card, API docs, team training

Prototype on existing data — 1-3 weeks. Production system with CI/CD — 1.5–2.5 months. Cost is calculated individually — get a consultation for a project estimate.

What's Included

  • Model and pipeline architecture documentation
  • Access to the model via REST API (FastAPI + ONNX)
  • Client team training (2-hour webinar + Q&A)
  • Accuracy guarantee on the agreed test set
  • Months of post-delivery support (bug fixes, adaptation to new data)

Our Experience

Years of NLP projects from classification to RAG systems. The team includes ML engineers experienced with Hugging Face, spaCy, LangChain, MLOps. We use vLLM, Kubeflow, Weights & Biases — a production stack, not toys. Contact us to evaluate your NLP project within two days — request a free consultation on your text processing pipeline.