Algorithm Search⌘K

Algorithmintro

Lesk algorithm

Also called simplified Lesk, gloss overlap disambiguation.

Choose the sense whose dictionary gloss shares the most words with the context of the ambiguous word.

Time
O(n + r g log g) worstO(n + r g) average
Space
O(n + g) extra
Where
g = the largest number of words in the gloss and examples of one sense; n = the number of context tokens; r = the number of senses of the target word
Properties
deterministicnot exactofflineiterativenot supervised
Origin
Michael Lesk, 1986

The Lesk algorithm solves word sense disambiguation with a dictionary and no training data. For each sense of the ambiguous word it takes the words of the dictionary entry, the gloss and the example sentences, and it counts how many of them also occur in the context. It returns the sense with the largest count. The form on this page is the simplified Lesk algorithm, which compares each entry with the context words. Lesk's original form compares the entries of two words that occur together with each other. Both are heuristics: they choose the sense with the most shared words, and nothing proves that this is the intended sense. The Yarowsky algorithm learns its evidence from a corpus instead.

In plain words

A dictionary explains each sense of a word with other words. If a sentence talks about a river, boats and water, the sense of "bank" whose explanation also talks about water is probably the right one.

So the method takes the sentence, drops small words such as "the" and "of", and keeps the rest. For each sense it looks at the definition and the example sentences of that sense, also without the small words. It counts the words that the sense and the sentence have in common. The sense with the highest count wins. If no sense shares any word with the sentence, it keeps the first sense of the dictionary, which is usually the most common one. Lesk's own version does the same with two words at once, for example "pine" and "cone", and picks the two senses whose definitions share the most words.

The problem

The input is a target word ww, its context (a list of tokens, for example the sentence), and the senses s1,…,srs_1, \ldots, s_r of ww in a dictionary, in dictionary order with the most frequent sense first. Each sense has a gloss and possibly example sentences. A stop list of function words is fixed. The output is one sense of ww. This is the per-occurrence classification of the word sense disambiguation problem, solved with the dictionary as the only knowledge.

The signature of a sense is the set of words of its gloss and examples, lowercased, minus the stop words. The context set CC is the set of context words, lowercased, minus the stop words and minus ww itself. The overlap of sis_i is ∣Si∩C∣|S_i \cap C|.

The algorithm

  1. SIMPLIFIED-LESK(w, context, s_1 .. s_r)
  2. 1best ← s_1 ▷ the most frequent sense
  3. 2maxoverlap ← 0
  4. 3C ← set of the context words, minus stop words and minus w
  5. 4for i ← 1 to r do
  6. 5S ← set of the words in the gloss and examples of s_i, minus stop words
  7. 6overlap ← |S ∩ C|
  8. 7if overlap > maxoverlap then
  9. 8maxoverlap ← overlap; best ← s_i
  10. 9return best

The strict test of line L7 gives each tie to the earlier sense, and the start values of lines L1 and L2 make the first sense the answer when no sense overlaps the context. With hash sets, line L6 costs time proportional to the smaller set.

The original form. For two words aa and bb that occur together, GLOSS-PAIR-LESK compares the signature of each sense of aa with the signature of each sense of bb and returns the pair of senses with the largest overlap, the first pair on ties. For more than two words, the joint choice of one sense per word that maximizes the sum of the pairwise overlaps must try every combination, which grows as the product of the numbers of senses; the code has this as all_pairs_lesk for a few words.

Example

The sense inventory for "bank", written for this page:

sense gloss example
bank.1 a financial institution that accepts deposits and lends money she opened an account at the bank
bank.2 sloping land beside a body of water they sat on the bank of the river and watched the boats
bank.3 a row of similar objects a bank of switches

With the stop list of the code, the signature of bank.2 is {sloping, land, beside, body, water, sat, river, watched, boats}. Four contexts:

context overlaps (1, 2, 3) shared words result
the fishermen pulled their boats onto the bank when the river rose 0, 2, 0 boats, river bank.2
I went to the bank to deposit my money 1, 0, 0 money bank.1
the bank was closed 0, 0, 0 none bank.1 (the default)
a body of water and a bank of switches 0, 2, 1 body, water; switches bank.2

In the second context, "deposit" does not match "deposits" in the gloss, so only "money" counts. In the third context nothing matches, and line L1 decides.

For the original form, take two words with senses written for this page: pine.1 "an evergreen tree with needle shaped leaves", pine.2 "to waste away from sorrow or longing", cone.1 "a solid body that narrows to a point from a round base", cone.2 "the woody fruit of an evergreen tree" and cone.3 "a crisp wafer shaped to hold ice cream". Of the six pairs, only (pine.1, cone.2) shares words, namely "evergreen" and "tree", so GLOSS-PAIR-LESK returns that pair with overlap 2.

Correctness

The claim is exact about what the algorithm computes, not about the sense the writer meant: SIMPLIFIED-LESK returns the first sense with the largest overlap, or s1s_1 when every overlap is 0. The loop of line L4 keeps the invariant that after ii senses, maxoverlapmaxoverlap is the largest of 0 and the first ii overlaps, and bestbest is the first sense that reaches it, or s1s_1 if it is 0. Line L7 changes them only for a strictly larger overlap, which is exactly what keeps the "first" in the invariant. The full proof, with the pair form, is below.

Whether the chosen sense is the right one is an empirical question. The overlap rule is a heuristic, and its accuracy is a measurement that depends on the dictionary, the stop list and the test set.

Proof: Simplified Lesk returns the first sense of largest overlap, or the first sensefull

We use the pseudocode of the page. The target word ww has the senses s1,…,srs_1, \ldots, s_r with r≥1r \ge 1, in dictionary order. Let CC be the context set of line L3: the context words, lowercased, without the stop words and without ww. Let SiS_i be the signature of sis_i (line L5) and oi=∣Si∩C∣o_i = |S_i \cap C| its overlap (line L6). Let M=max⁡(0,o1,…,or)=max⁡ioiM = \max(0, o_1, \ldots, o_r) = \max_i o_i, since each oi≥0o_i \ge 0.

Claim. SIMPLIFIED-LESK stops and returns si∗s_{i^*}, where i∗=1i^* = 1 if M=0M = 0, and otherwise i∗i^* is the smallest index ii with oi=Mo_i = M.

Proof. For 0≤t≤r0 \le t \le r let Mt=max⁡(0,o1,…,ot)M_t = \max(0, o_1, \ldots, o_t), with M0=0M_0 = 0. We use this invariant of the loop of line L4.

(I) After the first tt iterations, maxoverlap=Mtmaxoverlap = M_t, and best=s1best = s_1 if Mt=0M_t = 0, while otherwise best=sjbest = s_j for the smallest j≤tj \le t with oj=Mto_j = M_t.

Initialization. Before the loop, t=0t = 0. Lines L1 and L2 set best=s1best = s_1 and maxoverlap=0=M0maxoverlap = 0 = M_0, which is (I) for t=0t = 0.

Maintenance. Assume (I) after tt iterations, with t<rt < r. The next iteration computes ot+1o_{t+1} in lines L5 and L6.

  • If ot+1>Mto_{t+1} > M_t, then Mt+1=ot+1>0M_{t+1} = o_{t+1} > 0, and t+1t + 1 is the smallest index j≤t+1j \le t + 1 with oj=Mt+1o_j = M_{t+1}, because every earlier ojo_j is at most Mt<ot+1M_t < o_{t+1}. Line L7 is true and line L8 sets maxoverlap=ot+1maxoverlap = o_{t+1} and best=st+1best = s_{t+1}. So (I) holds after t+1t + 1 iterations.
  • If ot+1≤Mto_{t+1} \le M_t, then Mt+1=MtM_{t+1} = M_t, and the smallest index with the value Mt+1M_{t+1} (when Mt+1>0M_{t+1} > 0) is the same as before, since an index t+1t + 1 with ot+1=Mto_{t+1} = M_t comes after it. Line L7 is false and nothing changes, so (I) holds after t+1t + 1 iterations.

Termination. The loop runs over the rr senses once, so it stops. With t=rt = r, (I) gives maxoverlap=Mr=Mmaxoverlap = M_r = M and best=si∗best = s_{i^*}, and line L9 returns it. □\square

The pair form. GLOSS-PAIR-LESK takes two words with the senses a1,…,ara_1, \ldots, a_r and b1,…,bub_1, \ldots, b_u and visits the pairs (ax,by)(a_x, b_y) in the order of xx and then yy. It keeps a pair and its overlap, starts with the overlap −1-1, and replaces the pair only when a strictly larger overlap appears. The same argument, with the visiting order in place of the index order and −1-1 in place of 00, shows that it returns the first pair in that order whose overlap ∣S(ax)∩S(by)∣|S(a_x) \cap S(b_y)| is the largest. Since the first overlap is at least 0>−10 > -1, some pair is always kept. ■\blacksquare

Complexity

The model is the word-RAM with hash sets of words, so a set insertion and a lookup take expected constant time.

  • Context set. Line L3 inserts nn words: O(n)O(n) expected time and O(n)O(n) space.
  • One sense. Line L5 builds a set of at most gg words and line L6 looks each of them up in CC: O(g)O(g) expected time.
  • All senses. O(n+rg)O(n + r g) expected time. With sorted lists instead of hash sets, the intersections cost O(glog⁡g)O(g \log g) each, which gives the worst case of the front matter. Only one signature is kept at a time, so the extra space is O(n+g)O(n + g).
  • Pair form. O(rarbg)O(r_a r_b g) for words with rar_a and rbr_b senses, after building the signatures. The joint form for mm words tries ∏iri\prod_i r_i combinations.

Properties

  • Unsupervised. It needs no sense-tagged text, only a dictionary with glosses.
  • Deterministic. The answer depends on the order of the senses only through the tie rule.
  • Sparse evidence. Glosses are short, so most overlaps are 0 or 1, and many decisions fall back to the first sense.
  • Bag of words. The order of the words and their distance from the target do not count.

Variants and improvements

  • Original Lesk. Compare the glosses of the senses of the target with the glosses of the senses of the context words, as in the pair form above.
  • Extended gloss overlap. Banerjee and Pedersen 2002 add the glosses of related WordNet senses (hypernyms, hyponyms and others) to each signature, and score longer shared phrases higher.
  • Weighted overlap. Weight each shared word by its inverse document frequency, as in tf-idf, so that a shared rare word counts more than a shared common one.
  • Corpus Lesk. Add the words of sense-tagged example sentences from a corpus to the signatures, which is a step toward a supervised classifier such as naive Bayes.
  • Joint choice. Choosing the senses of all the words of a sentence at once makes the search exponential; Cowie, Guthrie and Guthrie 1992 searched it with simulated annealing.

When to use it

Use simplified Lesk as a baseline, or when there is a dictionary but no sense-tagged corpus. It is easy to explain, since the shared words are the reason for the answer. When sense-tagged data exist, a supervised classifier is usually better, and the most frequent sense alone is a strong baseline that simplified Lesk must beat to be worth its cost (see word sense disambiguation).

Pitfalls

  • The target word in the signature. The example sentences of a dictionary usually contain the target word, as all three examples above do. If line L3 keeps ww in the context, every sense with an example gets one free point. Remove ww in line L3, as the pseudocode does.
  • No stop list. If lines L3 and L5 keep function words, "the", "of" and "a" decide many choices. Remove the stop words on both sides (see stop word removal).
  • Word forms. Line L6 matches exact strings, so "deposit" does not match "deposits". Apply stemming or lemmatization to both sides before line L6.
  • The tie rule. With "≥" in line L7, ties go to the last sense, and a context with no overlap returns the last sense instead of the most frequent one. Keep the strict test, with the senses in frequency order.
  • Counting tokens instead of types. If the signature or the context is a list and not a set, a word repeated in a gloss counts several times. Use sets in lines L3 and L5, or say that the page uses multisets.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

lesk_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lesk-algorithm/. The authors are listed in prov/JX07Y6.jsonl.
"""The Lesk algorithm: choose the sense whose dictionary entry shares the most
words with the context.

simplified_lesk compares each gloss of the target word with the context
words. gloss_pair_lesk is the original form for two words: it compares the
glosses of the senses of one word with the glosses of the senses of the other.
"""

from dataclasses import dataclass, field
from itertools import product

STOP_WORDS = frozenset(
    "a an the of in on at to for from by with and or but is are was were be been "
    "it its this that these those he she they we you i his her their our my as "
    "which who what when where so not no do does did can will would".split()
)


@dataclass(frozen=True)
class Sense:
    """One dictionary sense: a name, the gloss and the example sentences, as tokens."""

    name: str
    gloss: tuple[str, ...]
    examples: tuple[str, ...] = field(default=())


def signature(sense: Sense, stop_words: frozenset[str] = STOP_WORDS) -> set[str]:
    """The set of lowercased words of the gloss and the examples, minus stop words."""
    return {w.lower() for w in sense.gloss + sense.examples} - stop_words


def simplified_lesk(
    word: str,
    context: list[str],
    senses: list[Sense],
    stop_words: frozenset[str] = STOP_WORDS,
) -> Sense:
    """The sense of word whose signature overlaps the context most.

    Precondition: senses is not empty and is in dictionary order, most
    frequent sense first. Ties, and a context with no overlap, give the
    earlier sense. Cost: O(r g + n) set operations for r senses with
    signatures of at most g words and a context of n tokens.
    """
    if not senses:
        raise ValueError("the word has no senses")
    best = senses[0]  # @line L1
    max_overlap = 0  # @line L2
    ctx = {w.lower() for w in context} - stop_words - {word.lower()}  # @line L3
    for sense in senses:  # @line L4
        sig = signature(sense, stop_words)  # @line L5
        overlap = len(sig & ctx)  # @line L6
        if overlap > max_overlap:  # @line L7
            max_overlap = overlap  # @line L8
            best = sense
    return best  # @line L9


def overlap_scores(
    word: str, context: list[str], senses: list[Sense], stop_words: frozenset[str] = STOP_WORDS
) -> list[int]:
    """The overlap of each sense with the context, in the order of senses."""
    ctx = {w.lower() for w in context} - stop_words - {word.lower()}
    return [len(signature(s, stop_words) & ctx) for s in senses]


def gloss_pair_lesk(
    senses_a: list[Sense], senses_b: list[Sense], stop_words: frozenset[str] = STOP_WORDS
) -> tuple[Sense, Sense, int]:
    """Lesk's original form for two words that occur together.

    Returns the pair of senses whose signatures share the most words, and
    the size of the overlap. Ties give the first pair in the order of
    (sense of a, sense of b). Cost: O(r_a r_b g) for r_a and r_b senses.
    """
    if not senses_a or not senses_b:
        raise ValueError("each word needs at least one sense")
    sigs_b = [signature(s, stop_words) for s in senses_b]
    best = (senses_a[0], senses_b[0], -1)
    for a in senses_a:
        sig_a = signature(a, stop_words)
        for b, sig_b in zip(senses_b, sigs_b):
            k = len(sig_a & sig_b)
            if k > best[2]:
                best = (a, b, k)
    return best


def all_pairs_lesk(
    inventory: dict[str, list[Sense]], words: list[str], stop_words: frozenset[str] = STOP_WORDS
) -> tuple[dict[str, Sense], int]:
    """Choose one sense for each of several words at once.

    The score of a choice is the sum of the overlaps of all pairs of chosen
    signatures. This tries every combination, so the cost grows as the
    product of the numbers of senses; use it only for a few words.
    """
    sigs = {w: [signature(s, stop_words) for s in inventory[w]] for w in words}
    best: tuple[tuple[int, ...], int] = ((), -1)
    for choice in product(*(range(len(inventory[w])) for w in words)):
        score = 0
        for x in range(len(words)):
            for y in range(x + 1, len(words)):
                score += len(sigs[words[x]][choice[x]] & sigs[words[y]][choice[y]])
        if score > best[1]:
            best = (choice, score)
    return {w: inventory[w][i] for w, i in zip(words, best[0])}, best[1]
test_lesk_algorithm.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lesk-algorithm/. The authors are listed in prov/JX07Y6.jsonl.

import itertools
import random

from lesk_algorithm import (
    STOP_WORDS,
    Sense,
    all_pairs_lesk,
    gloss_pair_lesk,
    overlap_scores,
    signature,
    simplified_lesk,
)


def sense(name: str, gloss: str, examples: str = "") -> Sense:
    return Sense(name, tuple(gloss.split()), tuple(examples.split()))


BANK = [
    sense("bank.1", "a financial institution that accepts deposits and lends money", "she opened an account at the bank"),
    sense("bank.2", "sloping land beside a body of water", "they sat on the bank of the river and watched the boats"),
    sense("bank.3", "a row of similar objects", "a bank of switches"),
]
PINE = [
    sense("pine.1", "an evergreen tree with needle shaped leaves"),
    sense("pine.2", "to waste away from sorrow or longing"),
]
CONE = [
    sense("cone.1", "a solid body that narrows to a point from a round base"),
    sense("cone.2", "the woody fruit of an evergreen tree"),
    sense("cone.3", "a crisp wafer shaped to hold ice cream"),
]


def test_worked_example() -> None:
    c1 = "the fishermen pulled their boats onto the bank when the river rose".split()
    assert overlap_scores("bank", c1, BANK) == [0, 2, 0]
    assert simplified_lesk("bank", c1, BANK).name == "bank.2"
    c2 = "I went to the bank to deposit my money".split()
    assert overlap_scores("bank", c2, BANK) == [1, 0, 0]
    assert simplified_lesk("bank", c2, BANK).name == "bank.1"
    c3 = "the bank was closed".split()
    assert overlap_scores("bank", c3, BANK) == [0, 0, 0]
    assert simplified_lesk("bank", c3, BANK).name == "bank.1"
    c4 = "a body of water and a bank of switches".split()
    assert overlap_scores("bank", c4, BANK) == [0, 2, 1]
    assert simplified_lesk("bank", c4, BANK).name == "bank.2"


def test_pine_cone() -> None:
    a, b, k = gloss_pair_lesk(PINE, CONE)
    assert (a.name, b.name, k) == ("pine.1", "cone.2", 2)
    assert signature(a) & signature(b) == {"evergreen", "tree"}
    chosen, score = all_pairs_lesk({"pine": PINE, "cone": CONE}, ["pine", "cone"])
    assert chosen["pine"].name == "pine.1" and chosen["cone"].name == "cone.2" and score == 2


def test_edges() -> None:
    assert simplified_lesk("bank", [], BANK).name == "bank.1"
    assert simplified_lesk("bank", ["bank", "bank"], BANK).name == "bank.1"
    assert simplified_lesk("Bank", "RIVER Boats".split(), BANK).name == "bank.2"
    assert simplified_lesk("x", ["y"], [BANK[2]]).name == "bank.3"
    assert "the" not in signature(BANK[0]) and "money" in signature(BANK[0])
    assert signature(BANK[0], frozenset()) >= {"the", "a", "money"}
    for bad in ([],):
        try:
            simplified_lesk("x", ["y"], bad)
        except ValueError:
            pass
        else:
            raise AssertionError("no senses must fail")


def random_sense(rng: random.Random, name: str, vocab: list[str]) -> Sense:
    return Sense(name, tuple(rng.choice(vocab) for _ in range(rng.randrange(0, 6))),
                 tuple(rng.choice(vocab) for _ in range(rng.randrange(0, 3))))


def test_against_brute_force() -> None:
    rng = random.Random(11)
    vocab = ["w%d" % i for i in range(12)] + ["the", "of", "a"]
    for trial in range(600):
        senses = [random_sense(rng, "s%d" % i, vocab) for i in range(rng.randrange(1, 6))]
        context = [rng.choice(vocab) for _ in range(rng.randrange(0, 8))]
        target = rng.choice(vocab)
        ctx = set(context) - STOP_WORDS - {target}
        scores = [len((set(s.gloss) | set(s.examples)) - STOP_WORDS & ctx) for s in senses]
        top = max(scores)
        want = 0 if top == 0 else scores.index(top)
        assert simplified_lesk(target, context, senses) is senses[want]
        others = [random_sense(rng, "t%d" % i, vocab) for i in range(rng.randrange(1, 5))]
        best = max(
            itertools.product(range(len(senses)), range(len(others))),
            key=lambda ij: (len(signature(senses[ij[0]]) & signature(others[ij[1]])), -ij[0], -ij[1]),
        )
        a, b, k = gloss_pair_lesk(senses, others)
        assert (a, b) == (senses[best[0]], others[best[1]])
        assert k == len(signature(a) & signature(b))
        if trial % 3 == 0:
            chosen, score = all_pairs_lesk({"x": senses, "y": others}, ["x", "y"])
            assert score == k and (chosen["x"], chosen["y"]) == (a, b)

History

Lesk 1986 proposed the method at SIGDOC, using machine-readable dictionaries, and named the paper after the pine cone and ice cream cone example of the title. Later work kept the idea and changed what is compared: Cowie, Guthrie and Guthrie 1992 chose all the senses of a sentence at once, Kilgarriff and Rosenzweig 2000 used the simplified form, which compares the definitions with the context words, as a baseline in the first SENSEVAL evaluation, and Banerjee and Pedersen 2002 extended the signatures with WordNet relations.

References

  1. Michael Lesk, Automatic sense disambiguation using machine readable dictionaries, how to tell a pine cone from an ice cream cone, Proceedings of SIGDOC '86, 1986, pages 24 to 26, the method of counting the words shared by the dictionary definitions of the senses of words that occur together
  2. Kilgarriff and Rosenzweig 2000, the simplified Lesk baseline, which compares each sense definition with the words of the context
  3. Roberto Navigli, Word sense disambiguation, a survey, ACM Computing Surveys 41(2), 2009, article 10, the section on knowledge-based disambiguation by overlap of sense definitions
  4. Jurafsky and Martin, SLP3 draft of August 2025, Appendix Word Senses and WordNet, the sections on word sense disambiguation and the simplified Lesk algorithm

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example