Argumentation, Stance, and Persuasion › Implementation
Language AI HandbookAll chapters Everything below is deterministic, CPU-sized, and built on small synthetic data. The goal is to make each metric and each reporting convention concrete enough to reproduce by hand.
Setup
The book's plotting helpers and a few shared utilities. This cell is hidden because it contains no teaching content.
The Gold Argument Graph
We store each component as a character span. Offsets are computed from the surface string so the data stays readable.
PythonIn [8]Expand
DOCS = {
"d1": "We should close Central at 6pm and move the savings to a mobile van.",
"d2": "Late-evening checkout counts at Central average 11 visitors per hour, and a closing shift costs $180 per hour.",
"d3": "The checkout counts come from the circulation desk logs for January through March 2025.",
"d4": "The 11-visitor figure counts only people who check out materials, so it understates use of the study rooms.",
"d5": "The van would serve two neighborhoods that are more than a mile from any branch.",
"d6": "The board should not trust the van cost projections, since the same consultant produced the 2023 figures that were withdrawn.",
}
GOLD = [
(
"n1",
"d1",
"We should close Central at 6pm and move the savings to a mobile van",
"claim",
),
(
"n2",
"d2",
"Late-evening checkout counts at Central average 11 visitors per hour",
"premise",
),
("n3", "d2", "a closing shift costs $180 per hour", "premise"),
(
"n4",
"d3",
"the circulation desk logs for January through March 2025",
"evidence",
),
("n5", "d4", "counts only people who check out materials", "premise"),
(
"n6",
"d5",
"The van would serve two neighborhoods that are more than a mile from any branch",
"premise",
),
(
"n7",
"d6",
"the same consultant produced the 2023 figures that were withdrawn",
"premise",
),
]
GOLD_NODES = {}
for node_id, doc_id, surface, role in GOLD:
start = DOCS[doc_id].index(surface)
GOLD_NODES[node_id] = {
"id": node_id,
"doc": doc_id,
"start": start,
"end": start + len(surface),
"role": role,
"text": surface,
}
GOLD_EDGES = {
("n2", "n1", "support"),
("n3", "n1", "support"),
("n6", "n1", "support"),
("n4", "n2", "support"),
("n5", "n2", "attack"),
("n7", "n1", "attack"),
}ConsoleOut [9]Expand
n1 d1 [claim ] We should close Central at 6pm and move the savings to a mobile van n2 d2 [premise ] Late-evening checkout counts at Central average 11 visitors per hour n3 d2 [premise ] a closing shift costs $180 per hour n4 d3 [evidence] the circulation desk logs for January through March 2025 n5 d4 [premise ] counts only people who check out materials n6 d5 [premise ] The van would serve two neighborhoods that are more than a mile from any branch n7 d6 [premise ] the same consultant produced the 2023 figures that were withdrawn n2 --support--> n1 n3 --support--> n1 n4 --support--> n2 n5 --attack--> n2 n6 --support--> n1 n7 --attack--> n1
Seven components across six comments yield four support edges and two attack edges. The edges all point toward the same root, directly or through n2.
The Gold Graph, Drawn
VisualizationOut [10]Expand

Both support and attack edges lead toward the joint claim. The attack from n5 points to n2 in this node-only representation, standing in for an objection to the inference from checkout counts to evening demand.
Span Metrics
Three numbers per condition: precision, recall, and F1. Keep them in a dictionary so the reporting code stays uniform.
PythonIn [11]Expand
def prf(n_correct, n_pred, n_gold):
precision = n_correct / n_pred if n_pred else 0.0
recall = n_correct / n_gold if n_gold else 0.0
f1 = (
2 * precision * recall / (precision + recall)
if (precision + recall)
else 0.0
)
return {
"precision": precision,
"recall": recall,
"f1": f1,
"n_correct": n_correct,
"n_pred": n_pred,
"n_gold": n_gold,
}
def span_key(node):
return (node["doc"], node["start"], node["end"])
def score_spans(pred_nodes, gold_nodes):
gold_keys = {span_key(n) for n in gold_nodes}
pred_keys = {span_key(n) for n in pred_nodes}
correct = len(pred_keys & gold_keys)
return prf(correct, len(pred_keys), len(gold_keys))Spans are compared on (document, start, end) triples. Two spans that cover the same words but start one character later are different objects, which is the strict convention we discussed.
A Heuristic Extractor
The baseline uses regular expressions for claims and clause splitting for premises and evidence. Its errors illustrate what these rules can miss on this fixture.
PythonIn [12]Expand
CLAIM_RE = re.compile(
r"\b(?:we|i|the board|they)\s+should\b[^.,;]*", re.IGNORECASE
)
EVIDENCE_RE = re.compile(
r"\b(?:logs?|records?|reports?|data|survey)\b", re.IGNORECASE
)
NUMERIC_RE = re.compile(r"\$\s?\d+|\b\d+\b")
UNDERCUT_RE = re.compile(
r"\b(?:only|not|never|withdrawn|unknown|understates?|excludes?)\b",
re.IGNORECASE,
)
CONNECTORS = (
", so ",
", and ",
", but ",
", since ",
", because ",
" and ",
" but ",
" so ",
" since ",
" because ",
)
def split_clauses(text):
"""Split on connectives, returning (start, end, surface) with offsets intact."""
cuts = []
for con in CONNECTORS:
start = 0
while True:
i = text.find(con, start)
if i == -1:
break
cuts.append((i, i + len(con)))
start = i + len(con)
pieces, prev = [], 0
for a, b in sorted(cuts):
if a < prev:
continue
pieces.append((prev, a))
prev = b
pieces.append((prev, len(text)))
out = []
for a, b in pieces:
while b > a and text[b - 1] in " .,;":
b -= 1
while a < b and text[a] == " ":
a += 1
if b > a:
out.append((a, b, text[a:b]))
return out
def extract_spans(docs):
predicted = []
for doc_id, text in docs.items():
taken = []
for m in CLAIM_RE.finditer(text):
predicted.append(
{
"id": None,
"doc": doc_id,
"start": m.start(),
"end": m.end(),
"role": "claim",
"text": m.group(0),
}
)
taken.append((m.start(), m.end()))
for a, b, seg in split_clauses(text):
if any(a < e and s < b for s, e in taken):
continue
if EVIDENCE_RE.search(seg):
role = "evidence"
elif NUMERIC_RE.search(seg) or re.match(
r"(?:since|because)\b", seg, re.IGNORECASE
):
role = "premise"
else:
continue
predicted.append(
{
"id": None,
"doc": doc_id,
"start": a,
"end": b,
"role": role,
"text": seg,
}
)
for i, node in enumerate(predicted, start=1):
node["id"] = f"p{i}"
return predictedConsoleOut [13]Expand
p1 d1 [claim ] We should close Central at 6pm and move the savings to a mobile van p2 d2 [premise ] Late-evening checkout counts at Central average 11 visitors per hour p3 d2 [premise ] a closing shift costs $180 per hour p4 d3 [evidence] The checkout counts come from the circulation desk logs for January through March 2025 p5 d4 [premise ] The 11-visitor figure counts only people who check out materials p6 d6 [claim ] The board should not trust the van cost projections p7 d6 [premise ] the same consultant produced the 2023 figures that were withdrawn
Four of the seven predicted spans match exactly. They are the claim in d1, both premises in d2 and the consultant premise in d6. The d3 and d4 predictions expand the annotated boundaries, the extractor misses the d5 premise, and the board-trust clause in d6 is an extra predicted claim.
The d3 and d4 errors affect boundaries. Missing the premise in d5 reduces recall, while the extra claim span in d6 also changes the last claim available to the linker.
Relation Metrics
For a node without an attack cue, the linker tries to attach it to the latest claim. With an attack cue, it first tries the latest preceding span from the same document, then a preceding non-claim, then the latest claim. It emits no edge when it cannot choose a target.
PythonIn [14]Expand
DOC_ORDER = {doc_id: i for i, doc_id in enumerate(DOCS)}
def node_order(node):
return (DOC_ORDER[node["doc"]], node["start"])
def predict_relations(nodes):
"""Link each non-claim node to a target using shallow thread-level cues."""
ordered = sorted(nodes, key=node_order)
edges, claim_anchor, previous = set(), None, []
for node in ordered:
if node["role"] == "claim":
claim_anchor = node["id"]
previous.append(node)
continue
target = None
if UNDERCUT_RE.search(node["text"]):
same_doc = [n for n in previous if n["doc"] == node["doc"]]
non_claim = [n for n in previous if n["role"] != "claim"]
if same_doc:
target = same_doc[-1]["id"]
elif non_claim:
target = non_claim[-1]["id"]
elif claim_anchor:
target = claim_anchor
label = "attack"
else:
target = claim_anchor
label = "support"
if target is not None:
edges.add((node["id"], target, label))
previous.append(node)
return edges
def score_edges(pred_edges, gold_edges, pred_to_gold=None):
"""Strict edge scoring: precision counts every predicted edge."""
if pred_to_gold is None:
ids = {e[0] for e in pred_edges} | {e[1] for e in pred_edges}
pred_to_gold = {i: i for i in ids}
mapped = set()
for src, dst, rel in pred_edges:
g_src, g_dst = pred_to_gold.get(src), pred_to_gold.get(dst)
if g_src is None or g_dst is None:
continue
mapped.add((g_src, g_dst, rel))
correct = mapped & gold_edges
return prf(len(correct), len(pred_edges), len(gold_edges)), correct, mappedUnder the gold-component comparison, the mapping is the identity. End-to-end evaluation maps each predicted span to an exactly matching gold ID or to None.
Three Conditions, Three Numbers
PythonIn [15]Expand
# Condition A: relation identification with gold spans and roles supplied
gold_span_edges = predict_relations(list(GOLD_NODES.values()))
gold_span_score, gold_span_correct, gold_span_mapped = score_edges(
gold_span_edges, GOLD_EDGES
)
# Condition B: end-to-end, predicted spans and predicted relations
pred_edges = predict_relations(pred_nodes)
gold_lookup = {span_key(n): n["id"] for n in GOLD_NODES.values()}
pred_to_gold = {n["id"]: gold_lookup.get(span_key(n)) for n in pred_nodes}
end_to_end_score, end_to_end_correct, end_to_end_mapped = score_edges(
pred_edges, GOLD_EDGES, pred_to_gold
)
# Span identification on its own
span_score = score_spans(pred_nodes, list(GOLD_NODES.values()))
# Ceiling on end-to-end recall imposed by span errors alone
recovered = {g for g in pred_to_gold.values() if g is not None}
reachable_gold = {
e for e in GOLD_EDGES if e[0] in recovered and e[1] in recovered
}
span_ceiling = len(reachable_gold) / len(GOLD_EDGES)ConsoleOut [16]Expand
condition P R F1 span identification (exact) 0.571 0.571 0.571 relations, gold components 0.500 0.500 0.500 relations, end-to-end 0.400 0.333 0.364 gold edges whose endpoints were both recovered: 3 of 6 span ceiling on end-to-end recall: 0.500
Exact span identification has F1 of 0.571. The linker achieves F1 of 0.500 with gold spans and gold component roles and 0.364 with predicted spans and roles. The two relation rows use the same scoring rule, with different inputs to the linker.
Three of six gold edges have exactly recovered endpoints. The end-to-end linker recovers two of those three, leaving one eligible edge it could recover with the current spans. Raising recall beyond 0.500 also requires recovering more endpoints. The oracle changes both boundaries and roles, so the gap between the two relation F1 scores is not a span-only estimate.
Per-Type Metrics and the Averaging Convention
This graph has four support edges and two attack edges. Report both label scores so the reader can see how each contributes to the average.
PythonIn [17]Expand
def edge_prf_by_label(pred_edges, gold_edges, pred_to_gold=None):
labels = sorted({e[2] for e in gold_edges} | {e[2] for e in pred_edges})
rows = {}
for label in labels:
p = {e for e in pred_edges if e[2] == label}
g = {e for e in gold_edges if e[2] == label}
_, _, mapped = score_edges(p, g, pred_to_gold)
correct = mapped & g
rows[label] = prf(len(correct), len(p), len(g))
return rowsConsoleOut [18]Expand
relation identification with gold spans and roles label P R F1 tp pred gold attack 0.000 0.000 0.000 0 2 2 support 0.750 0.750 0.750 3 4 4 macro-F1 over 2 relation types: 0.375 micro-F1 (all relations pooled): 0.500
With gold inputs, the linker recovers three support edges and neither of the two attacks. It attaches n5 to n4 instead of n2 and n7 to n6 instead of n1. Both errors persist even when the linker receives the correct spans and component roles.
Support F1 is 0.750 and attack F1 is 0.000. The macro average gives the two types equal weight and comes to 0.375. Pooling all edge counts gives micro-F1 of 0.500, which reflects the greater number of support edges in this example.
What the Numbers Say
VisualizationOut [19]Expand

Only three gold edges have both endpoints recovered, so end-to-end recall can reach at most 0.500 with these spans. The plot reports F1, which combines precision and recall. The per-type table separately shows the zero attack F1 even with gold inputs.
A Target-Conditioned Stance Dataset
The 18 hand-authored (text, target) pairs use different comments from the six graph documents. They share the fictional Riverton scenario and the same two policy targets. Each row has a hand-labeled indicator of whether that text addresses its target. Both annotation policies use this indicator.
PythonIn [20]Expand
T1 = "close Central at 6pm"
T2 = "fund the mobile van"
STANCE_ROWS = [
(
"r01",
"Closing Central at 6pm is a mistake, and we should fund the mobile van because it is exactly the outreach the neighborhood needs.",
T1,
"against",
True,
),
(
"r02",
"Closing Central at 6pm is a mistake, and we should fund the mobile van because it is exactly the outreach the neighborhood needs.",
T2,
"favor",
True,
),
(
"r03",
"I can't support the van until we see the cost projections.",
T2,
"against",
True,
),
(
"r04",
"Late hours are the only time I can visit, so cutting them would shut me out.",
T1,
"against",
True,
),
(
"r05",
"I don't have a view on the van either way, but I'd rather the library kept its evening hours.",
T1,
"against",
True,
),
(
"r06",
"I don't have a view on the van either way, but I'd rather the library kept its evening hours.",
T2,
"neutral",
True,
),
(
"r07",
"The van serves the Eastside and Northgate neighborhoods, both over a mile from a branch.",
T2,
"neutral",
True,
),
(
"r08",
"Closing at 6pm would save $180 an hour, and that money buys a lot of van miles.",
T1,
"favor",
True,
),
(
"r09",
"Closing at 6pm would save $180 an hour, and that money buys a lot of van miles.",
T2,
"favor",
True,
),
(
"r10",
"I'm not against saving money, but not at the cost of the study rooms.",
T1,
"against",
True,
),
(
"r11",
"Anyone who thinks the van will fix access hasn't looked at the route map.",
T2,
"against",
True,
),
("r12", "Save the late hours.", T1, "against", True),
("r13", "The 2023 consultant report was withdrawn.", T1, "neutral", False),
(
"r14",
"The van's operating costs are unknown, so the proposal is premature.",
T2,
"against",
True,
),
(
"r15",
"Closing at 6pm is a painful cut that I support, because the building is falling apart.",
T1,
"favor",
True,
),
(
"r16",
"Great news, the board is cutting evening hours; now nobody can study at night.",
T1,
"against",
True,
),
(
"r17",
"The van is a good idea, and we should fund it, though its cost estimates are fiction.",
T2,
"favor",
True,
),
(
"r18",
"Why is no one asking about the staffing plan?",
T1,
"neutral",
False,
),
]Rows r01 and r02 are the same sentence annotated against two targets, with opposite labels. Rows r05 and r06 are the same sentence again, one target with a position and one explicitly without. Rows r13 and r18 are the two cases where the target is not addressed at all, and they are the rows whose treatment differs between policies.
A Target-Conditioned Baseline
The baseline matches target keywords, collects stance cues within a six-token window, and flips each cue's polarity when it finds a preceding negator within two tokens. A keyword match is the rule’s proxy for whether the text addresses that target.
PythonIn [21]Expand
TARGET_KEYWORDS = {
T1: [
"central",
"6pm",
"closing",
"close",
"evening",
"hours",
"late",
"cutting",
],
T2: [
"van",
"mobile",
"outreach",
"route",
"neighborhood",
"access",
"costs",
],
}
POSITIVE_CUES = {
"support",
"exactly",
"need",
"needs",
"good",
"worth",
"keep",
"save",
"yes",
"idea",
"right",
"great",
}
NEGATIVE_CUES = {
"mistake",
"oppose",
"wrong",
"premature",
"unknown",
"withdrawn",
"nobody",
"fiction",
"shut",
"painful",
"against",
}
NEGATORS = {
"not",
"no",
"never",
"cannot",
"can't",
"don't",
"doesn't",
"isn't",
"hasn't",
"without",
}
WINDOW = 6
TOKEN_RE = re.compile(r"[A-Za-z0-9$']+")
def tokenize_with_offsets(text):
return [
(m.group(0).lower(), m.start(), m.end())
for m in TOKEN_RE.finditer(text)
]
def target_hits(tokens, target):
keywords = TARGET_KEYWORDS[target]
return [
i
for i, (tok, _, _) in enumerate(tokens)
if any(kw in tok for kw in keywords)
]
def score_stance(text, target):
"""Return the integer cue score and whether a target keyword matched."""
tokens = tokenize_with_offsets(text)
hits = target_hits(tokens, target)
if not hits:
return 0, False
score = 0
for i, (tok, _, _) in enumerate(tokens):
if min(abs(i - h) for h in hits) > WINDOW:
continue
polarity = 0
if tok in POSITIVE_CUES:
polarity = 1
elif tok in NEGATIVE_CUES:
polarity = -1
if polarity == 0:
continue
preceding = [t for t, _, _ in tokens[max(0, i - 2) : i]]
if any(w in NEGATORS for w in preceding):
polarity = -polarity
score += polarity
return score, True
def predict_label(text, target):
score, has_target_hit = score_stance(text, target)
if not has_target_hit:
return "neutral", "no-evidence", score
if score > 0:
return "favor", "favor", score
if score < 0:
return "against", "against", score
return "neutral", "neutral", scoreConsoleOut [22]Expand
id target score gold pred text r01 close Central at 6pm -1 against against Closing Central at 6pm is a mistake, and we should f r02 fund the mobile van 1 favor favor Closing Central at 6pm is a mistake, and we should f r03 fund the mobile van -1 against against I can't support the van until we see the cost projec r04 close Central at 6pm -1 against against Late hours are the only time I can visit, so cutting r05 close Central at 6pm 0 against neutral x I don't have a view on the van either way, but I'd r r06 fund the mobile van 0 neutral neutral I don't have a view on the van either way, but I'd r r07 fund the mobile van 0 neutral neutral The van serves the Eastside and Northgate neighborho r08 close Central at 6pm 1 favor favor Closing at 6pm would save $180 an hour, and that mon r09 fund the mobile van 0 favor neutral x Closing at 6pm would save $180 an hour, and that mon r10 close Central at 6pm 0 against neutral x I'm not against saving money, but not at the cost of r11 fund the mobile van 0 against neutral x Anyone who thinks the van will fix access hasn't loo r12 close Central at 6pm 1 against favor x Save the late hours. r13 close Central at 6pm 0 neutral neutral The 2023 consultant report was withdrawn. r14 fund the mobile van -1 against against The van's operating costs are unknown, so the propos r15 close Central at 6pm -1 favor against x Closing at 6pm is a painful cut that I support, beca r16 close Central at 6pm 0 against neutral x Great news, the board is cutting evening hours; now r17 fund the mobile van 2 favor favor The van is a good idea, and we should fund it, thoug r18 close Central at 6pm 0 neutral neutral Why is no one asking about the staffing plan?
Read the x rows carefully, because each one is a lesson rather than a bug.
- r05 ("I'd rather the library kept its evening hours") is predicted neutral. The stance is expressed by a comparative construction, not by a cue word, so the window never sees a polarity.
- r09 is predicted neutral. The cue save is ten or more tokens from the target van and therefore outside the six-token window. The relation between the savings and the van depends on interpreting that money.
- r10 is predicted neutral because no keyword matches T1. The target is implied by the study rooms, and the scorer has no bridging.
- r11 is predicted neutral. The target keyword is present, but the selected window does not yield a nonzero cue score. The intended opposition depends on the implication of the challenge about the route map.
- r12 ("Save the late hours") is predicted favor because save is positive. The cue is positive, but it applies to preserving the hours, which is a stance against closing. The target framing, not the word, determines the sign.
- r15 is predicted against. The selected window includes painful. The word support is seven tokens away from the nearest target hit and falls beyond the six-token window.
- r16 is predicted neutral because great and nobody cancel.
The errors on this fixed set illustrate missing target keywords, cues beyond the window, polarity that depends on target framing, and irony.
Label-Wise Metrics and Two Averaging Conventions
PythonIn [23]Expand
def label_metrics(gold, pred, labels):
rows = {}
for label in labels:
tp = sum(1 for g, p in zip(gold, pred) if g == label and p == label)
n_pred = sum(1 for p in pred if p == label)
n_gold = sum(1 for g in gold if g == label)
rows[label] = prf(tp, n_pred, n_gold)
return rows
def print_stance_report(rows, gold_key, pred_key, labels, title):
gold = [r[gold_key] for r in rows]
pred = [r[pred_key] for r in rows]
metrics = label_metrics(gold, pred, labels)
print(title)
print(
f"{'label':10s} {'P':>6s} {'R':>6s} {'F1':>6s} {'tp':>5s} {'gold':>5s} {'pred':>5s}"
)
for label in labels:
m = metrics[label]
print(
f"{label:10s} {m['precision']:6.3f} {m['recall']:6.3f} {m['f1']:6.3f} "
f"{m['n_correct']:5d} {m['n_gold']:5d} {m['n_pred']:5d}"
)
macro = float(np.mean([metrics[l]["f1"] for l in labels]))
official = float(
np.mean([metrics["favor"]["f1"], metrics["against"]["f1"]])
)
acc = sum(1 for g, p in zip(gold, pred) if g == p) / len(gold)
print(
f"accuracy {acc:.3f} | macro-F1 over {len(labels)} labels {macro:.3f} "
f"| favor/against average {official:.3f}\n"
)
return metrics, macro, officialConsoleOut [24]Expand
Policy A: three labels, both targets pooled (n=18) label P R F1 tp gold pred favor 0.750 0.600 0.667 3 5 4 against 0.800 0.444 0.571 4 9 5 neutral 0.444 1.000 0.615 4 4 9 accuracy 0.611 | macro-F1 over 3 labels 0.618 | favor/against average 0.619 Policy B: gold-addressed rows, both targets pooled (n=16) label P R F1 tp gold pred favor 0.750 0.600 0.667 3 5 4 against 0.800 0.444 0.571 4 9 5 neutral 0.333 1.000 0.500 2 2 6 accuracy 0.562 | macro-F1 over 3 labels 0.579 | favor/against average 0.619 addressed prevalence 0.889 | prediction coverage 0.833 | abstentions 3 | abstention precision 0.667
The reports share a cue scorer. Policy A maps the two unaddressed rows into the gold neutral class. Policy B excludes those rows from its stance table and keeps any false abstention on a gold-addressed row as a miss. Of the 18 input pairs, the system issues 15 predictions and abstains on three. Two of those three abstentions match gold NO-EVIDENCE.
Both reports pool the two targets. The Policy B table uses all 16 gold-addressed pairs, including false abstentions, so its F1 describes performance on the addressed reference subset. Coverage measures how often the system issues a stance label across all 18 inputs. If an evaluation scores only issued predictions instead, report that denominator and the coverage separately.
The three-label and two-label averages happen to be close under Policy A. The two-label average leaves out a standalone neutral F1. Any neutral row predicted as favor or against can still lower the corresponding label’s precision.
VisualizationOut [26]Expand

Of the nine gold-against examples, four receive a neutral prediction, one receives a favor prediction and four receive the correct label. The against recall is four ninths.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!