Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
docs(417): regenerate the threshold gating example from a real run
The Result Structure block and the Unmatched Items scenario in
threshold-gated-evaluation.md did not match what the page's own example
produces. With three products on each side, Hungarian matching pairs
Cable with New Product as an FD at 0.133, so there is no FN or FA, and
the Mouse pair scores 0.6725. Show the example inputs, replace the block
with the real counts and non_matches, retitle the heading over the
0.7999999999999999 pair, and say when an item is left unmatched. The
Laptop test now runs the whole example, plus the FN and FA cases.

Scope the docstrings in hungarian.py, base.py and the algorithms README
to the gates listed in Meeting a Threshold, and use
ThresholdHelper.is_below_threshold for the explain() verdict.
  • Loading branch information
Thanatos9404 committed Oct 20, 2026
commit 0d971cab6739174a8de6581808872c50636339bd
73 changes: 46 additions & 27 deletions docs/docs/Advanced/threshold-gated-evaluation.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,21 @@ class Order(StructuredModel):

Given three GT products and three Pred products:

### Good Match (similarity >= 0.8)
```python
gt = Order(order_id="ORD-1", products=[
Product(product_id="PROD-001", name="Laptop", price=999.99),
Product(product_id="PROD-002", name="Mouse", price=29.99),
Product(product_id="PROD-003", name="Cable", price=14.99),
])
pred = Order(order_id="ORD-1", products=[
Product(product_id="PROD-001", name="Laptop Computer", price=999.99),
Product(product_id="PROD-002", name="Different Product", price=99.99),
Product(product_id="PROD-004", name="New Product", price=19.99),
])
result = gt.compare_with(pred, include_confusion_matrix=True, document_non_matches=True)
```

### Good Match (meets 0.8)

**GT:** `Product("PROD-001", "Laptop", 999.99)`
**Pred:** `Product("PROD-001", "Laptop Computer", 999.99)`
Expand All @@ -107,49 +121,54 @@ Given three GT products and three Pred products:
**GT:** `Product("PROD-002", "Mouse", 29.99)`
**Pred:** `Product("PROD-002", "Different Product", 99.99)`

- Similarity: `(3 * 1.0 + 2 * 0.118 + 1 * 0.8) / 6`, about `0.6725`
- Classification: **FD**
- No nested field analysis -- the objects are too dissimilar for field-level breakdown to be useful.

### Unmatched Items
### Weak Pairing

**GT:** `Product("PROD-003", "Cable", 14.99)` -- **FN** (no counterpart in Pred)
**Pred:** `Product("PROD-004", "New Product", 19.99)` -- **FA** (no counterpart in GT)
**GT:** `Product("PROD-003", "Cable", 14.99)`
**Pred:** `Product("PROD-004", "New Product", 19.99)`

No nested analysis for either.
- Similarity: `0.1333`
- Classification: **FD**, with no nested analysis

Hungarian matching pairs every item when both lists have the same length, so
these two are paired even though they share almost nothing. An item is left
unmatched only when one list is longer: without `New Product` in Pred, `Cable`
would be an **FN**, and without `Cable` in GT, `New Product` would be an **FA**.
Neither is broken down into fields.

## Result Structure

The `products` counts and the `non_matches` from the run above, with other keys
left out and scores rounded to four places:

```json
{
"products": {
"confusion_matrix": { "fields": { "products": {
"overall": {
"tp": 1, "fd": 1, "fn": 1, "fa": 1,
"derived": { "cm_precision": 0.5, "cm_recall": 0.5, "cm_f1": 0.5 }
"tp": 1, "fd": 2, "fn": 0, "fa": 0,
"derived": { "cm_precision": 0.3333, "cm_recall": 1.0, "cm_f1": 0.5 }
},
"fields": {
"product_id": { "tp": 1 },
"name": { "fd": 1 },
"price": { "tp": 1 }
},
"non_matches": [
{ "type": "FD", "field_path": "products[0].name", "similarity": 0.4 },
{
"type": "FD",
"gt_object": "Product(PROD-002, Mouse, 29.99)",
"pred_object": "Product(PROD-002, Different Product, 99.99)",
"similarity": 0.3
},
{ "type": "FN", "gt_object": "Product(PROD-003, Cable, 14.99)" },
{ "type": "FA", "pred_object": "Product(PROD-004, New Product, 19.99)" }
]
}
"product_id": { "overall": { "tp": 1 } },
"name": { "overall": { "fd": 1 } },
"price": { "overall": { "tp": 1 } }
}
} } },
"non_matches": [
{ "field_path": "products[0].name", "non_match_type": "false_discovery", "similarity_score": 0.4 },
{ "field_path": "products[1]", "non_match_type": "false_discovery", "similarity_score": 0.6725 },
{ "field_path": "products[2]", "non_match_type": "false_discovery", "similarity_score": 0.1333 }
]
}
```

Field-level metrics appear only for the single TP pair, and its `name` is the
only leaf in `non_matches`. That list documents every other FD, FN, and FA once
at object level; `field_comparisons` uses the same boundary. Neither report
expands a rejected or unmatched object into leaves.
only leaf in `non_matches`. That list documents each rejected pair once at
object level, as it would an FN or FA; `field_comparisons` uses the same
boundary. Neither report expands a rejected or unmatched object into leaves.

## Delegation Pattern

Expand Down
6 changes: 4 additions & 2 deletions src/stickler/algorithms/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,10 @@ purpose and reads only `matched_pairs`. Nothing should read `tp` from a
matcher built with `0.0`.

**The threshold test is `ThresholdHelper.is_above_threshold`**, the one every
evaluator gate uses. It accepts a score up to `1e-10` under the threshold, so a
float rounding error does not turn a TP into an FD
classification gate listed in
[Meeting a Threshold](https://awslabs.github.io/stickler/Getting-Started/thresholds-and-metrics/#meeting-a-threshold)
uses. It accepts a score up to `1e-10` under the threshold, so a float rounding
error does not turn a TP into an FD
([#417](https://github.com/awslabs/stickler/issues/417)).

## How the evaluator uses it
Expand Down
5 changes: 3 additions & 2 deletions src/stickler/algorithms/hungarian.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,8 +290,9 @@ def calculate_metrics(self, list1: Any, list2: Any) -> dict:
as ``cm_recall`` there.

The threshold test is ``ThresholdHelper.is_above_threshold``, the
one every evaluator gate uses. It accepts a score up to ``1e-10``
under the threshold, so ``0.7 + 0.1`` against ``0.8`` is a TP.
one every classification gate listed in Meeting a Threshold uses.
It accepts a score up to ``1e-10`` under the threshold, so
``0.7 + 0.1`` against ``0.8`` is a TP.

``match_threshold=0.0`` is used elsewhere as a capture all
sentinel. Every score satisfies ``>= 0.0``, so ``tp`` then counts
Expand Down
2 changes: 1 addition & 1 deletion src/stickler/auto/facade.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def explain(self) -> Dict[str, Dict[str, Any]]:
score == 0.0
and raw_sim
and threshold is not None
and raw_sim < threshold
and ThresholdHelper.is_below_threshold(raw_sim, threshold)
):
entry["verdict"] = (
f"raw {raw_sim:.2f} < threshold {threshold} -> clipped to 0.0"
Expand Down
4 changes: 2 additions & 2 deletions src/stickler/comparators/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,8 +241,8 @@ def binary_compare(self, str1: Any, str2: Any) -> Tuple[int, int]:
based on the threshold. If the similarity meets the threshold, it returns
(1, 0) indicating true positive. Otherwise, it returns (0, 1) indicating
false positive. The test is ``ThresholdHelper.is_above_threshold``, the
one every evaluator gate uses, so a score less than ``1e-10`` under the
threshold meets it.
one every classification gate listed in Meeting a Threshold uses, so a
score less than ``1e-10`` under the threshold meets it.

Args:
str1: First value
Expand Down
55 changes: 47 additions & 8 deletions tests/structured_object_evaluator/test_threshold_tolerance.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,8 @@ def test_reports_agree_with_the_counts(self, score, matches):
else:
assert _comparison_rows(result) == {"items[0]": False}

def test_the_documented_laptop_pair_is_a_true_positive(self):
"""The Good Match scenario in ``threshold-gated-evaluation.md``."""
def test_the_documented_worked_example(self):
"""The scenarios and result block in ``threshold-gated-evaluation.md``."""

class Product(StructuredModel):
product_id: str = ComparableField(
Expand All @@ -215,19 +215,58 @@ class Product(StructuredModel):
match_threshold = 0.8

class Order(StructuredModel):
order_id: str = ComparableField(
comparator=ExactComparator(), threshold=1.0, weight=2.0
)
products: List[Product] = ComparableField(weight=3.0)

gt = Product(product_id="PROD-001", name="Laptop", price=999.99)
pred = Product(product_id="PROD-001", name="Laptop Computer", price=999.99)
assert gt.compare(pred) == NEAR
gt = [
Product(product_id="PROD-001", name="Laptop", price=999.99),
Product(product_id="PROD-002", name="Mouse", price=29.99),
Product(product_id="PROD-003", name="Cable", price=14.99),
]
pred = [
Product(product_id="PROD-001", name="Laptop Computer", price=999.99),
Product(product_id="PROD-002", name="Different Product", price=99.99),
Product(product_id="PROD-004", name="New Product", price=19.99),
]
assert gt[0].compare(pred[0]) == NEAR

def run(gt_items, pred_items):
return _full_result(
Order(order_id="ORD-1", products=gt_items),
Order(order_id="ORD-1", products=pred_items),
)

result = _full_result(Order(products=[gt]), Order(products=[pred]))
result = run(gt, pred)
products = result["confusion_matrix"]["fields"]["products"]
assert _counts(products) == (1, 0)
overall = products["overall"]
assert [overall[key] for key in ("tp", "fd", "fn", "fa")] == [1, 2, 0, 0]
assert overall["derived"]["cm_precision"] == pytest.approx(1 / 3)
assert overall["derived"]["cm_recall"] == 1.0
assert overall["derived"]["cm_f1"] == pytest.approx(0.5)
assert _counts(products["fields"]["product_id"]) == (1, 0)
assert _counts(products["fields"]["name"]) == (0, 1)
assert _counts(products["fields"]["price"]) == (1, 0)
assert _non_match_paths(result) == ["products[0].name"]
assert [
(entry["field_path"], entry["non_match_type"], round(entry["similarity_score"], 4))
for entry in result["non_matches"]
] == [
("products[0].name", "false_discovery", 0.4),
("products[1]", "false_discovery", 0.6725),
("products[2]", "false_discovery", 0.1333),
]

# Only lists of different lengths leave an item unmatched.
for gt_items, pred_items, kind, counts in (
(gt, pred[:2], "false_negative", [1, 1, 1, 0]),
(gt[:2], pred, "false_alarm", [1, 1, 0, 1]),
):
result = run(gt_items, pred_items)
overall = result["confusion_matrix"]["fields"]["products"]["overall"]
assert [overall[key] for key in ("tp", "fd", "fn", "fa")] == counts
last = result["non_matches"][-1]
assert (last["field_path"], last["non_match_type"]) == ("products[2]", kind)


class TestListSubFieldGate:
Expand Down