Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
26 changes: 26 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,32 @@ Each release links to full notes on the
([#322](https://github.com/awslabs/stickler/issues/322)). See
[`None` elements in a list](https://awslabs.github.io/stickler/Advanced/classification-logic/#none-elements-in-a-list)

- **Breaking:** a score that floating-point arithmetic leaves just under its
threshold now gets the same verdict at every classification gate. A
primitive list element allowed a `1e-10` tolerance, but a field, a nested
model, a `List[StructuredModel]` pair, `EvalResult.matched` and
`binary_compare()` used a bare `>=`. The Laptop pair in the threshold-gating
docs scores `0.7999999999999999` against `match_threshold = 0.8`, so it was an
FD and was not descended into, while the same score on a `List[str]` element
was a TP. Each of these now uses `ThresholdHelper.is_above_threshold`. A score
up to `1e-10` under its threshold:
- counts as a TP instead of an FD, in the confusion matrix, `non_matches` and
`field_comparisons`, for a field, a nested model, a list item's sub-field and
a list pair;
- keeps its score instead of being clipped to `0.0`, so `field_scores` and
`overall_score` can rise, and `ComparisonInfo.compare()` and
`ComparableFieldConfig.compare()` return it;
- opens a list pair for field-by-field evaluation;
- sets `EvalResult.matched`, makes `BaseComparator.binary_compare()` return
`(1, 0)`, and counts as a TP in `HungarianMatcher.calculate_metrics` and the
`evaluator_format=True` fallback metrics.

A score further under the threshold is unchanged, and so is a primitive list
element. `ANLSStarComparator`'s `leaf_threshold` and the bounding-box
`iou_thresholds` are separate metrics and keep their exact comparison
([#417](https://github.com/awslabs/stickler/issues/417)). See
[Meeting a Threshold](https://awslabs.github.io/stickler/Getting-Started/thresholds-and-metrics/#meeting-a-threshold)

- **Breaking:** `evaluator_format=True` output carries `non_matches` only
with `document_non_matches=True`, as the default `compare_with()` dict does,
so `result["non_matches"]` without it now raises `KeyError`. It always wrote
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/API-Reference/auto.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ above:
| `recall` | `float` | `cm_recall` |
| `f1` | `float` | `cm_f1` |
| `accuracy` | `float` | `cm_accuracy` |
| `matched` | `bool` | `overall_score >= match_threshold`. A convenience roll-up, not a per-field guarantee: individual fields can be below their thresholds while `matched` is `True`. Read `field_scores` or the confusion matrix for that. |
| `matched` | `bool` | `overall_score >= match_threshold` (see [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold)). A convenience roll-up, not a per-field guarantee: individual fields can be below their thresholds while `matched` is `True`. Read `field_scores` or the confusion matrix for that. |
| `confusion_matrix` | `dict` | The full confusion-matrix subtree |
| `raw` | `dict` | The unmodified `compare_with()` result |

Expand Down
6 changes: 3 additions & 3 deletions docs/docs/Advanced/classification-logic.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ False Alarm (FA) and False Discovery (FD) together make up the broader False Pos
Lists use the [Hungarian algorithm](hungarian-matching.md) for optimal element pairing.

1. **Empty lists**: `[] vs []` is TN; `[] vs [items]` produces one FA per item; `[items] vs []` produces one FN per item.
2. **Matched elements**: similarity >= threshold is TP; below threshold is FD.
2. **Matched elements**: similarity >= threshold is TP; below threshold is FD. See [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold).
3. **Unmatched elements**: leftover GT elements are FN; leftover EST elements are FA.
4. **`None` elements**: absent, so they are not matched or counted. A list of only `None` is an empty list. See [`None` elements in a list](#none-elements-in-a-list).

Expand Down Expand Up @@ -97,7 +97,7 @@ Result: TP=0, FA=0, FN=0, FD=3

### Nested Objects

Nested objects are evaluated recursively, field by field.
Nested objects are evaluated recursively, field by field, with `>=` as described in [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold).

| Condition | Classification |
|-----------|---------------|
Expand Down Expand Up @@ -194,7 +194,7 @@ These are computed at every node of the result tree, from that node's own counts

**TN in object matching** -- A TN is absence of evidence, not evidence of a match. Fields absent on both sides are excluded from the weighted object similarity used by Hungarian matching. If every field is absent, the similarity is defined as `1.0`.

**Threshold boundary** -- A similarity score exactly equal to the threshold counts as a match (TP).
**Threshold boundary** -- A similarity score exactly equal to the threshold counts as a match (TP). So does a score less than `1e-10` under it, at every gate listed in [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold), so a rounding error such as `0.7 + 0.1` (`0.7999999999999999`) against `0.8` does not turn a TP into an FD.

**List order** -- Order does not matter. The Hungarian algorithm finds the optimal pairing regardless of element position.

Expand Down
4 changes: 2 additions & 2 deletions docs/docs/Advanced/hungarian-matching.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ The Hungarian algorithm solves the assignment problem in O(n^3) time, producing

### 3. Threshold-Gated Classification

Each matched pair is classified using `StructuredModel.match_threshold`:
Each matched pair is classified using `StructuredModel.match_threshold`, with `>=` as described in [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold):

| Condition | Classification | Nested analysis? |
|-----------|---------------|-----------------|
Expand Down Expand Up @@ -195,7 +195,7 @@ The threshold for Hungarian classification comes from the element model's `match
### Recursion Gating

```
IF object_similarity >= match_threshold:
IF object_similarity meets match_threshold:
classification = TP
recurse into nested field analysis
ELSE:
Expand Down
82 changes: 52 additions & 30 deletions docs/docs/Advanced/threshold-gated-evaluation.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,64 +90,85 @@ 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)`

- Similarity: `(3 * 1.0 + 2 * 0.4 + 1 * 1.0) / 6`, which floating point evaluates to `0.7999999999999999`. It meets `0.8` through the [rounding tolerance](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold).
- Classification: **TP**
- Nested field analysis is performed:
- `product_id`: TP (exact match)
- `name`: TP (similarity ~0.9)
- `name`: FD (Levenshtein similarity 0.4, under its 0.7 threshold)
- `price`: TP (exact match)

### Poor Match (similarity < 0.8)

**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": { "tp": 1 },
"price": { "tp": 1 }
},
"non_matches": [
{
"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. The `non_matches` list
documents each FD, FN, and FA once at object level; `field_comparisons` uses the
same boundary. Neither report expands a rejected or unmatched object into
leaves.
Field-level metrics appear only for the single TP pair, and its `name` is the
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 Expand Up @@ -203,15 +224,16 @@ field's own `threshold` decides that verdict. See

`overall_score` is the scalar summary, and `EvalResult.matched` from
`stickler.evaluate()` is the object-level verdict
(`overall_score >= match_threshold`).
(`overall_score >= match_threshold`, see
[Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold)).

For the raw object similarity used by Hungarian matching, fields absent on both sides are omitted from both totals. They remain TNs in the confusion matrix, but do not help a pair clear `match_threshold`. If no fields remain, the similarity is defined as `1.0`, because nothing disagreed.

## Edge Cases

**Empty lists** -- `[] vs []` is TN. `[] vs [items]` generates one FA per item. `[items] vs []` generates one FN per item.

**Threshold boundary** -- `similarity >= threshold` counts as TP and triggers recursion. Values exactly at the boundary are matches.
**Threshold boundary** -- `similarity >= threshold` counts as TP and triggers recursion. Values exactly at the boundary are matches, and so are values less than `1e-10` under it, so a rounding error does not flip the verdict. See [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold).

**Different thresholds per model** -- Each `StructuredModel` subclass can define its own `match_threshold`. A `Product` with `match_threshold = 0.8` and an `Address` with `match_threshold = 0.6` are each evaluated independently.

Expand Down
6 changes: 3 additions & 3 deletions docs/docs/Getting-Started/Contributing/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,14 +211,14 @@ The source header documents preserved behavioral bugs:

#### Threshold-Gated Recursion Internals

Field-level detail is only generated for object pairs with `similarity >= match_threshold`. Poor matches are treated as atomic failures without recursive field analysis. This is both a correctness decision (poor matches don't have meaningful field-level breakdowns) and a performance optimization.
Field-level detail is only generated for object pairs with `similarity >= match_threshold` (see [Meeting a Threshold](../thresholds-and-metrics.md#meeting-a-threshold)). Poor matches are treated as atomic failures without recursive field analysis. This is both a correctness decision (poor matches don't have meaningful field-level breakdowns) and a performance optimization.

```python
# See: structured_list_comparator.py:243-249
# See: structured_list_comparator.py:245-249
good_matched_pairs = [
(gt_idx, pred_idx, similarity)
for gt_idx, pred_idx, similarity in matched_pairs
if similarity >= match_threshold
if ThresholdHelper.is_above_threshold(similarity, match_threshold)
]
```

Expand Down
6 changes: 5 additions & 1 deletion docs/docs/Getting-Started/thresholds-and-metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class Invoice(StructuredModel):

**What it gates:**

- **TP vs FD classification:** If `similarity >= threshold`, the field is a True Positive. Otherwise, it's a False Discovery.
- **TP vs FD classification:** If `similarity >= threshold` (see [Meeting a Threshold](#meeting-a-threshold)), the field is a True Positive. Otherwise, it's a False Discovery.
- **Score clipping:** When `clip_under_threshold=True` (the default), scores below the threshold are zeroed out in the weighted average.

**Default:** `0.5`
Expand Down Expand Up @@ -129,6 +129,10 @@ Field threshold → threshold named on the comparator → `0.5`.

A comparator's *default* threshold is not part of that chain. `LevenshteinComparator()` does not contribute its 0.7, because those defaults were chosen for `binary_compare()` and were never audited as classification cutoffs. `DateComparator` is the clearest case: it defaults to `1.0` while awarding `0.7` partial credit for a match with no year, so adopting its default would clip its own feature to zero.

## Meeting a Threshold

A score meets its threshold when it is at or above it, or less than `1e-10` under it. The allowance absorbs floating-point rounding: `0.7 + 0.1` is `0.7999999999999999`, which meets `0.8`, while `0.8 - 1e-9` does not. Field, list element and list pair classification, score clipping, recursion into a list pair, `EvalResult.matched` and `binary_compare()` all use this one test, `ThresholdHelper.is_above_threshold`, so wherever these docs write `similarity >= threshold` they mean it. `ANLSStarComparator`'s `leaf_threshold` and the bounding-box `iou_thresholds` are separate metrics and keep their exact comparison.

---

## Metrics Glossary
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/Guides/Evaluation/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ When defining a `StructuredModel` subclass in Python, each field is declared wit

See the [Comparators](../Comparators/README.md) section for the complete list and detailed descriptions.

**`threshold`** -- Acts as a binary classification cutoff. A similarity score at or above the threshold counts as a True Positive; below it counts as a False Discovery. Choose stricter thresholds (0.9--1.0) for critical fields and looser thresholds (0.5--0.7) for flexible fields.
**`threshold`** -- Acts as a binary classification cutoff. A similarity score at or above the threshold counts as a True Positive; below it counts as a False Discovery. See [Meeting a Threshold](../../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold). Choose stricter thresholds (0.9--1.0) for critical fields and looser thresholds (0.5--0.7) for flexible fields.

**`weight`** -- Controls how much a field contributes to the overall score. The overall score is computed as:

Expand Down
2 changes: 1 addition & 1 deletion docs/docs/Guides/Evaluation/understanding-results.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ Maps each field name to its similarity score (0.0 to 1.0). For nested objects, t

### Asking whether anything failed

`overall_score` is the scalar summary, and for a single object-level verdict `stickler.evaluate()` returns an `EvalResult` whose `matched` attribute is `overall_score >= match_threshold`.
`overall_score` is the scalar summary, and for a single object-level verdict `stickler.evaluate()` returns an `EvalResult` whose `matched` attribute is `overall_score >= match_threshold` (see [Meeting a Threshold](../../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold)).

To ask whether anything at all went wrong, read **both** rollup nodes, because they scope different things:

Expand Down
27 changes: 15 additions & 12 deletions src/stickler/algorithms/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,17 +63,20 @@ the method was returning that same pair inside `matched_pairs`. The fix reaches
only this class, so it says nothing about how `anls_score` treats a low score
pair; that runs through `trees/list_tree.py`.

## Two traps worth knowing before reading `tp`
## Before reading `tp`

**`match_threshold=0.0` is a capture all sentinel, not a threshold.** The test
is a bare `>=`, so every score satisfies zero and `tp` counts pairs rather than
true positives. `ComparisonHelper.compare_unordered_lists` builds a matcher
this way on purpose and reads only `matched_pairs`. Nothing should read `tp`
from a matcher built with `0.0`.
**`match_threshold=0.0` is a capture all sentinel, not a threshold.** Every
score satisfies zero, so `tp` counts pairs rather than true positives.
`ComparisonHelper.compare_unordered_lists` builds a matcher this way on
purpose and reads only `matched_pairs`. Nothing should read `tp` from a
matcher built with `0.0`.

**The threshold test here is exact.** `ThresholdHelper` and `ComparisonHelper`
accept a score up to `1e-10` under the threshold, so a score inside that window
is a TP there and an FD here.
**The threshold test is `ThresholdHelper.is_above_threshold`**, the one every
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 All @@ -86,9 +89,9 @@ themselves:
| `ComparisonHelper.compare_unordered_lists` | hands them to `unordered_list_metrics`, which counts against its own `classification_threshold` |
| `ComparisonHelperBase.get_optimal_assignments` | provides pairings for direct report-helper calls; `compare_with` reports instead reuse the scoring pass's pairings |

`unordered_list_metrics` uses the same derivation as `calculate_metrics`, so the
two agree on what a count means. The remaining difference is the tolerant
threshold test noted above.
`unordered_list_metrics` uses the same derivation and the same threshold test as
`calculate_metrics`, so for the same pairs and threshold the two return the same
counts.

Because these callers do not read the counts, a change to how `calculate_metrics`
classifies cannot move an evaluator score. It is a public API in its own right
Expand Down
Loading
Loading