🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Entity Linking: Candidate Generation and Disambiguation

Information ExtractionEntity Linking and Knowledge Base IntegrationđŸŸĸ Free Lesson

NER finds spans; linking decides what they mean

Named entity recognition answers where and what-type; it cannot answer which-one. A tagger that marks "Apple" as an organization has done its job, but a downstream system that wants a stock ticker, a headquarters city, or a Wikipedia link still faces every sense of the word that ever appeared in a newspaper. Entity linking closes that gap: it takes each mention span, proposes the knowledge-base entries it could refer to, uses the surrounding text to choose among them, and attaches a stable identifier to the result.

That identifier is the whole point. Strings are unstable — organizations rename, products accumulate acronyms, people get referred to by surname — while a knowledge-base ID such as Wikidata's Q312 is a permanent handle you can join against, deduplicate on, and query for structured properties. Pipelines that stop at raw entity strings look finished in a demo and fall apart the first time "Apple" and "AAPL" have to be counted as the same company in a quarterly report.

The four stages and how errors compound

The classical pipeline has four steps: mention detection, candidate generation, disambiguation, and NIL handling. Mention detection is usually an NER model or a dictionary match, and it defines the ceiling for everything downstream — a mention that is never proposed can never be linked correctly. Candidate generation retrieves the plausible knowledge-base entries for the surface form, typically by alias lookup: "Python" pulls up the programming language, the snake genus, and the Monty Python comedy group. Disambiguation picks the best candidate given context, and NIL handling decides that none of them fit.

Error propagation is the cascade's structural weakness. If mention detection reaches 92 F1 and disambiguation is 90 percent accurate on correctly detected mentions, end-to-end accuracy lands near 83 percent before any other factor is considered. This is why joint models, which predict the link directly from the sentence, often beat cascades on benchmarks even when each individual component looks worse in isolation — and why improving the last stage of a weak pipeline produces disappointing gains.

StageInputOutputFailure it causes downstream
Mention detectionRaw textSpan plus entity typeMissed spans cap final recall
Candidate generationSurface formRanked candidate IDsMissing alias makes an entity unreachable
DisambiguationCandidates plus contextBest-scoring IDWrong sense chosen despite correct candidates
NIL decisionScore patternID or abstentionForced links pollute the knowledge base

Candidate generation against a knowledge base

Candidate generation is a recall problem with a hard latency budget. The naive approach — string-match the mention against every entity label — works at toy scale and dies at Wikidata's size, so production systems use alias tables, inverted indexes over labels and redirects, and, for the long tail, a dense index built over entity descriptions.

The alias table matters more than the ranking model. Knowledge bases store the canonical label, but real text uses "the Big Apple", "Cupertino giant", and misspellings; every alias you fail to store becomes an unreachable entity no matter how good your classifier is. A practical recipe is to harvest aliases from page redirects, anchor text in Wikipedia, and search-log mining, then store them with a prior frequency — how often that alias resolved to that entity historically. The prior alone resolves a surprising fraction of short mentions that carry no useful context at all.

python
from collections import defaultdict

class AliasIndex:
    def __init__(self):
        self.alias_to_entities = defaultdict(list)
        self.priors = {}

    def add(self, kb_id, label, aliases, resolved_counts):
        total = sum(resolved_counts.values()) or 1
        for alias in [label, *aliases]:
            key = alias.lower().strip()
            if kb_id not in self.alias_to_entities[key]:
                self.alias_to_entities[key].append(kb_id)
            self.priors[(key, kb_id)] = resolved_counts.get(kb_id, 0) / total

    def candidates(self, mention, limit=10):
        key = mention.lower().strip()
        ids = self.alias_to_entities.get(key, [])
        ranked = sorted(
            ids, key=lambda e: self.priors.get((key, e), 0.0), reverse=True
        )
        return ranked[:limit]

index = AliasIndex()
index.add(
    "Q312", "Apple Inc.", ["Apple", "AAPL", "Apple Computer"],
    {"Q312": 9200, "Q16504": 180},
)
index.add(
    "Q16504", "Apple Records", ["Apple", "Apple Corps"],
    {"Q16504": 220},
)

print(index.candidates("Apple"))
# ['Q312', 'Q16504'] — the prior alone already ranks the company first
print(index.candidates("AAPL"))
# ['Q312']

Disambiguation: scoring mention against context

Once you have five or ten candidates, selection is a scoring problem. The strongest simple baseline combines four signals: the alias prior, similarity between the mention's local context and the candidate's description embedding, whether the rest of the document already favors one candidate, and type compatibility between the NER label and the candidate's knowledge-base types. Production systems usually learn a linear or tree-based model over these features rather than trusting any single one.

Embedding similarity is the component people over-trust. A generic bi-encoder run over "Apple: released the new iPhone" and the description of a record label still produces a moderately high cosine score, because both live near music and media in embedding space. The discriminative signal lives in the specific words — "iPhone", "quarterly earnings", "Cupertino" — which is why a cross-encoder reranker or a mention encoder fine-tuned on linking data beats a general sentence encoder on the same task, often by a wide margin.

python
import numpy as np
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")

class Disambiguator:
    def __init__(self, candidates, ner_type, context):
        self.candidates = candidates
        self.ner_type = ner_type
        self.context = context

    def _embed(self, text):
        return model.encode(text[:512], normalize_embeddings=True)

    def score(self, candidate):
        ctx = self._embed(self.context)
        desc = self._embed(candidate["description"])
        similarity = float(np.dot(ctx, desc))
        total = 0.65 * similarity + 0.35 * candidate["prior"]
        if self.ner_type not in candidate["types"]:
            total *= 0.4
        return total, similarity

    def resolve(self, min_score=0.30, min_margin=0.05):
        scored = []
        for c in self.candidates:
            total, sim = self.score(c)
            scored.append((c["id"], round(total, 3), round(sim, 3)))
        scored.sort(key=lambda row: row[1], reverse=True)
        best = scored[0]
        runner_up = scored[1][1] if len(scored) > 1 else 0.0
        margin = best[1] - runner_up
        if best[1] < min_score or margin < min_margin:
            return {"id": "NIL", "margin": round(margin, 3), "scores": scored}
        return {"id": best[0], "margin": round(margin, 3), "scores": scored}

candidates = [
    {
        "id": "Q312",
        "description": "American multinational technology company designing consumer electronics",
        "prior": 0.98,
        "types": ["ORG"],
    },
    {
        "id": "Q16504",
        "description": "British record label founded by The Beatles",
        "prior": 0.02,
        "types": ["ORG"],
    },
]

resolver = Disambiguator(
    candidates,
    ner_type="ORG",
    context="Apple unveiled the new iPhone at its Cupertino campus ahead of quarterly earnings.",
)
print(resolver.resolve())
# {'id': 'Q312', 'margin': 0.41, 'scores': ...}

The NIL problem: when nothing matches

Every knowledge base is incomplete. A new startup, a freshly published paper, or a person who was not notable last year simply has no entry, and a linker forced to choose among candidates will invent a link — attaching a mention of a new CEO to an existing athlete who shares the surname. Answering "none of the above" correctly is therefore a first-class requirement, not an edge case bolted on at the end.

The usual mechanism is a score margin. If the top candidate falls below an absolute threshold, or the gap between the top two candidates is smaller than a calibrated margin, emit NIL. Both thresholds should be tuned on a development slice of your own traffic rather than borrowed from a benchmark, because the right NIL rate depends on how quickly your domain moves relative to the knowledge base's update cadence. Systems that report accuracy only over linked mentions hide exactly the failure that annoys users most: the confident link to the wrong person.

âš ī¸Forced links are worse than abstentions

A wrong identifier poisons every downstream join, dashboard, and knowledge-graph edge built on it. When in doubt, abstain and queue the mention for review; the cost of a missing link is almost always lower than the cost of a wrong one.

Pipelines, joint models, and document-level context

Joint models feed the sentence plus marked mention spans into a single transformer and decode the entity ID directly, which removes the cascade's error propagation and lets the encoder condition on both mentions at once. The cost is that the model must carry the candidate set somehow — typically a classification head over a candidate embedding table, or a generative formulation that emits the ID as text — and every knowledge-base update means retraining or at least refreshing that table and its softmax layer.

Document-level linking is the cheaper axis and often the higher-return one. If one sentence mentions "Seattle" ambiguously and a later sentence says "the city council voted", the second mention disambiguates the first. A simple pass over candidate sets that share evidence across sentences resolves many of these cases without any new model. Full document-level encoders do better still, but they need longer contexts and more memory, so the lightweight consistency pass is the right default for most teams.

Evaluating end-to-end versus oracle-linking

Benchmark tables are easy to misread because papers report different tasks. Mention-level F1 counts a correct span plus correct ID; end-to-end F1 additionally requires getting span boundaries right; micro-averaging weights frequent entities more heavily than rare ones. A system evaluated with gold mentions — the pipeline's real NER replaced by human annotation — reports an oracle-linking number that can sit ten points above the end-to-end figure on the same data, and that gap is exactly the cost of the cascade.

For your own system, build a small labeled slice of production text before tuning anything. Include the mentions your users actually care about, label the knowledge-base IDs, and track three numbers: span F1, linking accuracy on gold spans, and end-to-end F1. The middle number isolates the linker; comparing all three tells you whether the next week of work belongs to NER, to candidate recall, or to disambiguation.

MetricWhat it isolatesTypical use
Span F1Mention detection qualityDecides whether to retrain the NER model
Linking accuracy on gold spansDisambiguation and candidatesIsolates the linker itself
End-to-end F1The deployed cascadeThe number stakeholders actually feel
NIL accuracyAbstention calibrationGuards against confident wrong links
Latency per mentionServing costKeeps the pipeline inside its budget

Common Mistakes

Building candidates from canonical labels only

Fix: Harvest aliases from redirects, anchor text, and logs; an unstored alias makes that entity permanently unreachable.

Trusting raw cosine similarity between context and entity description

Fix: Combine prior, similarity, and type checks, and calibrate a margin threshold so ambiguous mentions abstain instead of guessing.

Reporting accuracy only over successfully linked mentions

Fix: Include NIL cases and report end-to-end F1, because forced links are the failure users actually encounter.

Tuning thresholds on a public benchmark instead of your traffic

Fix: NIL rate depends on domain churn relative to the knowledge base; calibrate on a labeled slice of your own text.

Best Practices

  • Store alias priors and use them as the first ranking signal before any embedding runs
  • Mark both mention spans with special tokens so the encoder can attend to their exact positions
  • Apply a document-level consistency pass before reaching for a heavier document encoder
  • Version the knowledge-base snapshot used at training time so evaluations stay reproducible
  • Route low-margin and NIL predictions into a human review queue to grow gold data over time

Interview Questions

Q1: Why is end-to-end linking accuracy always lower than accuracy on gold mentions?

The cascade adds mention detection errors on top of disambiguation errors, and missed or mis-bound spans cannot be recovered downstream, so the gap measures the cost of the pipeline structure itself.

Q2: How do you decide between a pipeline and a joint model?

Pipelines are modular, debuggable, and easy to refresh against a live knowledge base; joint models avoid error propagation and win when the candidate set is small and stable. Teams usually start with a pipeline and move joint only when measured cascade loss justifies the serving complexity.

Q3: What role does the alias prior play in disambiguation?

It encodes how often a surface form resolved to each entity historically, which resolves most short mentions outright and acts as a strong regularizer when context embeddings are ambiguous.

Key Takeaways

  • Linking converts mention strings into stable knowledge-base IDs, which is what makes joins, deduplication, and structured queries possible
  • Candidate recall is bounded by your alias table, so harvesting aliases is often worth more than a better ranking model
  • Disambiguation works best as a weighted combination of prior, contextual similarity, document evidence, and type compatibility
  • NIL prediction with calibrated thresholds prevents the confident wrong links that poison downstream systems
  • Measure span F1, gold-span linking accuracy, and end-to-end F1 separately to know which stage to improve
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement