Entities alone do not answer questions
Knowing that a sentence mentions "Elon Musk" and "SpaceX" is bookkeeping. The value appears when you can assert a typed relationship between them â founder_of, ceo_of, invested_in â because triples are what a knowledge graph stores, what a question-answering system joins over, and what a compliance report can actually check. Relation extraction is the task of producing those triples from raw text, and it sits immediately downstream of entity recognition in every information-extraction stack.
The task splits into three families with very different trade-offs. Closed-schema classification assumes you know the relation inventory in advance and assigns one label to an entity pair. Open information extraction invents relation phrases freely, trading consistency for coverage. Distant supervision generates training data automatically from an existing knowledge base, trading label noise for scale. Most mature systems combine them: open extraction to discover which relations actually occur in the corpus, distant supervision to harvest examples at volume, and a supervised classifier to serve the relations that matter to the product.
Closed-schema classification as multi-class learning
With a fixed label set, relation extraction is ordinary classification: encode the sentence, pool a representation that highlights the two entities, and softmax over the relation inventory plus a no-relation class. The no-relation class dominates every benchmark â roughly 80 percent of entity pairs in TACRED carry no relation â so accuracy is a meaningless metric and macro-averaged F1 is the number to watch. Class weighting or focal loss is usually necessary before any architecture change is worth trying.
Entity-pair enumeration is the hidden cost. A sentence with five entities yields ten ordered pairs, and only one or two carry a relation. Systems that classify every pair pay ten forward passes for two useful triples, so a cheap filter â pair distance in the sentence, NER type compatibility, a lexical heuristic â should run before the transformer. In practice this filter removes the majority of pairs and cuts serving cost without touching recall on the pairs that matter.
Entity markers and how encoders see the pair
The representation choice matters more than the classifier head. Early systems used the pooled class token and hoped self-attention would find the entities; marker-based models splice special tokens around each mention and read the hidden states at those positions, which consistently adds several F1 points for almost no cost. Concatenating the two marker vectors with their elementwise product and difference gives the head both the individual meanings and the interaction terms, which is why that four-way concatenation became the standard feature vector.
Directionality is a design decision you make once and regret later. "Apple acquired Beats" and "Beats acquired Apple" share the same unordered pair; if your label set distinguishes subject from object â and founder_of certainly does â train on ordered pairs and mark them in the order you intend, or the model will learn an arbitrary orientation that flips on paraphrases.
import torch
import torch.nn as nn
from transformers import AutoModel, AutoTokenizer
class EntityMarkerRE(nn.Module):
def __init__(self, model_name, num_relations):
super().__init__()
self.encoder = AutoModel.from_pretrained(model_name)
hidden = self.encoder.config.hidden_size
self.classifier = nn.Sequential(
nn.Linear(hidden * 4, hidden),
nn.ReLU(),
nn.Dropout(0.1),
nn.Linear(hidden, num_relations),
)
def mark(self, tokenizer, sentence, e1, e2):
marked = sentence.replace(e1, f" [E1] {e1} [/E1]")
marked = marked.replace(e2, f" [E2] {e2} [/E2]")
return tokenizer(marked, return_tensors="pt", truncation=True)
def forward(self, input_ids, attention_mask, e1_pos, e2_pos):
hidden = self.encoder(
input_ids=input_ids, attention_mask=attention_mask
).last_hidden_state
e1 = hidden[torch.arange(hidden.size(0)), e1_pos]
e2 = hidden[torch.arange(hidden.size(0)), e2_pos]
features = torch.cat([e1, e2, e1 * e2, e1 - e2], dim=-1)
return self.classifier(features)
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
tokenizer.add_special_tokens(
{"additional_special_tokens": ["[E1]", "[/E1]", "[E2]", "[/E2]"]}
)
model = EntityMarkerRE("bert-base-uncased", num_relations=10)
model.encoder.resize_token_embeddings(len(tokenizer))
sentence = "Elon Musk founded SpaceX in 2002."
inputs = model.mark(tokenizer, sentence, "Elon Musk", "SpaceX")
e1_pos = (inputs["input_ids"][0] == tokenizer.convert_tokens_to_ids("[E1]")).nonzero().item()
e2_pos = (inputs["input_ids"][0] == tokenizer.convert_tokens_to_ids("[E2]")).nonzero().item()
logits = model(
inputs["input_ids"],
inputs["attention_mask"],
torch.tensor([[e1_pos]]),
torch.tensor([[e2_pos]]),
)
print("predicted relation id:", torch.argmax(logits, dim=-1).item())
Open IE: triples without a label set
Open information extraction refuses the fixed inventory. Instead of choosing among forty-one relations, it reads a sentence and emits whatever triples it finds, usually as subject, relation phrase, object. "Apple was founded by Steve Jobs in California" yields founded_by(Steve Jobs, Apple) and located_in(Apple, California) with the relation phrase preserved verbatim. That makes open IE attractive for bootstrapping a domain schema, because clustering the relation phrases across a corpus shows you which relations actually occur in your text before anyone spends an annotation hour.
Sequence-to-sequence models now dominate the space. A model fine-tuned to emit marked triples in a single decoding pass replaces the hand-built rules that older open IE systems relied on, and the parsing step afterward is pure string handling. The characteristic failure mode is hallucinated triples: generative extractors occasionally produce a relation the sentence does not support, so downstream consumers need a verification step â typically an entailment check of each triple against the source sentence â before anything is written to a knowledge graph.
from transformers import pipeline
rebel = pipeline("text2text-generation", model="Babelscape/rebel-large")
def extract_triples(text, max_length=256):
out = rebel(
f"<ent> {text} <sep>", max_length=max_length, num_beams=3
)[0]["generated_text"]
triples = []
for chunk in out.split("<sep>"):
chunk = chunk.strip()
if not chunk:
continue
parts = chunk.split("<ent>")
subject = parts[0].replace("<rel>", "").strip()
relation = parts[1].split("<ent>")[0].strip() if len(parts) > 1 else ""
obj = parts[-1].strip() if len(parts) > 2 else ""
if subject and relation and obj:
triples.append(
{"subject": subject, "relation": relation, "object": obj}
)
return triples
for t in extract_triples("Apple was founded by Steve Jobs in California in 1976."):
print(f"({t['subject']}, {t['relation']}, {t['object']})")
Distant supervision and the noise it buys you
Distant supervision rests on one assumption: if the knowledge base says Tesla's chief executive is Elon Musk, then any sentence containing both probably expresses that relation. Aligning a knowledge-base triple with a corpus sentence produces a training example with no human in the loop, which is how systems scale to dozens of relations and millions of instances. The assumption is also wrong often enough to hurt â a sentence mentioning Musk and Tesla may discuss a lawsuit, a launch, or a regulatory filing, and distant supervision labels it ceo_of anyway.
Standard mitigations are well established. Multi-instance learning treats all sentences for one entity pair as a bag and only requires that at least one of them expresses the relation. Selective supervision keeps sentences where the relation phrase is lexically aligned with the knowledge-base predicate, such as matching the word "founded" against founder_of. Noise-aware training downweights examples whose annotation confidence is low. None of these fully clean the data, but each measurably improves macro F1 on held-out human-annotated test sets, and the confidence signal they produce is what makes the harvested data usable at all.
def align_triples_to_corpus(kb_triples, sentences, min_gap=2):
examples = []
for subject, relation, obj in kb_triples:
for sent in sentences:
if subject in sent and obj in sent:
i, j = sent.index(subject), sent.index(obj)
gap = abs(i - j) - max(len(subject), len(obj))
if gap < min_gap:
continue
lexical_hint = relation.split("_")[-1] in sent.lower()
examples.append({
"text": sent,
"subject": subject,
"object": obj,
"relation": relation,
"confidence": 1.0 if lexical_hint else 0.5,
})
return examples
kb = [
("Apple", "founded_by", "Steve Jobs"),
("Tesla", "ceo_of", "Elon Musk"),
]
corpus = [
"Steve Jobs founded Apple in 1976.",
"Apple reported record revenue this quarter.",
"Elon Musk is the CEO of Tesla.",
"Tesla opened a new factory in Berlin.",
]
for ex in align_triples_to_corpus(kb, corpus):
print(f"{ex['relation']} <- {ex['text']} (conf={ex['confidence']})")
# founded_by <- Steve Jobs founded Apple in 1976. (conf=1.0)
# ceo_of <- Elon Musk is the CEO of Tesla. (conf=1.0)
đĄHold out entity pairs, not sentences
Datasets, splits, and the F1 numbers people quote
Reported scores are hard to compare because the datasets differ in size, relation count, and annotation policy. TACRED's forty-plus relations over roughly one hundred thousand sentences is the long-standing news-domain standard; its revised release fixed thousands of noisy labels, and several published improvements evaporated when re-evaluated on the corrected version. DocRED moves to full documents with ninety-six relations, which forces models to aggregate evidence across sentences, and scores drop accordingly. FewRel targets few-shot transfer with eighty balanced relations and support sets drawn from Wikipedia.
Micro F1 over triples remains the headline metric, but macro F1 exposes whether a model only learned the frequent relations. When you fine-tune on your own schema, hold out entire entity pairs rather than sentences â the same pair appearing in train and test inflates scores through pair memorization, and the effect is large enough to reverse conclusions about which model is better.
| Dataset | Relations | Size | Domain | Primary use |
|---|---|---|---|---|
| TACRED, revised | 41 plus no-relation | about 106k sentences | News | Supervised baselines |
| SemEval-2010 Task 8 | 9 directed | about 10.7k sentences | News | Teaching and prototyping |
| FewRel | 80 | about 70k sentences | Wikipedia | Few-shot evaluation |
| DocRED | 96 | about 5k documents | Wikipedia | Cross-sentence reasoning |
| NYT-Freebase | 24 | about 56k sentences | News | Distant supervision research |
Choosing between the three families
Start from your label needs. If you have fewer than thirty relations, clean human annotation of a few thousand pairs, and a consumer that requires stable identifiers, supervised classification with entity markers is the right answer and everything else is optimization. If the schema is unknown or the corpus is large enough that annotation cannot keep up, open extraction followed by clustering and manual mapping gives you a defensible inventory before you spend a single labeling hour. If a knowledge base already covers your domain, distant supervision can generate the training signal overnight, and a small human-labeled test set is the only annotation you still owe.
Whichever route you take, keep the pipeline honest about uncertainty. Relation extraction feeds knowledge graphs that other systems treat as ground truth, and a confidently wrong triple persists far longer than a missing one â it gets copied into search indexes, analytics, and automated alerts. Emitting a confidence score with every triple, and suppressing the low tail, is the cheapest safeguard you can add.
Common Mistakes
Reporting accuracy on a dataset where most pairs have no relation
Fix: Use micro and macro F1 over the relation labels; a model that always predicts no-relation still scores about 80 percent accuracy on TACRED.
Ignoring subject-object direction in the label set
Fix: Mark entities in a fixed order during training and keep that order at inference, or founder_of will flip unpredictably on paraphrases.
Training and testing distant supervision on random sentences from the same entity pair
Fix: Split by entity pair so the model cannot memorize pair-specific patterns and report inflated scores.
Writing open-IE triples straight into a knowledge graph
Fix: Run an entailment check per triple and keep a confidence field; generative extractors hallucinate relations the sentence never asserted.
Best Practices
- Filter entity pairs with cheap heuristics before running the transformer to cut serving cost without losing labeled pairs
- Use entity markers and the four-way feature concatenation rather than relying on a pooled class token
- Cluster open-IE relation phrases to discover your real schema before committing to a closed label set
- Combine distant supervision with multi-instance learning so only one sentence per bag needs to express the relation
- Emit confidence with every triple and suppress the low-confidence tail before it reaches downstream consumers
Interview Questions
Q1: Why is accuracy meaningless on TACRED?
About 80 percent of entity pairs are labeled no-relation, so a constant no-relation predictor already achieves roughly 80 percent accuracy; micro and macro F1 over the positive relations are the informative numbers.
Q2: What problem do entity markers solve?
They give the encoder explicit positions for both mentions, so the hidden states at those positions can be read as entity representations instead of hoping pooled attention isolates them; this adds several F1 points at almost no cost.
Q3: How does distant supervision create training data, and what is its main drawback?
It aligns knowledge-base triples with corpus sentences containing both entities, labeling them with the known relation. The drawback is label noise: many such sentences do not actually express the relation, so mitigations like multi-instance learning or selective supervision are required.
Key Takeaways
- Relation extraction turns entity mentions into typed triples, which is what knowledge graphs and question-answering joins actually consume
- Closed-schema classification needs the no-relation class, pair filtering, and macro F1 to behave sensibly on real data
- Entity markers plus the product and difference features are the standard way to represent the pair for a transformer
- Open IE discovers relation phrases without annotation; distant supervision buys scale at the cost of label noise
- Split evaluation by entity pair and attach confidence to every triple before downstream systems trust the output