Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Relation extraction

Relation extraction is the NLP task of finding and classifying semantic relationships (like 'works-for' or 'born-in') between entities in text.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Relation extraction is used by engineers to convert unstructured text into structured facts for knowledge graphs, question answering, information retrieval and business intelligence. It connects named entities (people, places, organisations) with labelled edges that downstream systems can query or reason over.

Key ideas

Start simple and build up.

  • Relation extraction — the task of detecting a relation (a labelled semantic link) between two or more entities in natural language text, and outputting the entity pair (or tuple) plus the relation label. Define here: an entity is a span of text that denotes a real-world object (person, place, organisation, chemical, date, etc.). A relation is a semantic predicate such as "works_for", "born_in", or "located_at" that connects entities.

  • Scope and assumptions. Most course problems assume: relations are binary (two entities), relations can be expressed inside a single sentence (intra-sentential), and entity mentions are already detected (NER done). Also assume relations are directed unless stated (entity order matters), though some relations are symmetric. If these assumptions change, algorithms must handle n-ary relations, cross-sentence inference, and joint entity–relation extraction.

  • Types of relation extraction methods:

    • Pattern-based: manually written patterns (surface patterns or dependency patterns). Assumes patterns generalise; precise but low recall.
    • Supervised classification: train a classifier on sentences labelled with relation types. Assumes enough labelled data, and that training and test sentences are similar.
    • Distant supervision: automatically generate training data by aligning facts from a knowledge base with text (assumes if KB has relation(r, e1, e2) then any sentence mentioning e1 and e2 expresses r). This assumption is noisy — many sentences mentioning both entities do not express the relation.
    • OpenIE (Open Information Extraction): extract relation triples with no fixed schema. Assumes we want many surface predicates, not canonical relation labels.
    • Neural end-to-end: models (CNN, RNN, Transformer) that encode sentences and output relation labels; often fine-tune pretrained contextual embeddings (like BERT). These reduce feature engineering needs but require more compute.
    • Joint models: extract entities and relations together, avoiding error propagation from NER to RE.
  • Typical pipeline (if not joint): Tokenisation → NER → Coreference resolution (optional) → Syntactic parsing (optional) → Relation classifier / pattern matcher → Post-processing.

  • Features commonly used (classical methods): surface words, word windows around entities, part-of-speech tags, dependency path between entities, entity types, shortest dependency path length, relative order, bag-of-words, and trigger words. Neural methods replace manual features with learned representations (word embeddings, position embeddings, sentence encodings).

  • Evaluation: use precision, recall, and F1. For ranked systems, use precision–recall curve and area under curve (AUC-PR). For open extraction, evaluate using held-out factual correctness or manual annotation. State whether you report micro- or macro-averaged scores; in closed-schema RE include a no_relation negative class and report micro-F1 over positive classes if required by the dataset/rubric.

  • Error sources and practical caveats: noisy labels (distant supervision), domain shift between training and real text, coreference errors, and ambiguous entity mentions. When designing an extraction system, explicitly list your assumptions (sentence-level, binary, labelled relations) because evaluation and method choice depend on them.

  • What to draw in an exam diagram:

    1. Pipeline diagram: draw boxes left-to-right labelled Tokenisation → NER → Coreference → Parser → Relation classifier → Knowledge base. Draw arrows between boxes. Annotate common features used at the parser → classifier arrow (dependency path, entity types).
    2. Dependency tree example: draw a small sentence like "Alice founded Acme in 2010." Draw nodes for tokens (Alice, founded, Acme, in, 2010) and labelled dependency arcs (nsubj from founded→Alice, dobj from founded→Acme, prep from founded→in, pobj from in→2010). Mark the shortest dependency path between Alice and Acme (Alice ← nsubj — founded — dobj → Acme) as the feature used for relation classification. Note: dependency labels vary by scheme (e.g., spaCy/Stanford vs Universal Dependencies), so use labels consistent with your parser.

Formulas

Precision = TP / (TP + FP) — TP: true positives, FP: false positives. Unit: dimensionless (fraction). Applies when counting system predictions against gold labels.

Recall = TP / (TP + FN) — FN: false negatives. Dimensionless. Applies same situation.

F1 = 2 * (Precision * Recall) / (Precision + Recall) — harmonic mean of precision and recall. Dimensionless. Defined when Precision + Recall > 0; if one is zero then F1 = 0, and if both are zero it is undefined.

CrossEntropy = - (1/N) * sum_{i=1..N} sum_{c} y_{i,c} * log(p_{i,c}) — where N is number of training examples, y_{i,c} is 1 if example i has class c, p_{i,c} is model probability. Units: nats if natural log is used, or bits if log base 2 is used. Used when training classifiers for relation labels.

P(r | s) = softmax(score_r(s)) — probability that sentence s expresses relation r, computed via softmax over relation scores. Dimensionless.

Notes on symbols: TP, FP, FN are simple counts (no units). N is count of examples. log is natural log unless specified.

Syntax to remember (Python classifier training outline):

  • model.forward(sentence) -> logits # compute scores
  • loss = CrossEntropyLoss(logits, label)
  • optimizer.zero_grad(); loss.backward(); optimizer.step()

Worked examples

Example 1 — rule-based extractor (programming). This runs in plain Python and extracts simple "X is the CEO of Y" style relations.

Code:

# simple_relation_extractor.py
import re

def extract_relations(text):
    patterns = [
        (re.compile(r"([A-Z][a-z]+(?:\s[A-Z][a-z]+)*)\s+is\s+the\s+CEO\s+of\s+([A-Z][a-zA-Z0-9& ]+)"), 'ceo_of'),
        (re.compile(r"([A-Z][a-z]+(?:\s[A-Z][a-z]+)*)\s+founded\s+([A-Z][a-zA-Z0-9& ]+)"), 'founded')
    ]
    triples = []
    for pat, rel in patterns:
        for m in pat.finditer(text):
            e1 = m.group(1).strip()
            e2 = m.group(2).strip()
            triples.append((e1, rel, e2))
    return triples

if __name__ == '__main__':
    s = "Sundar Pichai is the CEO of Google. Larry Page founded Google."
    for t in extract_relations(s):
        print(t)

Sample input (the program prints from main): Sundar Pichai is the CEO of Google. Larry Page founded Google.

Exact output when run (each tuple on its own line): ('Sundar Pichai', 'ceo_of', 'Google') ('Larry Page', 'founded', 'Google')

This example shows pattern-based extraction: simple and precise, but misses many paraphrases.

Example 2 — distant supervision (theory model-answer): Question: Explain how distant supervision creates training data and its main problem. Model answer (exam style):

  1. Take a knowledge base (KB) with facts (r, E1, E2), for example (born_in, 'Albert Einstein', 'Ulm').
  2. For each sentence in a large corpus that mentions both E1 and E2, label that sentence as expressing relation r. This produces many labelled examples automatically.
  3. Train a supervised relation classifier on this noisy dataset. Assumption: any sentence mentioning both entities expresses the KB relation. Main problem: assumption is false often — many sentences co-mention the pair without expressing the relation. This injects false positive labels (noise), lowering precision. Common fixes: multi-instance learning, sentence-level attention, filtering with patterns.

Example 3 — model comparison (theory): Question: Compare supervised vs neural Transformer-based extraction. Model answer: Supervised traditional systems require features (dependency path, POS, lexicon) and work well with limited data; they are interpretable. Transformer-based models (BERT fine-tuning) produce contextual embeddings and achieve higher accuracy with transfer learning; they need less manual feature work but require GPUs and risk domain mismatch. A full answer lists assumptions, data needs, typical performance trade-offs and when to choose each.

Common mistakes

  • Using precision/recall interchangeably: forget that precision measures false positives while recall measures false negatives.
  • Forgetting to include coreference when relations cross mentions (e.g., "He founded X") — this loses relations.
  • Drawing only linear pipeline boxes without annotating features or error sources in diagrams.

For your exam

Types of questions that appear:

  • Definitions: define relation extraction, entity, binary relation, distant supervision.
  • Short notes: list methods (pattern-based, supervised, distant supervision, OpenIE, neural), pros and cons.
  • Derivations: show formula for F1 as harmonic mean and derive it from precision/recall; show cross-entropy loss form.
  • Programs: implement a simple pattern-based extractor (regular expressions) and show output.
  • Diagrams: draw pipeline and dependency tree, label shortest dependency path.

What a full-marks answer includes:

  • Clear definitions (bold terms), assumptions stated, method description and when it applies, example diagram with labels, and discussion of advantages and problems (noise, domain shift). For program questions include runnable code, sample input and exact output.

Quick check

  1. What is the main assumption of distant supervision?
  2. Give the formula for recall.
  3. Name two features used by classical supervised relation extractors.

Answers: 1) Any sentence that mentions both entities from a KB fact expresses that relation (this is the noisy assumption). 2) Recall = TP / (TP + FN). 3) Shortest dependency path between entities; entity types (from NER).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?