Algorithmadvanced
Smatch
Also called semantic match score.
Score two AMR graphs by the F1 of matching triples under the best variable mapping, found by hill climbing with restarts.
- Time
- O(r t^2 (m n + m^2)) worst
- Space
- O(t + m + n) extra
- Where
- m = the number of variables of the test graph; n = the number of variables of the gold graph; r = the number of restarts; t = the number of triples of both graphs
- Model
- Word RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Shu Cai, Kevin Knight, 2013
Smatch compares two abstract meaning representation graphs, a test graph from a parser and a gold graph from an annotator, and gives one number between 0 and 1. It writes each graph as a set of triples, maps the variables of the test graph one to one onto the variables of the gold graph, counts the triples that match, and reports the F1 of the best mapping. Finding the best mapping is NP-hard, so the standard tool searches with hill climbing from a concept-matching start plus random restarts, and the score it reports can be slightly below the true Smatch score. It is the usual metric for semantic parsing into AMR, in the way that PARSEVAL is for constituency trees, but it has no fixed alignment to the words, which is why it needs a search.
In plain words
Two people draw the meaning of a sentence as a graph. Each graph has boxes such as "want" and "boy" and labeled arrows such as "the wanter is the boy". The box names in the two drawings are arbitrary, so before comparing them we must decide which box in one drawing goes with which box in the other.
For a given pairing, list every fact of the first drawing and count how many also appear in the second. The score is based on the best pairing: it rewards facts that both drawings share and punishes facts that only one of them has.
Trying every pairing is too slow for large graphs. So the program starts from a good guess, pairing boxes with the same name, and makes the change that helps most until no change helps. It repeats this from a few random guesses and keeps the best result.
The problem
An AMR graph is a set of triples of three kinds: instance(v, c) says that the variable is an instance of the concept , role(v, w) is a relation between two variables, and role(v, k) gives a variable an attribute with a constant , such as polarity(v, -). The test graph has variables, the gold graph has variables, and the two graphs have triples together.
A mapping sends each test variable to a different gold variable or to nothing. Constants map to themselves. A test triple matches if all its variables are mapped and its image is a triple of . Let be the number of matched test triples. Then
Smatch is for the mapping with the largest . One mapping maximizes , and together, because the denominators do not depend on the mapping. The match count is symmetric: the best from to equals the best from to .
For a corpus, Smatch adds up , and over all sentence pairs and then applies the same formulas. This gives more weight to large graphs than the mean of the sentence scores would.
The algorithm
CLIMB(T, G, φ)- 1
M ← the number of test triples that match under φ - 2
loop - 3
for each test variable a and each gold variable g that is unused, or nothing: gain of sending a to g - 4
for each pair of test variables a, b: gain of swapping their images - 5
if no move has a positive gain then return (M, φ) - 6
apply the move with the largest gain; M ← M + gain SMATCH(T, G, r)- 7
(best, φ*) ← CLIMB(T, G, SMART-INIT(T, G)) - 8
repeat r times: (M, φ) ← CLIMB(T, G, a random one to one mapping) - 9
if M > best then (best, φ*) ← (M, φ) - 10
return P, R and F for best
SMART-INIT sends each test variable to the first unused gold variable with the same concept, and leaves it unmapped if there is none. Lines L3 and L4 are the two kinds of moves of Cai and Knight: change the image of one variable, and swap the images of two variables. Both keep the mapping one to one. Line L6 takes the steepest move, so this is steepest-ascent hill climbing, and lines L7 to L9 make it random-restart hill climbing. The implementation also has an exact search that tries every mapping, which the tests use as the reference.
Example
The example of Cai and Knight, section 2. The gold graph says "the boy wants to go" and the test graph says "the boy wants the football":
gold: (a / want-01 :ARG0 (b / boy) :ARG1 (c / go-01 :ARG0 b))
test: (x / want-01 :ARG0 (y / boy) :ARG1 (z / football))
The gold graph has 6 triples: three instance triples, ARG0(a, b), ARG1(a, c) and ARG0(c, b). The test graph has 5: three instance triples, ARG0(x, y) and ARG1(x, z). The six full mappings of onto give:
| image of | matched triples | |
|---|---|---|
instance(x, want-01), instance(y, boy), ARG0(x, y), ARG1(x, z) |
4 | |
instance(x, want-01) |
1 | |
| none | 0 | |
| none | 0 | |
| none | 0 | |
instance(y, boy), and ARG0(x, y), whose image is ARG0(c, b) |
2 |
The best mapping is , , with , so , , and . The smart start finds this mapping directly here, because want-01 and boy occur once in each graph.
Hill climbing can stop too early. Take the test graph instance(t0, p), instance(t1, q), r(t0, t1) and the gold graph instance(g0, q), instance(g1, q), r(g0, g1). The smart start leaves unmapped, because no gold variable has the concept , and sends to , with . No single move raises , so the climb stops at 1. The best mapping, and , has : it gives up nothing and gains the relation, but it takes two moves to reach, and the first of them lowers . A random restart can start near it.
Correctness
The full proofs are in proofs/correctness.md. The claims:
- Exact search (theorem). The search over every one to one partial mapping returns the best , and so the true Smatch score. It is enough to try mappings that map variables, because mapping one more variable to an unused gold variable never loses a match.
- Hill climbing (theorem). Each step raises by at least 1, and , so CLIMB takes at most steps and stops. Every mapping it holds is one to one, so the reported is at most the best : the reported score is a lower bound on the true score.
- Not exact (theorem, with the example above). A climb can stop at a local maximum below the best .
- NP-hardness (theorem). Deciding whether some mapping has is NP-complete. The proof reduces subgraph isomorphism: give every vertex the concept
nodeand turn each edge into twoedgetriples, one in each direction. Then a graph is a subgraph of exactly when the best equals the number of triples of , . Cai and Knight note that the problem is NP-complete; the reduction on this page is written out for it.
Proof: The exact search gives the Smatch score, hill climbing gives a lower bound and stops, and the best mapping is NP-hard to findfull
We use the definitions and the pseudocode of the page. The test graph and the gold graph are sets of triples. has variables and has variables, and the two sets of variables are disjoint. A mapping sends each test variable to a gold variable or to nothing, and no two test variables go to the same gold variable. A constant maps to itself. A test triple matches under if all its variables are mapped and its image is a triple of . is the number of matched test triples, and .
Part 1: the score is a function of the best match count
For a mapping the precision is , the recall is , and
when , and when . The sizes and do not depend on , so , and all grow with , and one mapping maximizes all three. Smatch is at .
The match count is symmetric. If is a mapping from to , its inverse on the image is a mapping from to . A test triple matches the gold triple exactly when maps to , and is one to one on triples because it is one to one on variables. So the matched triples of the two directions are in bijection, and is the same in both directions.
For a corpus of pairs the score is computed from the sums, , and , by the same algebra. This is in general not the mean of the sentence scores.
Part 2: the exact search is correct
The function match_count looks at each test triple once. It skips a triple whose first variable is unmapped, or whose second field is an unmapped variable. Otherwise it forms the image and tests it against . This is the definition of a match, so it returns .
smatch_brute_force enumerates every one to one partial map from the test variables to the gold variables: it chooses an ordered list of slots from the gold variables and copies of "nothing", and it removes repeated lists. There are of them, where is the number of mapped variables. It keeps the largest count, so it returns .
Monotonicity. Let leave a test variable unmapped, and let be a gold variable outside the image of . Let agree with and send to . Every triple that matches under does not contain , because a triple with an unmapped variable never matches, so it has the same image under and still matches. Hence . Repeating this, a mapping that is maximal (it maps variables) reaches . So an exact search may restrict itself to maximal mappings. When , these are the one to one maps of all test variables.
Part 3: hill climbing stops and gives a lower bound
climb starts from a mapping and looks at two kinds of moves: send one test variable to an unused gold variable or to nothing, and swap the images of two test variables. Each move gives a one to one mapping again. Line L5 stops when no move raises . Otherwise line L6 takes the move with the largest gain.
Termination. The gain of a taken move is a positive integer, so rises by at least 1 at each step. is at most . So climb takes at most steps. Each step looks at moves. smatch_hill_climb runs climb once from the concept-matching start and once from each of a fixed number of random starts, so it stops.
Lower bound. Every mapping that climb holds is a one to one partial map, so its count is . The result of smatch_hill_climb is the count of one such mapping, so it is at most , and the score it reports is at most the true Smatch score.
Not always optimal. The result of one climb is a local maximum: no single move raises . It need not be . Take
- :
instance(t0, p),instance(t1, q),r(t0, t1), - :
instance(g0, q),instance(g1, q),r(g0, g1).
The concept-matching start finds no gold variable with concept for , and gives the first gold variable with concept . So it is nothing, , with . The moves are: (the relation goes to r(g1, g0), which is not in , so ), (), nothing (), and the swap (, nothing, ). None of them raises , so the climb stops at 1. The mapping , matches instance(t1, q) and r(t0, t1), so . The tests check this case and also check, on random graphs, that random restarts find where one climb does not.
Part 4: the best mapping is NP-hard
The decision problem asks, for graphs and and an integer , whether some mapping has .
It is in NP. A mapping is a certificate of size , and match_count checks it in time polynomial in .
It is NP-hard. We reduce from subgraph isomorphism: given undirected graphs and , is there a one to one map from the vertices of to the vertices of that sends every edge of to an edge of ? This problem is NP-complete, since it contains the clique problem. Build from : a variable with the triple instance(x_v, node) for each vertex , and the two triples edge(x_u, x_v) and edge(x_v, x_u) for each edge . Build from in the same way. Let . The construction takes linear time.
If exists, the mapping is one to one. Every instance triple matches, because all concepts are node. Each edge triple edge(x_u, x_v) maps to edge(x_{f(u)}, x_{f(v)}), which is in because is an edge of . So .
If some mapping has , every test triple matches. An instance triple matches only if its variable is mapped, so every test variable is mapped, and the vertex of the image of is one to one. An edge triple matches only if its image is an edge triple of , so sends every edge of to an edge of . So is isomorphic to a subgraph of .
Hence the decision problem is NP-complete, even with one concept and one role. Computing is therefore NP-hard, and no polynomial time exact algorithm exists unless P = NP. The tests run this reduction on random small graphs and compare it with a direct search for the subgraph. ∎
Complexity
Exact search. There are one to one partial mappings, and each takes time to score with a hash table of gold triples. For there are 1546. The exact search is only for tiny graphs.
Hill climbing. One step looks at moves. Scoring a move from scratch takes , so a step takes , and a climb has at most steps. With restarts the worst case is , expected with hashing. The space is . The implementation on this page scores moves from scratch for clarity. The standard tool first lists, for each test triple, the pairs of variable images that would make it match, and then computes the gain of a move from the triples that touch the moved variables, which is much faster in practice.
Measurement. Cai and Knight compared the integer program, which is exact, with hill climbing from a smart start and four random restarts on AMR data, and found that hill climbing gave nearly the same scores at a small fraction of the time. That setting is the default of the tool.
Properties
- Symmetric match count. The best from to equals the best from to , so swapping the graphs swaps and and keeps .
- Identity. A graph scored against itself, with renamed variables, gets , and hill climbing finds it from the smart start when every concept occurs once.
- Lower bound. The reported score never exceeds the true one. More restarts can only raise it.
- Randomized. The result depends on the random restarts. With a fixed seed it is reproducible.
- No word alignment. The score depends only on the graphs. Two graphs can score high even if a parser got the concepts from the wrong words.
Variants and improvements
- Integer program. Cai and Knight also write the search as a 0-1 integer program, with one variable for each pair of test and gold variables and one for each pair of triples that could match, which gives the exact score with a general solver at a much higher cost. See binary integer programming.
- Fine-grained scores. Later tools split the triples by kind and report separate scores for concepts, named entities, negation, reentrancies and semantic roles, to show where a parser fails.
- Faster or exact metrics. Later work replaced the search with an exact solver, or with a metric that compares graphs through their paths or through graph kernels, to avoid the randomness of the search.
When to use it
Use Smatch to evaluate an AMR parser against gold graphs, to measure agreement between two annotators, and in general to compare two small labeled graphs whose node names are arbitrary. Report the corpus score, state the number of restarts or use the default, and use the same tool for every system in a comparison. For graphs that come with an alignment to the words, a metric that uses the alignment is cheaper and exact.
Pitfalls
- Averaging sentence scores. The corpus score sums the counts. The mean of the sentence F values is a different number.
- Hill climbing noise. Two runs with different seeds can give slightly different scores. Small differences between systems can be within this noise.
- Variable names. Both graphs must use separate variable names, or a reader must rename them first. Otherwise a test variable can be confused with a gold one.
- Inverse roles. In PENMAN notation
:ARG0-ofis the inverse of:ARG0. The reader must turn(b :ARG0-of w)intoARG0(w, b), or equal graphs will not match. - Constants and quotes.
"Ed"andEdmust be read as the same constant. - Tool versions. Tools differ in small details, such as whether the root gets an extra triple. Compare scores only from the same tool.
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/smatch/. The authors are listed in prov/SMYWR9.jsonl.
"""Smatch: the F1 of matching triples between two AMR graphs.
An AMR graph is a set of triples of three kinds:
("instance", v, concept) the variable v is an instance of concept
(role, v, w) a relation between two variables
(role, v, constant) an attribute with a constant value
A value is a variable if it is the second field of an instance triple.
A mapping sends each variable of the test graph to a distinct variable of the
gold graph, or to None. A test triple matches if its image under the mapping
(constants map to themselves) is a gold triple. M(m) is the number of matched
test triples. Smatch is the F1 of the best mapping:
P = M / |test|, R = M / |gold|, F = 2 M / (|test| + |gold|).
smatch_brute_force tries every mapping. smatch_hill_climb is the search of Cai
and Knight 2013: steepest ascent over two moves (remap one variable, swap the
images of two variables), started once from a concept-matching mapping and
then from random mappings. It returns a lower bound on the best M.
"""
from fractions import Fraction
from itertools import permutations
import random
def variables(triples):
"""The variables of a graph, in sorted order."""
return sorted({t[1] for t in triples if t[0] == "instance"})
def match_count(test, gold, mapping):
"""Number of test triples whose image under mapping is in gold."""
gold = set(gold)
tvars = set(variables(test))
count = 0
for rel, a, b in set(test):
a2 = mapping.get(a)
if a2 is None:
continue
if rel == "instance" or b not in tvars:
b2 = b
else:
b2 = mapping.get(b)
if b2 is None:
continue
if (rel, a2, b2) in gold:
count += 1
return count
def all_mappings(tvars, gvars):
"""Every injective partial map from tvars to gvars (None means unmapped)."""
m = len(tvars)
slots = list(gvars) + [None] * m
seen = set()
for perm in permutations(slots, m):
if perm in seen:
continue
seen.add(perm)
yield dict(zip(tvars, perm))
def smatch_brute_force(test, gold):
"""Exact best match count and one best mapping, by trying every mapping."""
best, best_map = -1, None
for mapping in all_mappings(variables(test), variables(gold)):
c = match_count(test, gold, mapping)
if c > best:
best, best_map = c, mapping
return best, best_map
def smart_init(test, gold):
"""Map each test variable to an unused gold variable with the same concept."""
concept_t = {t[1]: t[2] for t in test if t[0] == "instance"}
by_concept = {}
for t in sorted(set(gold)):
if t[0] == "instance":
by_concept.setdefault(t[2], []).append(t[1])
used = set()
mapping = {}
for v in variables(test):
mapping[v] = None
for g in by_concept.get(concept_t[v], []):
if g not in used:
mapping[v] = g
used.add(g)
break
return mapping
def random_init(test, gold, rng):
"""A random injective partial mapping."""
tvars = variables(test)
slots = variables(gold) + [None] * len(tvars)
rng.shuffle(slots)
return dict(zip(tvars, slots[: len(tvars)]))
def climb(test, gold, mapping):
"""Steepest ascent from mapping; return (M, mapping) at a local maximum."""
tvars = variables(test)
gvars = variables(gold)
mapping = dict(mapping) # @line L1
score = match_count(test, gold, mapping)
while True: # @line L2
best_gain, best_move = 0, None
used = {g for g in mapping.values() if g is not None}
for a in tvars: # @line L3
for g in gvars + [None]:
if g == mapping[a] or (g is not None and g in used):
continue
trial = dict(mapping)
trial[a] = g
gain = match_count(test, gold, trial) - score
if gain > best_gain:
best_gain, best_move = gain, trial
for i in range(len(tvars)): # @line L4
for j in range(i + 1, len(tvars)):
a, b = tvars[i], tvars[j]
if mapping[a] == mapping[b]:
continue
trial = dict(mapping)
trial[a], trial[b] = mapping[b], mapping[a]
gain = match_count(test, gold, trial) - score
if gain > best_gain:
best_gain, best_move = gain, trial
if best_move is None: # @line L5
return score, mapping
mapping, score = best_move, score + best_gain # @line L6
def smatch_hill_climb(test, gold, restarts=4, seed=0):
"""Best (M, mapping) over one smart start and `restarts` random starts."""
rng = random.Random(seed)
best, best_map = climb(test, gold, smart_init(test, gold)) # @line L7
for _ in range(restarts): # @line L8
c, m = climb(test, gold, random_init(test, gold, rng))
if c > best: # @line L9
best, best_map = c, m
return best, best_map # @line L10
def prf(match, n_test, n_gold):
"""Precision, recall and F1 as Fractions; 0 when undefined."""
p = Fraction(match, n_test) if n_test else Fraction(0)
r = Fraction(match, n_gold) if n_gold else Fraction(0)
f = Fraction(2 * match, n_test + n_gold) if n_test + n_gold else Fraction(0)
return p, r, f
def smatch(test, gold, exact=False, restarts=4, seed=0):
"""Return (P, R, F) of the best mapping found."""
if exact:
m, _ = smatch_brute_force(test, gold)
else:
m, _ = smatch_hill_climb(test, gold, restarts, seed)
return prf(m, len(set(test)), len(set(gold)))
def corpus_smatch(pairs, exact=False, restarts=4, seed=0):
"""Corpus score: sum the matches and the triple counts over all pairs."""
total_m = total_t = total_g = 0
for test, gold in pairs:
if exact:
m, _ = smatch_brute_force(test, gold)
else:
m, _ = smatch_hill_climb(test, gold, restarts, seed)
total_m += m
total_t += len(set(test))
total_g += len(set(gold))
return prf(total_m, total_t, total_g)
def _tokens(text):
out = []
i = 0
while i < len(text):
c = text[i]
if c.isspace():
i += 1
elif c in "()/":
out.append(c)
i += 1
elif c == '"':
j = text.index('"', i + 1)
out.append(text[i : j + 1])
i = j + 1
else:
j = i
while j < len(text) and not text[j].isspace() and text[j] not in '()/"':
j += 1
out.append(text[i:j])
i = j
return out
def parse_penman(text, prefix=""):
"""Read one AMR in PENMAN notation and return its list of triples.
Variables get the prefix, so that two graphs can share no names. A role
that ends in "-of" (but not ":consist-of") is read as the inverse of the
role without it. Constants keep their quotes off.
"""
toks = _tokens(text)
pos = 0
triples = []
names = set()
def node():
nonlocal pos
assert toks[pos] == "("
var = prefix + toks[pos + 1]
assert toks[pos + 2] == "/"
concept = toks[pos + 3]
pos += 4
names.add(var)
triples.append(("instance", var, concept))
while toks[pos] != ")":
role = toks[pos]
assert role.startswith(":")
role = role[1:]
pos += 1
if toks[pos] == "(":
value = node()
is_var = True
else:
value = toks[pos].strip('"')
pos += 1
is_var = None
pending.append((role, var, value, is_var))
pos += 1
return var
pending = []
node()
for role, a, b, is_var in pending:
if is_var is None and prefix + b in names:
b = prefix + b
if role.endswith("-of") and role != "consist-of" and b in names:
triples.append((role[:-3], b, a))
else:
triples.append((role, a, b))
return triples
test_smatch.py 181 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/smatch/. The authors are listed in prov/SMYWR9.jsonl.
from fractions import Fraction
from itertools import permutations
from math import comb, perm
import random
from smatch import (
all_mappings,
climb,
corpus_smatch,
match_count,
parse_penman,
smart_init,
smatch,
smatch_brute_force,
smatch_hill_climb,
)
# The example of Cai and Knight 2013, section 2.
GOLD = parse_penman("(a / want-01 :ARG0 (b / boy) :ARG1 (c / go-01 :ARG0 b))")
TEST = parse_penman("(x / want-01 :ARG0 (y / boy) :ARG1 (z / football))")
def rand_graph(rng, nv, ne, concepts, roles, pre):
vs = [pre + str(i) for i in range(nv)]
t = [("instance", v, rng.choice(concepts)) for v in vs]
for _ in range(ne):
t.append((rng.choice(roles), rng.choice(vs), rng.choice(vs)))
if rng.random() < 0.5:
t.append(("polarity", rng.choice(vs), "-"))
return sorted(set(t))
def test_reader():
assert sorted(GOLD) == sorted([
("instance", "a", "want-01"),
("instance", "b", "boy"),
("instance", "c", "go-01"),
("ARG0", "a", "b"),
("ARG1", "a", "c"),
("ARG0", "c", "b"),
])
assert len(TEST) == 5
def test_reader_inverse_role_and_constant():
g = parse_penman('(b / boy :ARG0-of (w / want-01) :name (n / name :op1 "Ed") :polarity -)', "p.")
assert ("ARG0", "p.w", "p.b") in g
assert ("op1", "p.n", "Ed") in g
assert ("polarity", "p.b", "-") in g
def test_paper_table_of_six_mappings():
want = {
("a", "b", "c"): 4,
("a", "c", "b"): 1,
("b", "a", "c"): 0,
("b", "c", "a"): 0,
("c", "a", "b"): 0,
("c", "b", "a"): 2,
}
for images, m in want.items():
assert match_count(TEST, GOLD, dict(zip("xyz", images))) == m
def test_paper_score():
p, r, f = smatch(TEST, GOLD, exact=True)
assert (p, r, f) == (Fraction(4, 5), Fraction(2, 3), Fraction(8, 11))
assert round(float(f), 2) == 0.73
assert smatch(TEST, GOLD) == (p, r, f)
def test_identical_graphs_score_one():
g2 = parse_penman("(a / want-01 :ARG0 (b / boy) :ARG1 (c / go-01 :ARG0 b))", "g.")
assert smatch(GOLD, g2, exact=True)[2] == 1
assert smatch(GOLD, g2)[2] == 1
def test_symmetric_match_count():
rng = random.Random(1)
for _ in range(30):
a = rand_graph(rng, 3, 3, ["p", "q"], ["r", "s"], "t")
b = rand_graph(rng, 4, 4, ["p", "q"], ["r", "s"], "g")
assert smatch_brute_force(a, b)[0] == smatch_brute_force(b, a)[0]
def test_number_of_mappings():
# Injective partial maps from m variables to n variables.
for m in range(4):
for n in range(4):
got = sum(1 for _ in all_mappings(["t" + str(i) for i in range(m)], ["g" + str(i) for i in range(n)]))
assert got == sum(comb(m, k) * perm(n, k) for k in range(min(m, n) + 1))
got = sum(1 for _ in all_mappings(list("abcde"), list("ABCDE")))
assert got == 1546
def test_hill_climbing_stuck_at_local_maximum():
test = [("instance", "t0", "p"), ("instance", "t1", "q"), ("r", "t0", "t1")]
gold = [("instance", "g0", "q"), ("instance", "g1", "q"), ("r", "g0", "g1")]
start = smart_init(test, gold)
assert start == {"t0": None, "t1": "g0"}
assert climb(test, gold, start)[0] == 1
assert smatch_brute_force(test, gold)[0] == 2
assert match_count(test, gold, {"t0": "g0", "t1": "g1"}) == 2
def test_hill_climbing_never_exceeds_brute_force():
rng = random.Random(2)
for trial in range(60):
a = rand_graph(rng, 5, rng.randint(3, 7), ["p", "q", "r"], ["r", "s"], "t")
b = rand_graph(rng, rng.randint(3, 5), rng.randint(3, 7), ["p", "q", "r"], ["r", "s"], "g")
opt, best_map = smatch_brute_force(a, b)
got, mapping = smatch_hill_climb(a, b, restarts=1, seed=trial)
assert got <= opt
assert match_count(a, b, mapping) == got
assert match_count(a, b, best_map) == opt
def test_restarts_reach_the_optimum():
rng = random.Random(5)
cases = []
for _ in range(120):
a = rand_graph(rng, 4, rng.randint(2, 6), ["p", "q", "r"], ["r", "s"], "t")
b = rand_graph(rng, rng.randint(3, 5), rng.randint(2, 6), ["p", "q", "r"], ["r", "s"], "g")
cases.append((a, b, smatch_brute_force(a, b)[0]))
stuck_without = sum(smatch_hill_climb(a, b, restarts=0, seed=7)[0] < opt for a, b, opt in cases)
stuck_with = sum(smatch_hill_climb(a, b, restarts=20, seed=7)[0] < opt for a, b, opt in cases)
assert stuck_without > 0
assert stuck_with == 0
def test_corpus_score_sums_counts():
g2 = parse_penman("(w / want-01 :ARG0 (b / boy))", "g.")
t2 = parse_penman("(w / want-01 :ARG0 (b / girl))", "t.")
p, r, f = corpus_smatch([(TEST, GOLD), (t2, g2)], exact=True)
# Matches 4 + 2, test triples 5 + 3, gold triples 6 + 3.
assert (p, r, f) == (Fraction(6, 8), Fraction(6, 9), Fraction(12, 17))
mean_f = (smatch(TEST, GOLD, exact=True)[2] + smatch(t2, g2, exact=True)[2]) / 2
assert mean_f != f
def test_empty_graph():
assert smatch([], GOLD, exact=True) == (0, 0, 0)
def has_subgraph(h_edges, nh, g_edges, ng):
gset = set(g_edges) | {(v, u) for u, v in g_edges}
for images in permutations(range(ng), nh):
if all((images[u], images[v]) in gset for u, v in h_edges):
return True
return False
def graph_to_amr(edges, n, pre):
t = [("instance", pre + str(v), "node") for v in range(n)]
for u, v in edges:
t.append(("edge", pre + str(u), pre + str(v)))
t.append(("edge", pre + str(v), pre + str(u)))
return t
def test_reduction_from_subgraph_isomorphism():
# H is a subgraph of G iff the best match count is |V(H)| + 2 |E(H)|.
rng = random.Random(9)
seen = {True: 0, False: 0}
for _ in range(40):
nh, ng = 3, 4
all_h = [(u, v) for u in range(nh) for v in range(u + 1, nh)]
all_g = [(u, v) for u in range(ng) for v in range(u + 1, ng)]
h = [e for e in all_h if rng.random() < 0.6]
g = [e for e in all_g if rng.random() < 0.5]
best, _ = smatch_brute_force(graph_to_amr(h, nh, "h"), graph_to_amr(g, ng, "g"))
answer = has_subgraph(h, nh, g, ng)
assert (best == nh + 2 * len(h)) == answer
seen[answer] += 1
assert seen[True] > 0 and seen[False] > 0
triangle = [(0, 1), (1, 2), (0, 2)]
four_cycle = [(0, 1), (1, 2), (2, 3), (0, 3)]
assert smatch_brute_force(graph_to_amr(triangle, 3, "h"), graph_to_amr(four_cycle, 4, "g"))[0] < 9
History
Cai and Knight introduced Smatch in 2013, the year of the first AMR release by Banarescu and others, who used it to measure agreement between annotators. Cai and Knight wrote the triples, the F1 score and the integer program, and they made hill climbing with a smart start and four random restarts the practical method. Smatch became the standard metric for AMR parsing, and later work added fine-grained scores and exact or faster variants.
References
- Shu Cai and Kevin Knight, Smatch: an Evaluation Metric for Semantic Feature Structures, Section 2 (the triples, the example and the score), Section 3 (the integer program, hill climbing, smart initialization and restarts), Table 2 (accuracy and speed of the methods)
- Laura Banarescu et al., Abstract Meaning Representation for Sembanking, the PENMAN notation of AMR and the use of Smatch for agreement between annotators
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 SMYWR9 Edit this page History Report an error Markdown