Keyphrase Extraction: Finding Terms That Summarize
Module: Natural Language Processing | Difficulty: Advanced
What You'll Learn
- 1Generate and score candidate phrases with TF-IDF and position features
- 2Implement RAKE and TextRank over a word co-occurrence graph
- 3Evaluate exact-match precision, recall, and F1 at a fixed cutoff
- 4Choose between extraction and generation given available supervision
Keyphrase extraction pulls the few noun phrases that capture a document's subject, which is what a search snippet, a paper's author keywords, and a document clustering feature all need. The task splits cleanly in two: extraction reuses strings that already appear in the text, while generation may write phrases that do not. This lesson builds the two classic unsupervised graphs, adds the TF-IDF candidate scorer, and fixes the evaluation protocol that exact-match metrics demand.
Candidates and Scoring
A candidate extractor first proposes noun phrases, typically with a part-of-speech pattern such as adjective-noun or noun-noun sequences, then ranks them. TF-IDF is the baseline scorer and it already filters single-use terms in large corpora, while position features such as first occurrence and heading proximity add a large share of the remaining signal.
| Method | Year | Supervision | Training size | F1@10 |
|---|---|---|---|---|
| RAKE | 2010 | none | 0 | 0.12 |
| TextRank | 2004 | none | 0 | 0.14 |
| SingleRank | 2010 | none | 0 | 0.17 |
| Kea Naive Bayes | 1999 | supervised | 248 abstracts | 0.19 |
| KPMiner | 2006 | heuristic | 0 | 0.18 |
| Neural, KP20k | 2018 | supervised | 567,000 papers | 0.30 |
Unsupervised graph ranking
Both RAKE and TextRank build a graph and rank nodes, but they disagree about what a node is. RAKE builds a word graph within stopword-delimited segments and scores each word by degree divided by frequency. TextRank runs PageRank over a co-occurrence graph with weighted edges, then sums word scores inside each candidate phrase.
Aggregating word scores into phrases
Once words carry scores, a phrase is ranked by summing them, which favors longer candidates unless the score is divided by length. SingleRank therefore normalizes, and header-adjacent candidates receive a position bonus because authors state their topic in the first two paragraphs.
Worked Code
import re
from collections import Counter, defaultdict
STOP = set("""a an the and or of for to in on with by at from is are was were be been
this that these those it its as such into about over under between within""".split())
def rake(text, k=5):
"""Rapid Automatic Keyword Extraction over stopword-delimited segments."""
segments = [s for s in re.split(r"[^A-Za-z]+|\b(?:%s)\b" % "|".join(STOP), text) if s.strip()]
words, degree = Counter(), Counter()
for seg in segments:
toks = seg.split()
for i, w in enumerate(toks):
words[w] += 1
degree[w] += len(toks) - 1
for j in range(i + 1, len(toks)):
degree[w] += 1
degree[toks[j]] += 1
scored = {w: degree[w] / max(1, words[w]) for w in words}
phrases = [seg for seg in segments if seg]
ranked = sorted(phrases, key=lambda p: sum(scored.get(w, 0.0) for w in p.split()),
reverse=True)
return ranked[:k], scored
TEXT = ("Remote sensing satellites capture data about the earth surface. "
"Remote sensing satellites measure reflected electromagnetic radiation. "
"Image classification assigns a land cover label to each pixel. "
"The classification accuracy depends on training samples and sensor resolution.")
phrases, scores = rake(TEXT, k=4)
print("top phrases:")
for p in phrases:
print(" ", p, round(sum(scores.get(w, 0) for w in p.split()), 3))
import math
from collections import Counter, defaultdict
DAMPING = 0.85
TOKENS = ("remote sensing satellites capture data earth surface measure "
"reflected electromagnetic radiation image classification assigns "
"land cover label pixel accuracy depends training samples sensor resolution").split()
WINDOW = 4
COUNTS = Counter(TOKENS)
def build_graph(tokens, window=WINDOW):
graph = defaultdict(lambda: defaultdict(float))
for i, w in enumerate(tokens):
for j in range(i + 1, min(i + window, len(tokens))):
v = tokens[j]
if w == v:
continue
graph[w][v] += 1.0
graph[v][w] += 1.0
return graph
def textrank(graph, iters=60):
nodes = list(graph)
rank = {n: 1.0 / len(nodes) for n in nodes}
for _ in range(iters):
nxt = {}
for n in nodes:
acc = 0.0
for m in nodes:
if n in graph[m] and graph[m]:
out_w = sum(graph[m].values())
acc += rank[m] * graph[m][n] / out_w
nxt[n] = (1 - DAMPING) + DAMPING * acc
rank = nxt
return rank
GRAPH = build_graph(TOKENS)
RANK = textrank(GRAPH)
top = sorted(RANK.items(), key=lambda kv: kv[1], reverse=True)[:6]
print("textrank top words:")
for w, r in top:
print(f" {w:15s} {r:.4f}")
print("phrase score:",
round(sum(RANK.get(w, 0.0) for w in ("remote", "sensing")) / 2, 4))
Real-World Applications
- Kea (Frank et al., 1999) trained a Naive Bayes ranker on just 248 DUC abstracts and still reaches 0.19 F1@10, showing how small supervised sets go far.
- RAKE (Rose et al., 2010) needs no corpus statistics at all, so it runs on a single document in milliseconds and remains common in editorial tooling.
- KP20k (Meng et al., 2018) released 567,000 computer-science papers with author keywords, which is what pushed supervised F1@10 to about 0.30.
- TextRank over a co-occurrence graph is also the default inside most summarizers, where it selects sentences instead of words.
đĄExact match is unforgiving
Common Mistakes
Filling k slots regardless of score
Fix: Use a score threshold or a gap heuristic; proposing 10 phrases when the gold set has 8 caps precision at 0.8 before any ranking error
Evaluating on the training topic
Fix: Split by document, not by phrase, or IDF and neural rankers leak the exact keyphrases of neighbouring abstracts
Comparing extraction to generation numbers
Fix: Generation models may emit unseen phrases and are scored differently; keep the two regimes in separate table rows
Best Practices
- Report exact-match and stemmed F1 at several k, usually 5, 10, and 15
- Add a first-occurrence position feature; it is worth 3 to 5 F1 on scientific abstracts
- Filter candidates that appear only once in the corpus, since IDF already marks them as noise
Key Takeaways
- Candidates come from noun phrase patterns, then TF-IDF and position rank them
- RAKE scores degree divided by frequency; TextRank runs PageRank over a co-occurrence graph
- F1@10 of 0.12 to 0.17 for unsupervised methods against about 0.30 for KP20k-trained models
- Exact and stemmed matching must both be reported, because gold keyphrases vary in surface form
Frequently Asked Questions
What corpora are standard for evaluation?
Inspec holds 2,000 journal abstracts, SemEval-2010 Task 4 provides 248 papers with about 14,907 keyphrases, and KP20k adds 567,000 papers for training. KPTimes extends the task to news.
How many keyphrases should a system return?
Authors assign 3 to 10 keywords in practice. Most papers fix to 10 for comparability and additionally report F1 at 5 for short application contexts such as search snippets.
Does keyphrase generation beat extraction?
It beats extraction on recall because it can phrase a concept the authors never wrote, but it loses on precision when its outputs drift from the document's exact terminology, so the choice depends on whether downstream use tolerates paraphrase.
Interview Questions
Q1: Why does RAKE divide degree by frequency?
Degree counts co-occurrence, so dividing by frequency stops a word that appears in every segment from dominating; it rewards words that are well connected relative to how often they occur
Q2: What features did Kea use?
TF-IDF of the candidate and its relative position in the document, fed to a Naive Bayes classifier trained on 248 abstracts