Algorithmcore
Incremental algorithm for referring expressions
Also called Dale-Reiter incremental algorithm.
Build a description of a target object by adding attributes in a fixed preference order whenever they rule out some distractor.
- Time
- O(p m) worst
- Space
- O(p + m) extra
- Where
- m = the number of distractors; p = the number of attributes in the preference list
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Robert Dale, Ehud Reiter, 1995
The incremental algorithm builds a description that picks out one object, the referent, from the other objects in the context, the distractors. It goes through the attributes in a fixed preference order, such as type, colour and size. It adds an attribute with the value of the referent when that property rules out at least one distractor that is still left, and it stops as soon as no distractor is left. Robert Dale and Ehud Reiter published it in 1995. It is the referring expression step of the microplanner in the natural language generation pipeline. The description it returns is correct but need not be the shortest, and finding the shortest one is NP-hard.
In plain words
You want to say which dog you mean. There are two dogs and a cat in the room. Your dog is small and black, the other dog is large and white, and the cat is small and black.
Say first what kind of thing it is: "dog" rules out the cat. Then try the next attribute on your list. If the list says colour next, "black" rules out the white dog, and you say "the black dog". If the list says size next, "small" rules out the large dog, and you say "the small dog".
The algorithm never goes back. Once a word is in, it stays, even when a later word makes it unnecessary. People speak like this too: they often say more than they need, and they do not first search all short descriptions.
The problem
The input is a referent , a set of distractors and a preference list of attributes. Each object has a value for some of the attributes. A property is true of when has the value for , and it rules out a distractor when is known to have a value for that is not . A description is a set of properties true of , and it distinguishes when every distractor is ruled out by some property in . The task is to find a distinguishing description, or to report that none exists. A short description is better, but the algorithm does not try to minimize the length.
The algorithm
MAKE-REFERRING-EXPRESSION(r, C, P)- 1
L ← {} - 2
for each attribute A in P, in order - 3
V ← the value of A for r - 4
R ← {x in C : the known value of A for x is not V} - 5
if R ≠ {} - 6
add <A, V> to L - 7
C ← C - R - 8
if C = {} - 9
add <type, r.type> to L if L has no type pair - 10
return L - 11
return failure
This is Figure 6 of the paper in its flat form. In the paper, line L3 calls FindBestValue, which can climb a taxonomy of values, for example from "chihuahua" to "dog", and picks the basic level value unless a more specific value rules out more distractors. Line L4 is RulesOut: a distractor is removed only when the hearer is known to believe that it does not have the property. Line L9 adds the type even when it rules out nothing, so that the result can be said as a noun phrase, "the black one" becoming "the black dog".
Example
This is the example of Section 4.4 of the paper. The referent is Object1, a small black dog. The distractors are Object2, a large white dog, and Object3, a small black cat.
| step | attribute | value | ruled out | left |
|---|---|---|---|---|
| start | Object2, Object3 | |||
| 1 | type | dog | Object3 | Object2 |
| 2 | colour | black | Object2 | none |
With = (type, colour, size) the result is {type: dog, colour: black}, "the black dog". With = (type, size, colour), step 2 uses size, "small" rules out Object2, and the result is "the small dog".
The result need not be minimal. Take the referent as before, and the distractors a small white cat and a large black cat. With = (colour, size, type), "black" rules out the white cat and "small" rules out the large cat, so the list is empty after two attributes, and line L9 adds the type: "the small black dog". The single property "dog" rules out both cats, so "the dog" is enough.
Correctness
These are theorems, proved in full in the proofs file.
- Soundness. If the algorithm returns , then every property in is true of , and rules out every distractor. The invariant is that holds exactly the distractors that no property of rules out.
- Completeness for . The algorithm fails exactly when the properties of for all attributes in together do not distinguish . Once an attribute rules out a distractor, that distractor is gone, and no step brings it back.
- No redundancy when added. Each attribute pair except the final type pair rules out, at the time it is added, some distractor that no earlier pair ruled out. A later pair can still make an earlier one unnecessary.
- No constant factor. For every there is an input where one property is enough and the algorithm returns .
- Hardness of the shortest description. Deciding whether a distinguishing description with at most properties exists is NP-complete, by a direct reduction from set cover: one attribute per set, one distractor per element, and the distractor of element differs from on attribute exactly when is in set .
Dale and Reiter (Section 2.2) state that a distinguishing description is a set cover, and cite Garey and Johnson for its NP-hardness. They do not write out a reduction, so the proofs file gives one.
That the incremental algorithm gives natural descriptions is a heuristic claim, which the paper supports with results from psycholinguistics. The algorithm optimizes nothing: it follows a fixed order and never revises a choice.
Proof: The incremental algorithm returns a distinguishing description exactly when the preferred attributes allow one, and the minimal description problem is NP-hardfull
Fix a referent , a finite set of distractors and a non-empty list of attributes. For an attribute that has, write for the value of on , and let ; for an attribute that does not have, . A set of pairs distinguishes when . Line L4 computes for the current .
Lemma 1 (invariant). At the start of each round of line L2, and at line L8, , and every pair in is true of .
Proof. Before the first round and . A round with attribute either changes nothing (when ), or adds to and removes from . In the second case the new is , which is the old right side minus . The value added is , the value of .
Theorem 1 (soundness). If the algorithm returns a list , then distinguishes , every pair of is true of , and the attribute pairs of other than the type pair added at line L9 each rule out a distractor that no earlier pair ruled out.
Proof. Line L10 runs only when , so by Lemma 1 the pairs of rule out all of . Adding the type pair at line L9 keeps this true, and the type pair is true of . A pair is added at line L6 only when , and by Lemma 1 the elements of were not ruled out by earlier pairs.
Theorem 2 (completeness for ). The algorithm returns failure if and only if the full set does not distinguish .
Proof. Suppose some is in no for . Then by Lemma 1, at every test of line L8, so line L10 never runs and line L11 returns failure. Conversely, suppose every is in for some , and suppose the algorithm reaches the round of the last attribute without returning. Take any and the first with . In round , either was already removed, or , so and line L7 removes . Elements never come back into . So after round , line L8 finds and line L10 returns .
Theorem 3 (cost). The algorithm runs in time with hash table lookups for the attribute values, and uses extra space.
Proof. There are at most rounds. In a round, line L4 checks each element of once, and line L7 removes the elements of in time. Every other line takes time, and line L9 checks , of size at most , once.
Theorem 4 (no constant factor). For every there is an input where the minimal distinguishing description has 1 attribute pair and the algorithm returns attribute pairs.
Proof. Let have attributes , all with value 1, and no type. Let . The distractor has value 0 for and for , and value 1 for the other attributes; has value 0 for and value 1 for the other attributes. Then for and . With , round finds , adds and removes . The distractor stays in until round , which adds . So the result has pairs, while the single pair rules out all of .
Theorem 5 (the minimal description problem is NP-complete). The problem "given , , a set of attributes and an integer , is there a distinguishing description with at most pairs?" is NP-complete.
Proof. It is in NP: a description of at most pairs is checked with Lemma 1 in polynomial time. For hardness, reduce from set cover, which Karp (1972) showed NP-complete: a universe , sets and an integer ; is there a cover by at most sets? Build a referent with attributes , all with value 1, and one distractor for each , where has value 0 for if and value 1 otherwise. Then . A set of indices covers exactly when rules out every . So a cover of size at most exists if and only if a distinguishing description of size at most exists. The construction takes time.
Conversely, the minimal description problem is a set cover instance with universe and sets , so the greedy set cover algorithm (Johnson 1974) finds a description at most times the minimal size, where is the harmonic number. Dale and Reiter (1995, Section 2.2) state this correspondence; Theorem 5 is the formal reduction in the direction that gives hardness.
Complexity
The loop runs at most times. Line L4 checks each remaining distractor once, with a hash table lookup for the attribute value, and line L7 removes the ruled out ones. So the worst case is time for distractors, and extra space for and . Section 4.5 of the paper notes that the run time is linear in the number of distractors and does not depend on the number of attributes the referent has.
Figure 2 of the paper compares four interpretations of the maxims, with the properties true of the referent, the distractors and the attributes in the final description:
| interpretation | complexity | typical run time |
|---|---|---|
| Full Brevity (Dale 1989) | NP-hard | about |
| Greedy Heuristic (Dale 1989) | polynomial | about |
| Local Brevity (Reiter 1990) | polynomial | about |
| Incremental Algorithm | polynomial | about |
The estimate for the incremental algorithm assumes that few attributes of are tried without being added.
Properties
- Deterministic and order dependent. The output depends only on the order . Different orders give different descriptions, as in the example.
- Not minimal. The output can be longer than the shortest description, with no constant bound on the ratio. This is by design: the paper argues that people also add properties that are not needed.
- Never backtracks. A property, once added, stays. This makes the algorithm fast and simple to implement.
- Fails only when it must. If the attributes in can distinguish the referent at all, the algorithm finds a description.
- The type is always there. Line L9 adds the type pair, so a noun is available for the noun phrase.
Variants and improvements
- Full Brevity. Search the descriptions by size and return the shortest. This is exact and NP-hard; on small inputs a search over subsets of attributes, in time, is fast enough. The tests use it as the reference.
- Greedy Heuristic. Add the property that rules out the most remaining distractors. This is Johnson's greedy set cover algorithm, so its result is at most times the shortest, where is the harmonic number. The code includes it.
- Local Brevity. Reiter (1990) starts from a description and replaces or removes properties while the result gets shorter.
- Value taxonomies. The full algorithm of the paper picks the value of each attribute from a taxonomy, with the basic level value preferred.
- Relations and sets. Later work extends the algorithm to relations between objects ("the cup on the table"), to sets of referents, and to negated or vague properties.
When to use it
Use the incremental algorithm in a rule based generator when you need short, natural descriptions of objects in a known domain, and a fixed preference order of attributes is easy to state, for example type before colour before size. It is fast and predictable. If the shortest description matters, for example on a small screen, and the number of attributes is small, search the subsets instead. If the description must also say how objects relate to each other, use an algorithm that handles relations.
Pitfalls
- Missing values. Treat a distractor with no known value for an attribute as not ruled out. Treating a missing value as "different" gives a description that the hearer cannot use.
- Stopping before the check. The check of line L8 must run after every attribute, also when the attribute is skipped. Skipping the check after an attribute that the referent does not have can make the algorithm fail on an input it can solve.
- Empty preference list. With empty the loop never runs and the algorithm fails, even when there are no distractors. Put at least the type in .
- Expecting minimality. Do not use the algorithm where the shortest description is required. Its output can be much longer than needed.
- Order of output. The order of the pairs in is the order of , not the order of words in the phrase. The realizer must order the adjectives and the noun.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/incremental-algorithm-referring-expressions/. The authors are listed in prov/NEB4RM.jsonl.
"""The incremental algorithm of Dale and Reiter (1995) for referring expressions.
An object is a dict from attribute names to values, for example
{"type": "dog", "size": "small", "colour": "black"}. The referent r is an
object, the distractors are a list of objects, and the preference order P is
a list of attribute names.
A property <A, V> rules out a distractor x when x has a value for A and that
value is not V. A distractor without the attribute A is not ruled out: the
hearer is not known to believe that it lacks the property (UserKnows is not
false). This is the flat form of the algorithm: there is no value taxonomy, so
FindBestValue returns the value of the referent, and BasicLevelValue of the
type is the type of the referent.
The result is a list of (attribute, value) pairs in the order they were
added, or None for failure.
"""
from itertools import combinations
from typing import Dict, Hashable, List, Optional, Sequence, Tuple
Obj = Dict[str, Hashable]
Pair = Tuple[str, Hashable]
def rules_out(attr: str, value: Hashable, distractors: Sequence[Obj]) -> List[int]:
"""Return the indices of the distractors that the property <attr, value> rules out."""
return [i for i, x in enumerate(distractors) if attr in x and x[attr] != value]
def make_referring_expression(
r: Obj, distractors: Sequence[Obj], preferred: Sequence[str], type_attr: str = "type"
) -> Optional[List[Pair]]:
"""Run the incremental algorithm (Figure 6 of Dale and Reiter 1995)."""
chosen: List[Pair] = [] # @line L1
c = list(distractors)
for a in preferred: # @line L2
v = r.get(a) # @line L3
out = set(rules_out(a, v, c)) if a in r else set() # @line L4
if out: # @line L5
chosen.append((a, v)) # @line L6
c = [x for i, x in enumerate(c) if i not in out] # @line L7
if not c: # @line L8
if type_attr in r and all(p[0] != type_attr for p in chosen): # @line L9
chosen.append((type_attr, r[type_attr]))
return chosen # @line L10
return None # @line L11
def distinguishes(pairs: Sequence[Pair], distractors: Sequence[Obj]) -> bool:
"""True when every distractor is ruled out by some pair."""
return all(any(a in x and x[a] != v for a, v in pairs) for x in distractors)
def minimal_description(
r: Obj, distractors: Sequence[Obj], attrs: Sequence[str]
) -> Optional[List[Pair]]:
"""Brute force: a smallest set of the referent's attributes that rules out every distractor.
Tries all subsets by size, in the order of attrs, so it takes O(2^m) time
for m attributes. Returns None when no subset works.
"""
own = [a for a in attrs if a in r]
for size in range(len(own) + 1):
for sub in combinations(own, size):
pairs = [(a, r[a]) for a in sub]
if distinguishes(pairs, distractors):
return pairs
return None
def greedy_description(
r: Obj, distractors: Sequence[Obj], attrs: Sequence[str]
) -> Optional[List[Pair]]:
"""The greedy set cover heuristic: add the attribute that rules out the most remaining distractors."""
own = [a for a in attrs if a in r]
c = list(distractors)
pairs: List[Pair] = []
while c:
best, gain = None, 0
for a in own:
g = len(rules_out(a, r[a], c))
if g > gain:
best, gain = a, g
if best is None:
return None
pairs.append((best, r[best]))
c = [x for x in c if not (best in x and x[best] != r[best])]
own.remove(best)
return pairs
test_incremental_algorithm_referring_expressions.py 156 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/incremental-algorithm-referring-expressions/. The authors are listed in prov/NEB4RM.jsonl.
import random
from fractions import Fraction
from itertools import combinations
from incremental_algorithm_referring_expressions import (
distinguishes,
greedy_description,
make_referring_expression,
minimal_description,
rules_out,
)
DOG1 = {"type": "dog", "size": "small", "colour": "black"}
DOG2 = {"type": "dog", "size": "large", "colour": "white"}
CAT3 = {"type": "cat", "size": "small", "colour": "black"}
def test_dale_reiter_example():
# Section 2.2 and Section 4.4 of the paper (with cat for siamese-cat).
got = make_referring_expression(DOG1, [DOG2, CAT3], ["type", "colour", "size"])
assert got == [("type", "dog"), ("colour", "black")]
got = make_referring_expression(DOG1, [DOG2, CAT3], ["type", "size", "colour"])
assert got == [("type", "dog"), ("size", "small")]
def test_type_is_added_at_the_end():
got = make_referring_expression(DOG1, [DOG2], ["colour", "size", "type"])
assert got == [("colour", "black"), ("type", "dog")]
# No distractors: the loop stops at the first attribute with only the type.
assert make_referring_expression(DOG1, [], ["colour"]) == [("type", "dog")]
def test_not_minimal():
r = {"type": "dog", "colour": "black", "size": "small"}
x1 = {"type": "cat", "colour": "white", "size": "small"}
x2 = {"type": "cat", "colour": "black", "size": "large"}
got = make_referring_expression(r, [x1, x2], ["colour", "size", "type"])
assert got == [("colour", "black"), ("size", "small"), ("type", "dog")]
assert minimal_description(r, [x1, x2], ["colour", "size", "type"]) == [("type", "dog")]
def test_k_pairs_against_one():
# The input of Theorem 4 in the proofs file.
for k in range(2, 8):
attrs = ["a%d" % i for i in range(1, k + 1)]
r = {a: 1 for a in attrs}
dist = []
for i in range(1, k):
x = {a: 1 for a in attrs}
x["a%d" % i] = 0
x["a%d" % k] = 0
dist.append(x)
y = {a: 1 for a in attrs}
y["a%d" % k] = 0
dist.append(y)
got = make_referring_expression(r, dist, attrs)
assert got == [(a, 1) for a in attrs]
assert minimal_description(r, dist, attrs) == [("a%d" % k, 1)]
def set_cover_instance(sets, m):
"""The reduction of Theorem 5: one attribute per set, one distractor per element."""
attrs = ["s%d" % j for j in range(len(sets))]
r = {a: 1 for a in attrs}
dist = [{a: (0 if u in sets[j] else 1) for j, a in enumerate(attrs)} for u in range(m)]
return r, dist, attrs
def test_set_cover_reduction():
rng = random.Random(72)
for _ in range(200):
m = rng.randint(1, 6)
sets = [set(u for u in range(m) if rng.random() < 0.4) for _ in range(rng.randint(1, 5))]
r, dist, attrs = set_cover_instance(sets, m)
best = None
for size in range(len(sets) + 1):
for js in combinations(range(len(sets)), size):
if set().union(*[sets[j] for j in js]) == set(range(m)):
best = size
break
if best is not None:
break
desc = minimal_description(r, dist, attrs)
assert (desc is None) == (best is None)
if desc is not None:
assert len(desc) == best
def test_failure():
twin = dict(DOG1)
assert make_referring_expression(DOG1, [twin, DOG2], ["type", "colour", "size"]) is None
assert minimal_description(DOG1, [twin], ["type", "colour", "size"]) is None
def test_unknown_value_is_not_ruled_out():
x = {"type": "dog"}
assert rules_out("colour", "black", [x]) == []
assert make_referring_expression(DOG1, [x], ["colour", "size"]) is None
def replay(r, distractors, preferred):
"""An independent run with sets of indices; returns the pairs or None."""
left = set(range(len(distractors)))
pairs = []
for a in preferred:
if a in r:
gone = {i for i in left if a in distractors[i] and distractors[i][a] != r[a]}
if gone:
pairs.append((a, r[a]))
left -= gone
if not left:
if "type" in r and not any(p[0] == "type" for p in pairs):
pairs.append(("type", r["type"]))
return pairs
return None
def harmonic(n):
return sum(Fraction(1, i) for i in range(1, n + 1))
def test_random_against_brute_force():
rng = random.Random(1995)
attrs = ["type", "colour", "size", "shape", "material"]
worse = 0
for _ in range(800):
def obj(full):
o = {}
for a in attrs:
if full or rng.random() < 0.85:
o[a] = rng.randint(0, 2)
return o
r = obj(True)
dist = [obj(False) for _ in range(rng.randint(0, 6))]
pref = rng.sample(attrs, rng.randint(1, len(attrs)))
got = make_referring_expression(r, dist, pref)
assert got == replay(r, dist, pref)
best = minimal_description(r, dist, pref + [a for a in attrs if a not in pref])
best_p = minimal_description(r, dist, pref)
assert (got is None) == (best_p is None)
if got is None:
continue
assert distinguishes(got, dist)
assert all(r[a] == v for a, v in got)
assert len(got) >= len(best)
if len(got) > len(best):
worse += 1
g = greedy_description(r, dist, pref)
assert g is not None and distinguishes(g, dist)
# Johnson (1974): greedy set cover is within H(n) of the optimum.
assert len(g) <= harmonic(len(dist)) * len(best_p) or len(dist) == 0
# The incremental algorithm is often not minimal.
assert worse > 50
History
Dale (1989) had generated referring expressions in the EPICURE system by searching for the shortest description, with a greedy heuristic to make the search fast. Reiter (1990) proposed the Local Brevity interpretation. In their 1995 paper, Dale and Reiter compared these interpretations of Grice's maxims with experiments in psycholinguistics, which show that people often include properties that are not needed. They concluded that a simple, fast algorithm that does not try to minimize the description is both more efficient and closer to human behavior. The algorithm was used in the IDAS system and became the standard baseline for the generation of referring expressions.
References
- Robert Dale and Ehud Reiter, Computational Interpretations of the Gricean Maxims in the Generation of Referring Expressions, Cognitive Science 19(2), 1995, pages 233 to 263, Section 2.2 (the set cover correspondence), Figure 2 in Section 3.1 (the costs of four interpretations), Figure 6 in Section 4.3 (the algorithm), Section 4.4 (the example), Section 4.5 (the run time)
- David S. Johnson, Approximation algorithms for combinatorial problems, Journal of Computer and System Sciences 9(3), 1974, the greedy set cover heuristic
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag NEB4RM Edit this page History Report an error Markdown