diff --git a/CHANGELOG.md b/CHANGELOG.md index 58f57afc..e6714105 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -240,6 +240,38 @@ Each release links to full notes on the `match_threshold` overrides the element class's for list pairing; on a `StructuredModel` it sets only `EvalResult.matched`. Scoring is unchanged ([#484](https://github.com/awslabs/stickler/issues/484)) +- The list contract is stated once, as a table in `classification-logic.md` + (pairing, bar, counts, recursion, score, reports), and other pages link to + it instead of restating it. Scoring is unchanged. Claims corrected against + measured output: + - A list declared without `ComparableField` pairs against the class + `match_threshold` (`0.7` unless set), not `0.5`. + - A list field's element order does not matter, but a nested list element + is compared as one value, and on the zero-config path it must match + exactly, order included. + - On a plain pydantic class, the runtime `match_threshold` of `evaluate()` + and `eval_for()` also sets `List[Model]` and `List[dict]` pairing and the + threshold of nested plain-model and `dict` fields, while a primitive list + keeps its inferred threshold. On a `StructuredModel` class it sets only + `matched`, and a `List[StructuredModel]` field pairs at the element + class's own `match_threshold` on either path + ([#416](https://github.com/awslabs/stickler/issues/416)). The docstrings + now say TP/FD, not TP/FN/FA. + - `clip_under_threshold` has no effect on `List[StructuredModel]`, so an FD + pair keeps its score, a known defect + ([#415](https://github.com/awslabs/stickler/issues/415)). + - `clip_under_threshold` defaults to off, not on, for dict and plain-model + fields and lists of them on a `StructuredModel` declared in Python. With + `x-aws-stickler-infer-unspecified`, an inferred JSON Schema property takes + its clip setting from inference, which is off for a free-form object and a + free-text string, rather than always `true`. + - `aggregate` leaves out FN and FA items beside an accepted sibling, and a + field `threshold` on `List[StructuredModel]` raises `ValueError`. + - A primitive list element row's `weighted_score` in `field_comparisons` is + its raw similarity, unweighted. Rows inside list items are described as + they are today ([#418](https://github.com/awslabs/stickler/issues/418)). + - The Hungarian matching example shows measured counts and the list score, + and its result block is checkable. - Amount examples no longer present a field threshold as rounding tolerance for `NumericComparator`. It scores 1.0 or 0.0, so the README, Best Practices, Evaluation and IDP Accelerator examples now set `absolute_tolerance=0.01` (or diff --git a/docs/docs/Advanced/aggregate-metrics.md b/docs/docs/Advanced/aggregate-metrics.md index 7a533294..0071d8ad 100644 --- a/docs/docs/Advanced/aggregate-metrics.md +++ b/docs/docs/Advanced/aggregate-metrics.md @@ -9,7 +9,7 @@ Stickler automatically includes an `aggregate` field at every node in the confus ## Key Features - **Automatic** -- Every node gets an `aggregate` field, with no per-field configuration. -- **Hierarchical** -- Parent nodes sum metrics from all child primitive fields, except where a list's items were all rejected and the node reports object rows instead ([why](#aggregate-counts-objects-for-an-all-rejected-list)). +- **Hierarchical** -- Parent nodes sum metrics from all child primitive fields, except where a list's items were all rejected and the node reports object rows instead ([why](#aggregate-counts-objects-for-an-all-rejected-list)). In a list of models only accepted (TP) items contribute leaves, so an unmatched FN or FA item beside an accepted sibling appears on `overall` only ([Recursion](classification-logic.md#list-contract)). - **Consistent** -- The same access pattern works at every level: `result['confusion_matrix']['aggregate']` or `result['confusion_matrix']['fields']['contact']['aggregate']`. - **Derived metrics included** -- Each aggregate contains precision, recall, F1, and accuracy. @@ -142,7 +142,10 @@ Coinciding is not evidence that nothing was hidden, which is the separate and mo has **no child field nodes at all**. `AggregateMetricsCalculator` decides leaf versus parent on exactly that -- whether `fields` has any entries -- so such a node is treated as a leaf and its `aggregate` becomes a copy of its own - `overall`: one row per rejected item. The **unit of the count changes with the + `overall`: one row per rejected item. The same holds for any list with no + accepted item, so its FN and FA items count here as object rows too; beside an + accepted sibling they are left out of `aggregate` (with two-field items, + `[A, B]` vs `[A]` reads `overall tp=1 fn=1`, `aggregate tp=2`). The **unit of the count changes with the data**. This is decided per node, and needs only that one list's items to be rejected -- not the whole document: diff --git a/docs/docs/Advanced/classification-logic.md b/docs/docs/Advanced/classification-logic.md index 2dd27438..c78a4647 100644 --- a/docs/docs/Advanced/classification-logic.md +++ b/docs/docs/Advanced/classification-logic.md @@ -36,12 +36,20 @@ False Alarm (FA) and False Discovery (FD) together make up the broader False Pos ### Lists -Lists use the [Hungarian algorithm](hungarian-matching.md) for optimal element pairing. +#### The list contract {: #list-contract } -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. 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). +This table is the single statement of how Stickler treats a list field. Other pages link here rather than restate it. The Known gaps note under it lists where the code does not yet follow it. + +| Aspect | Rule | +|---|---| +| Pairing | A list field's elements are paired one-to-one by the [Hungarian algorithm](hungarian-matching.md), maximising total similarity, so their order does not matter: `["a", "b"]` vs `["b", "a"]` scores `1.0`. An element that is itself a list (`List[List[str]]`) is compared as one whole value, so order inside it does count. On the zero-config path (`stickler.evaluate()` on a plain pydantic class) that inner list, and a list held in an `Any` field, must match exactly, order included. `None` and `NaN` elements are removed first ([`None` elements in a list](#none-elements-in-a-list)); reports keep original indices. Pair similarity is the field's comparator, or `GT[i].compare(Pred[j])` for `List[StructuredModel]` (fields absent on both sides excluded). | +| Bar | `List[StructuredModel]`: the element class's `match_threshold`; a runtime `match_threshold` does not change it. A field `threshold` there raises `ValueError` in Python, and JSON Schema ignores it. Primitive, dict and plain-model lists on a `StructuredModel` declared in Python: the field's `threshold`, else a threshold named on the comparator, else `0.5` when declared with `ComparableField()`, or the class `match_threshold` (`0.7` unless set) when declared without it (`tags: List[str]`). JSON Schema and the zero-config path have their own defaults ([JSON Schema](../Guides/Evaluation/README.md#extension-reference), [zero-config](../Getting-Started/thresholds-and-metrics.md#4-runtime-match-threshold)). A pair that [meets](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold) the bar is a TP. | +| Counts (the list node's `overall`) | Paired element: TP if it meets the bar, else FD. Unpaired GT element: FN. Unpaired prediction: FA. An empty, `None` or all-`None` list is null: both null is one TN (score `1.0`); one side null gives one FN or FA per present element (score `0.0`). | +| Recursion | Only TP pairs of `StructuredModel` items are descended into. FD, FN and FA items are atomic. `aggregate` holds the leaves of TP items only, so FD, FN and FA items are left out of it when any sibling was accepted. With no accepted item it falls back to the list node's own counts ([why](aggregate-metrics.md#aggregate-counts-objects-for-an-all-rejected-list)). | +| Score | `sum(pair scores) / max(n_gt, n_pred)`, never clipped as a whole against a field threshold. For primitive, dict and plain-model lists the pair score is the element similarity, zeroed below the bar when `clip_under_threshold` is on. On a `StructuredModel` declared in Python it defaults to on for primitive lists and off for dict and plain-model lists. JSON Schema and the zero-config path have their own defaults ([JSON Schema](../Guides/Evaluation/README.md#extension-reference), [zero-config](../API-Reference/auto.md#inference)). For `List[StructuredModel]` the pair score is `GT[i].compare_with(Pred[j])["overall_score"]`, which applies each field's own threshold and can differ from the pairing similarity. Currently `clip_under_threshold` has no effect there, so an FD pair keeps its score: a known gap. [Worked example](hungarian-matching.md#step-4-list-score). | +| Reports | `field_comparisons`: one row per element of a primitive, dict or plain-model list, whatever its classification (a dict or plain-model element is not expanded into its keys or fields); for `List[StructuredModel]`, one row per leaf of a TP item and one object row per FD, FN or FA item. `non_matches` has the same rows, but only the FD, FN and FA ones. A `field_comparisons` row's `match` is true when its own classification is TP or TN: a value or object row met its bar; a list row had every element paired as a TP, with no FD, FA or FN at the element level. Failures deeper down get their own rows. | + +**Known gaps.** Four behaviours are defects, not the contract: `clip_under_threshold` having no effect on `List[StructuredModel]`; inside a list item, a `field_comparisons` row reporting the clipped `score`, and a nested list or object getting one row; a `None` list being reported differently from `[]` in `field_comparisons` (one row for the whole field against a non-empty list, and one row against another `None`, where every other pair of null lists, such as `[]` vs `[]`, gets none); and inside a list item, the cases listed under **Nested lists** below counting differently than at top level. #### `None` elements in a list {: #none-elements-in-a-list } @@ -214,7 +222,7 @@ neither term. The mixed-matching example above scores recall `1.000` even though `0.667`. `HungarianMatcher.calculate_metrics` always uses that second formula. See [FD and recall](hungarian-matching.md#fd-and-recall). -These are computed at every node of the result tree, from that node's own counts, and which counts those are depends on which node you read. `overall` classifies that node's direct children: for a list field, whether each pairing was genuine or spurious; at the root, its own fields, which means the two units can mix in a single count. `aggregate` gives leaf detail, and for a list of objects that means only the items that were comparable, since a list item below the element class's `match_threshold` is one FD and is not descended into. A single nested `StructuredModel` field is not gated this way: its leaves are always reported. See [Which node answers which question](aggregate-metrics.md#which-node-answers-which-question). +These are computed at every node of the result tree, from that node's own counts, and which counts those are depends on which node you read. `overall` classifies that node's direct children: for a list field, whether each pairing was genuine or spurious; at the root, its own fields, which means the two units can mix in a single count. `aggregate` gives leaf detail, and for a list of objects that means only the items that were comparable, since a list item below the element class's `match_threshold` is one FD and is not descended into; unmatched FN and FA items are left out too when a sibling was accepted ([Recursion](#list-contract)). A single nested `StructuredModel` field is not gated this way: its leaves are always reported. See [Which node answers which question](aggregate-metrics.md#which-node-answers-which-question). ## Edge Cases @@ -224,9 +232,9 @@ These are computed at every node of the result tree, from that node's own counts **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. +**List order** -- The order of a list field's elements does not matter. The Hungarian algorithm finds the optimal pairing regardless of element position. A nested list element is compared as one whole value ([Pairing](#list-contract)). -**Nested lists** -- For `List[StructuredModel]`, the Hungarian algorithm pairs objects at the list level, then each matched pair is evaluated recursively: every field the ground-truth element's class declares is classified by the same dispatcher as a top-level field, so it follows the rules on this page. A field annotated as a model, a list, or an `Optional` model or union of models, such as `Optional[Inner]`, `List[str]`, `Optional[Union[A, B]]` or `Union[A, B, List[str]]`, goes to the dispatcher directly. Any other field, such as `Any`, `object`, `Union[A, B]`, `Sequence[str]` or `Optional[Annotated[Inner, Field(...)]]`, is read by its value first. If the classes in one list annotate a field differently, the first matched ground-truth element that declares it decides which, or, when the list's first element is not matched, each pair's own class does. These cases are counted differently from top level: +**Nested lists** -- For `List[StructuredModel]`, the Hungarian algorithm pairs objects at the list level, then each TP pair is evaluated recursively ([Recursion](#list-contract)): every field the ground-truth element's class declares is classified by the same dispatcher as a top-level field, so it follows the rules on this page. A field annotated as a model, a list, or an `Optional` model or union of models, such as `Optional[Inner]`, `List[str]`, `Optional[Union[A, B]]` or `Union[A, B, List[str]]`, goes to the dispatcher directly. Any other field, such as `Any`, `object`, `Union[A, B]`, `Sequence[str]` or `Optional[Annotated[Inner, Field(...)]]`, is read by its value first. If the classes in one list annotate a field differently, the first matched ground-truth element that declares it decides which, or, when the list's first element is not matched, each pair's own class does. These cases are counted differently from top level: - A field the predicted element's class does not declare (an extra field) is not counted, where at top level it adds an FA to the root `overall`. - In a field read by value, a model of another class than the ground truth's is one TP or FD, from the ground-truth model's `compare_with()` score against the field's threshold, and `aggregate` counts it the same way rather than per field. That score reads a field the prediction lacks as `None`, so `Search(query="hotels")` against `Browse(url="x.com")` scores `0.0` and is an FD. A ground-truth field left `None` matches the missing one, so `Inner(a="x", b=None)` against `Other(c="z")` scores `0.5`, from `b`, and is a TP at the default threshold of `0.5`. It scores only the ground truth's own fields, so `Pet(name="tom")` against its subclass `Cat(name="tom", lives=9)` scores `1.0` and is a TP, as the warning under [Objects of different classes](#objects-of-different-classes) says. A field that goes to the dispatcher directly counts such a pair as top level does. diff --git a/docs/docs/Advanced/hungarian-matching.md b/docs/docs/Advanced/hungarian-matching.md index 61116ef0..78f26629 100644 --- a/docs/docs/Advanced/hungarian-matching.md +++ b/docs/docs/Advanced/hungarian-matching.md @@ -165,27 +165,55 @@ The Hungarian algorithm produces: Because the lists are equal length, every element gets paired. Only the TP pair (GT[0] -> Pred[0]) receives field-level analysis; the FD pairs are treated as atomic mismatches. +### Step 4: List Score + +The list's score is the sum of the pair scores over the longer list's length ([Score](classification-logic.md#list-contract)). For `List[StructuredModel]` a pair's score is `GT[i].compare_with(Pred[j])["overall_score"]`, which applies each field's threshold, so it can differ from the pairing similarity in Step 1: + +| Pair | Pairing similarity | Pair score | +|------|-------------------|-----------| +| GT[0] -> Pred[0] | 0.860 | 0.667 (`description` 0.579 is below 0.7, so it contributes 0.0) | +| GT[1] -> Pred[1] | 0.572 | 0.500 | +| GT[2] -> Pred[2] | 0.124 | 0.000 | + +`field_scores["transactions"]` = (0.667 + 0.5 + 0.0) / 3 = **0.3889**, and the account scores (2 x 1.0 + 3 x 0.3889) / 5 = 0.6333. + ### Result Structure ```python -"transactions": { - "overall": { - "tp": 1, "fd": 2, "fa": 0, "fn": 0, "fp": 2 - }, - "fields": { - # Only from the TP pair (GT[0] -> Pred[0]) - "transaction_id": {"tp": 1, "fd": 0, "fa": 0, "fn": 0}, - "description": {"tp": 1, "fd": 0, "fa": 0, "fn": 0}, - "amount": {"tp": 1, "fd": 0, "fa": 0, "fn": 0} - } +gt = Account(account_id="ACC-1", transactions=[ + Transaction(transaction_id="TXN-001", description="Coffee shop payment", amount=4.95), + Transaction(transaction_id="TXN-002", description="Grocery store", amount=127.43), + Transaction(transaction_id="TXN-003", description="Gas station", amount=45.67), +]) +pred = Account(account_id="ACC-1", transactions=[ + Transaction(transaction_id="TXN-001", description="Coffee shop", amount=4.95), + Transaction(transaction_id="TXN-002", description="Online purchase", amount=89.99), + Transaction(transaction_id="TXN-004", description="Restaurant", amount=23.45), +]) +result = gt.compare_with(pred, include_confusion_matrix=True) +result["confusion_matrix"]["fields"]["transactions"] +``` + +With other keys left out, the counts are: + +```json +{ + "overall": { "tp": 1, "fd": 2, "fa": 0, "fn": 0, "fp": 2 }, + "fields": { + "transaction_id": { "overall": { "tp": 1, "fd": 0, "fa": 0, "fn": 0 } }, + "description": { "overall": { "tp": 0, "fd": 1, "fa": 0, "fn": 0 } }, + "amount": { "overall": { "tp": 1, "fd": 0, "fa": 0, "fn": 0 } } + } } ``` +The `fields` counts come only from the TP pair (GT[0] -> Pred[0]). A TP pair can still hold a failing leaf: the pair cleared `match_threshold`, and its `description` (0.579) did not clear its own `threshold` of 0.7. + ## Key Architectural Principles ### Threshold Source -The threshold for Hungarian classification comes from the element model's `match_threshold` class attribute (default 0.7). It is **not** taken from the `ComparableField` on the parent list field. +The threshold for Hungarian classification comes from the element model's `match_threshold` class attribute (default 0.7). It is **not** taken from the `ComparableField` on the parent list field: `ComparableField(threshold=...)` on a `List[StructuredModel]` raises `ValueError` in Python, and `x-aws-stickler-threshold` on an array of models is ignored. ### Metric Separation diff --git a/docs/docs/Advanced/threshold-gated-evaluation.md b/docs/docs/Advanced/threshold-gated-evaluation.md index a55f4c71..67a4a768 100644 --- a/docs/docs/Advanced/threshold-gated-evaluation.md +++ b/docs/docs/Advanced/threshold-gated-evaluation.md @@ -133,10 +133,11 @@ result = gt.compare_with(pred, include_confusion_matrix=True, document_non_match - 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**. +Once `None` elements are removed, 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 @@ -189,7 +190,7 @@ The dispatcher uses pattern matching on null states for early exits, then routes Scores percolate upward from leaf fields to the top-level result using weighted averaging: 1. Each field comparison produces a raw similarity score (0.0 -- 1.0). -2. The score is optionally clipped to 0 if below the field threshold (`clip_under_threshold`). +2. The score is optionally clipped to 0 if below the field threshold (`clip_under_threshold`). A list field follows the [Score](classification-logic.md#list-contract) rule of the list contract instead. 3. Clipped scores are multiplied by the field weight and summed. 4. The overall similarity is `total_weighted_score / total_weight`. diff --git a/docs/docs/Getting-Started/Contributing/architecture.md b/docs/docs/Getting-Started/Contributing/architecture.md index 3b59855d..d28308a7 100644 --- a/docs/docs/Getting-Started/Contributing/architecture.md +++ b/docs/docs/Getting-Started/Contributing/architecture.md @@ -232,7 +232,7 @@ Every field comparison produces three score variants: | Score | Description | |-------|-------------| -| `raw_similarity_score` | Unclipped score (0.0–1.0). On a list node it is the coverage-scaled mean of the matched pairs' unclipped scores, `sum(pair scores) / max(len(gt), len(pred))`, which is what `compare()` returns for the field. On a `List[StructuredModel]` each pair's score is the item's own `overall_score`, so it is still clipped inside each item. No score or count reads it. `EvalResult.explain()` shows it (`raw_similarity`, `verdict`) for each top-level field. On a scalar field it also decides `match` in `field_comparisons`, the label confidence metrics score against, and gives an FD non-match record its similarity and reason | +| `raw_similarity_score` | Unclipped score (0.0–1.0). On a list node it is the coverage-scaled mean of the matched pairs' unclipped scores, `sum(pair scores) / max(len(gt), len(pred))`, which is what `compare()` returns for the field. On a `List[StructuredModel]` each pair's score is the item's own `overall_score`, so it is still clipped inside each item. No score or count reads it. `EvalResult.explain()` shows it (`raw_similarity`, `verdict`) for each top-level field. On a scalar field it also decides `match` in `field_comparisons`, the label confidence metrics score against, and gives an FD non-match record its similarity and reason (see [Score](../../Advanced/classification-logic.md#list-contract)) | | `similarity_score` | Maintained for API compatibility. Equal to `raw_similarity_score` on a scalar or nested model, and to `threshold_applied_score` on a list node | | `threshold_applied_score` | Raw score with `clip_under_threshold` applied (0.0 if below threshold and clipping is enabled). The score: `field_scores` and `overall_score` read it | @@ -248,7 +248,7 @@ Weights are configured per-field via `ComparableField` metadata. Default weight ### `clip_under_threshold` -When enabled on a field (the default), a score below the threshold contributes 0.0 instead of its partial similarity. This holds for **every** field kind; the layer that applies it differs. +When enabled on a field, a score below the threshold contributes 0.0 instead of its partial similarity. On a `StructuredModel` declared in Python it is on by default, except on dict and plain-model fields and lists of them. JSON Schema and the zero-config path have their own defaults ([JSON Schema](../../Guides/Evaluation/README.md#extension-reference), [zero-config](../../API-Reference/auto.md#inference)). It holds for every field kind except `List[StructuredModel]`, where it currently has no effect, a known gap (see the warning below); the layer that applies it differs. For a primitive or a single nested `StructuredModel`, `FieldComparator` clips when producing `threshold_applied_score`, and the engine's percolation loop uses the already-clipped score: diff --git a/docs/docs/Getting-Started/thresholds-and-metrics.md b/docs/docs/Getting-Started/thresholds-and-metrics.md index 00aaf249..e3f611f6 100644 --- a/docs/docs/Getting-Started/thresholds-and-metrics.md +++ b/docs/docs/Getting-Started/thresholds-and-metrics.md @@ -39,7 +39,7 @@ class Invoice(StructuredModel): **What it gates:** - **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. +- **Score clipping:** When `clip_under_threshold=True` (the default, except on dict and plain-model fields), scores below the threshold are zeroed out in the weighted average. A list field follows the [Score](../Advanced/classification-logic.md#list-contract) rule of the list contract instead. **Default:** `0.5` @@ -65,16 +65,16 @@ class LineItem(StructuredModel): ### 4. Runtime Match Threshold -**What it is:** The `match_threshold` parameter passed to `evaluate()` or `EvalSpec`. +**What it is:** The `match_threshold` parameter passed to `evaluate()` or `eval_for()`. ```python result = stickler.evaluate(gt, pred, match_threshold=0.8) -# Or via EvalSpec +# Or compile a reusable EvalSpec spec = stickler.eval_for(Invoice, match_threshold=0.8) ``` -**What it gates:** The document-level `EvalResult.matched` verdict (`overall_score >= match_threshold`). On a `StructuredModel` class that is all it does: field thresholds, list element pairing and every score keep their class values. On a plain pydantic class, the model `evaluate()` builds from it also uses the value as the field threshold of its `dict`, `List[dict]` and single nested-model fields, and for element pairing in its lists of plain models. A `List[StructuredModel]` field keeps the element class's `match_threshold`. It never changes a similarity score. +**What it gates:** The document-level `EvalResult.matched` verdict (`overall_score >= match_threshold`). On a `StructuredModel` class that is all it does: field thresholds, list element pairing and every score keep their class values. On a plain pydantic class (the zero-config path) it also decides TP vs FD for `List[Model]` and `List[dict]` elements at every nesting level, and sets the field threshold of nested plain-model and `dict` fields. A `List[StructuredModel]` field keeps the element class's `match_threshold`, and a primitive list keeps the threshold inferred from its element type and field name (`0.7` for `tags: List[str]`, `0.6` for `notes: List[str]`). It never changes a similarity score or `overall_score`. **Default:** the class's `match_threshold` on a `StructuredModel`, else `0.7` @@ -86,22 +86,27 @@ When multiple thresholds could apply, here's which one wins: |-----------|------------------------| | **Primitive field comparison** (str, int, float, and date, datetime, time, timedelta, Decimal, UUID, Enum) | Field threshold (`ComparableField(threshold=...)`), else a threshold named on the comparator | | **Nested object comparison** | Recurses into fields; each field uses its own field threshold | -| **List element pairing** (`List[StructuredModel]`) | The element class's `match_threshold` | -| **Score clipping** | Field threshold (when `clip_under_threshold=True`) | +| **List element pairing** (`List[StructuredModel]`) | The element class's `match_threshold`; a runtime value does not override it | +| **List element pairing** (zero-config `List[BaseModel]` and `List[dict]`) | Runtime match threshold if provided, else `0.7` | +| **List element pairing** (primitive, dict, plain-model lists on a `StructuredModel`) | Field threshold, else a threshold named on the comparator, else `0.5` with `ComparableField()` or the class `match_threshold` without it ([Bar](../Advanced/classification-logic.md#list-contract)) | +| **Score clipping** | Field threshold (when `clip_under_threshold=True`); lists follow the [Score](../Advanced/classification-logic.md#list-contract) rule | | **Binary classification (TP/FD)** for primitives | Field threshold | -| **Binary classification (TP/FD)** for list pairs | The element class's `match_threshold` | +| **Binary classification (TP/FD)** for list pairs | The list element pairing bar above | | **Document `matched` verdict** | Runtime match threshold if provided, else the class's `match_threshold` on a `StructuredModel`, else `0.7` | ### Key Rules 1. **Field threshold** controls primitive-level TP/FD classification and score clipping. -2. **Match threshold** on the element class controls object-level TP/FD classification for list matching. -3. **Runtime match threshold** sets the `matched` verdict. On a `StructuredModel` it reaches nothing else. +2. **Match threshold** on the element class controls object-level TP/FD classification for `List[StructuredModel]` matching. Other lists use the pairing bars in the table above. +3. **Runtime match threshold** sets the `matched` verdict. On a `StructuredModel` it reaches nothing else. On the zero-config path it also sets the `List[Model]` and `List[dict]` pairing bar and the threshold of nested plain-model and `dict` fields, but a `List[StructuredModel]` field still pairs at the element class's own `match_threshold`. 4. **Comparator threshold** fills in for the field threshold when the field does not set one. A threshold on the field always wins, and a comparator's own default is never adopted. ### Example: All Four in Action ```python +from typing import List + +import stickler from stickler import StructuredModel, ComparableField, LevenshteinComparator class Product(StructuredModel): @@ -115,15 +120,18 @@ class Product(StructuredModel): class Order(StructuredModel): products: List[Product] = ComparableField(weight=2.0) +gt_order = Order(products=[Product(name="Wireless Mouse")]) +pred_order = Order(products=[Product(name="Wireless Mice")]) # similarity 0.786 + # (4) Runtime match threshold - gates result.matched only result = stickler.evaluate(gt_order, pred_order, match_threshold=0.8) ``` In this example: -- `name` similarity is compared against **0.8** (field threshold) for TP/FD -- Product pairs are compared against **0.75** (`Product.match_threshold`) for list matching; the runtime 0.8 does not replace it -- `result.matched` is `overall_score >= 0.8` (runtime threshold) +- `name` (0.786) is compared against **0.8** (field threshold): FD +- The Product pair (0.786) is compared against **0.75** (`Product.match_threshold`): TP. The runtime 0.8 does not replace it. +- `result.matched` is `overall_score >= 0.8` (runtime threshold). `overall_score` is `0.0`, because `name` is clipped below its 0.8, so `matched` is `False`. - The comparator's **0.5** is overridden by the field's **0.8**. Drop `threshold=0.8` from the field and the comparator's 0.5 governs instead. ### Precedence, in one line @@ -404,10 +412,11 @@ Hungarian algorithm pairs: | SKU-C, "Widget Gamma" | SKU-X, "New Item" | 0.083 | < 0.7 | **FD** → atomic | Both lists hold three items, so the Hungarian algorithm pairs every one of them and -no item is left over. **FN and FA are impossible for an equal-length list** -- +no item is left over. **FN and FA are impossible for an equal-length list** with +no `None` elements, which are removed before pairing -- `SKU-C` does not go missing, it gets paired with the only prediction left, scores `0.083`, and lands below `match_threshold` as a false discovery. Unmatched items -appear only when the two lists differ in length. +appear only when the two lists differ in length once `None` elements are removed. Within each matched pair that *meets* the threshold, the fields (sku, description) are evaluated and contribute to the aggregate counts. A below-threshold pair is @@ -447,7 +456,7 @@ Recall (with FD) = TP / (TP + FN + FD) = 5 / (5 + 1 + 1) = 0.714 | Comparator | `Comparator(threshold=...)` | TP/FD and clipping when the field sets no threshold; `binary_compare()` | varies, and a default is not adopted | | Field | `ComparableField(threshold=...)` | TP/FD for primitives, clipping | 0.5 | | Model | `match_threshold = ...` on class | Hungarian pairing of its instances, bare-field default, `matched` verdict | 0.7 | -| Runtime | `evaluate(..., match_threshold=...)` | `matched` verdict only (on a `StructuredModel`) | class `match_threshold`, else 0.7 | +| Runtime | `evaluate(..., match_threshold=...)` | `matched` verdict only on a `StructuredModel`; on the zero-config path also `List[Model]` and `List[dict]` pairing and nested plain-model and `dict` field thresholds | class `match_threshold`, else 0.7 | ### Metric Formulas diff --git a/docs/docs/Guides/Best-Practices/README.md b/docs/docs/Guides/Best-Practices/README.md index 08208a68..31f3570d 100644 --- a/docs/docs/Guides/Best-Practices/README.md +++ b/docs/docs/Guides/Best-Practices/README.md @@ -189,7 +189,7 @@ result = ground_truth.compare_with( | Threshold too high | Many fields classified as non-matches | Lower the threshold to match acceptable variation | | Threshold too low | Poor matches classified as matches | Raise the threshold to enforce stricter matching | | Missing weights on critical fields | Overall score does not reflect business impact | Add weights proportional to field importance | -| Not using Hungarian matching | List items compared positionally instead of optimally | Use `List[StructuredModel]` type annotation for list fields | +| Expecting list order to matter | `[a, b]` vs `[b, a]` scores 1.0 | A list field's elements are Hungarian-paired regardless of order ([list contract](../../Advanced/classification-logic.md#list-contract)); put the position in the data, such as a `line_number` field | --- diff --git a/docs/docs/Guides/Evaluation/README.md b/docs/docs/Guides/Evaluation/README.md index babbaac3..094d9d83 100644 --- a/docs/docs/Guides/Evaluation/README.md +++ b/docs/docs/Guides/Evaluation/README.md @@ -51,7 +51,7 @@ When defining a `StructuredModel` subclass in Python, each field is declared wit | `comparator` | `BaseComparator` | `LevenshteinComparator()` | The comparison algorithm to use. See [Comparators](../Comparators/README.md) for the full list. | | `threshold` | `float` (0.0--1.0) | `0.5` | Minimum similarity score required for a field to be classified as a match. | | `weight` | `float` (> 0.0) | `1.0` | Relative importance of this field when computing aggregate scores. | -| `clip_under_threshold` | `bool` | `True` | When `True`, scores below `threshold` are zeroed out before contributing to the weighted average. | +| `clip_under_threshold` | `bool` | `True` (`False` on dict and plain-model fields and lists of them) | When `True`, scores below `threshold` are zeroed out before contributing to the weighted average. List fields follow the [Score](../../Advanced/classification-logic.md#list-contract) rule of the list contract. | ### How Each Parameter Affects Scoring @@ -74,7 +74,7 @@ overall_score = sum(field_score * weight) / sum(weights) Fields with higher weights pull the overall score toward their individual result. At the dataset level, `BulkStructuredModelEvaluator.compute()` exposes this weight-aware aggregate as `metrics["weighted_overall_score"]` -- prefer it over `cm_f1` when weights are non-uniform, since `cm_f1` treats every field-match equally. See [Weighted Overall Score](bulk-evaluation.md#weighted-overall-score) in the bulk-evaluation guide. -**`clip_under_threshold`** -- When enabled (the default), a field that scores below its threshold contributes 0.0 to the weighted average instead of its partial similarity. This prevents low-confidence matches from inflating the overall score. +**`clip_under_threshold`** -- When enabled (the default, except on dict and plain-model fields), a field that scores below its threshold contributes 0.0 to the weighted average instead of its partial similarity. This prevents low-confidence matches from inflating the overall score. A list field follows the [Score](../../Advanced/classification-logic.md#list-contract) rule of the list contract instead. ### Example Model @@ -186,12 +186,12 @@ Add these extensions to any property in your JSON Schema to control comparison b | Extension | Type | Default | Purpose | |-----------|------|---------|---------| | `x-aws-stickler-comparator` | string | Type-dependent | Comparison algorithm (e.g., `"ExactComparator"`, `"LevenshteinComparator"`) | -| `x-aws-stickler-threshold` | number (0.0--1.0) | see below | Match classification cutoff. Read on a scalar, an object, and an array of scalars. **Ignored on an array of models** -- an array whose `items` declare `properties` -- where pairing is gated by the element class's `x-aws-stickler-match-threshold`, and a declared value warns there. Read, not ignored, on an array of free-form `{"type": "object"}` items | +| `x-aws-stickler-threshold` | number (0.0--1.0) | see below | Match classification cutoff. Read on a scalar, an object, and an array of scalars. **Ignored on an array of models** -- an array whose `items` declare `properties` -- where pairing is gated by the element class's `x-aws-stickler-match-threshold`, and a declared value warns there (in Python, `ComparableField(threshold=...)` on a `List[StructuredModel]` raises `ValueError`). Read, not ignored, on an array of free-form `{"type": "object"}` items | | `x-aws-stickler-weight` | number (> 0.0) | 1.0 | Field importance multiplier | -| `x-aws-stickler-clip-under-threshold` | boolean | `true` | Zero out scores below threshold | +| `x-aws-stickler-clip-under-threshold` | boolean | `true` | Zero out scores below threshold. An inferred property takes it from inference (see below) | | `x-aws-stickler-model-name` | string | `"DynamicModel"` | Name of the generated Python class (root level) | | `x-aws-stickler-match-threshold` | number (0.0--1.0) | 0.7 | Model-level matching threshold for Hungarian algorithm (root level) | -| `x-aws-stickler-infer-unspecified` | boolean | `false` | Infer a comparator, threshold and weight for any property that names none, using the same rules `stickler.evaluate()` uses (root level) | +| `x-aws-stickler-infer-unspecified` | boolean | `false` | Infer a comparator, threshold, weight and clip setting for any property that names none, using the same rules `stickler.evaluate()` uses (root level) | | `x-aws-stickler-comparator-config` | object | `{}` | Keyword arguments passed to the named comparator | An unstated `x-aws-stickler-threshold` does not resolve to one number. It depends @@ -211,6 +211,13 @@ A scalar is plain when it has none of the keywords in the last row. Any other overrides the default in every position that reads it. `x-aws-stickler-clip-under-threshold` defaults to `true` in all of them. +With `x-aws-stickler-infer-unspecified`, a scalar, a free-form object, or an +array of either that names no comparator takes any threshold or clip setting it +leaves unstated from +[inference](../../Advanced/dynamic-models.md#what-inference-chooses) instead. +Inference turns clip off for a free-form object, a free-text string such as +`notes` or `description`, and an array of either, and leaves it on elsewhere. + ### Example Schema ```json diff --git a/docs/docs/Guides/Evaluation/understanding-results.md b/docs/docs/Guides/Evaluation/understanding-results.md index 24fd500a..4a505b5c 100644 --- a/docs/docs/Guides/Evaluation/understanding-results.md +++ b/docs/docs/Guides/Evaluation/understanding-results.md @@ -36,13 +36,13 @@ A weighted average of all field scores, ranging from 0.0 to 1.0. Calculated as: overall_score = sum(field_score * field_weight) / sum(field_weights) ``` -Fields with `clip_under_threshold=True` (the default) contribute 0.0 if they score below their threshold, rather than their partial similarity. +Fields with `clip_under_threshold=True` contribute 0.0 if they score below their threshold, rather than their partial similarity. On a `StructuredModel` declared in Python that is the default, except on dict and plain-model fields. JSON Schema and the zero-config path have their own defaults ([JSON Schema](README.md#extension-reference), [zero-config](../../API-Reference/auto.md#inference)). A list field follows the [Score](../../Advanced/classification-logic.md#list-contract) rule of the list contract instead. A field absent on both sides scores `1.0` and carries its full weight: a value the model correctly left blank is a value it got right. On a schema where most fields are usually empty this makes `overall_score` behave more like accuracy than like a hit rate. See [Sparse Objects](../../Getting-Started/thresholds-and-metrics.md#sparse-objects) for which metric answers which question. ### `field_scores` (dict) -Maps each field name to its similarity score (0.0 to 1.0). For nested objects, the value is the weighted average of the sub-fields. For lists, it reflects the Hungarian-matched aggregate. +Maps each field name to its similarity score (0.0 to 1.0). For nested objects, the value is the weighted average of the sub-fields. For lists, it is the sum of the Hungarian pair scores divided by the longer list's length ([Score](../../Advanced/classification-logic.md#list-contract)): the [Transaction example](../../Advanced/hungarian-matching.md#step-4-list-score) scores (0.667 + 0.5 + 0.0) / 3 = 0.3889. ### Asking whether anything failed @@ -105,7 +105,7 @@ The `confusion_matrix` object has four keys: - **`overall`** -- Metrics for this node's direct children. Where the field is a list, those children are item pairings rather than leaves. - **`fields`** -- Field-by-field breakdown, with nested structure for objects and lists. - **`non_matches`** -- Always `[]`, a placeholder, also in evaluator-format output. With `document_non_matches=True` the records are in the result's top-level `non_matches`. -- **`aggregate`** -- Primitive field metrics summed recursively below this node, excluding list items rejected at their element class's `match_threshold`. A single nested `StructuredModel` field is not excluded; its leaves are always counted. Where a list's items were *all* rejected the counts become object rows rather than primitive-field metrics, so check that before computing a leaf rate ([why](../../Advanced/aggregate-metrics.md#aggregate-counts-objects-for-an-all-rejected-list)). See [`overall` vs `aggregate`](#overall-vs-aggregate). +- **`aggregate`** -- Primitive field metrics summed recursively below this node, excluding list items rejected at their element class's `match_threshold`, and unmatched (FN/FA) items when a sibling was accepted ([Recursion](../../Advanced/classification-logic.md#list-contract)). A single nested `StructuredModel` field is not excluded; its leaves are always counted. Where a list's items were *all* rejected the counts become object rows rather than primitive-field metrics, so check that before computing a leaf rate ([why](../../Advanced/aggregate-metrics.md#aggregate-counts-objects-for-an-all-rejected-list)). See [`overall` vs `aggregate`](#overall-vs-aggregate). ### `overall` vs `aggregate` @@ -370,7 +370,7 @@ For list fields (e.g., products, line items), non-match entries can be at the ob ## Field Comparisons -When you pass `document_field_comparisons=True`, the result includes a `field_comparisons` list documenting every individual field comparison -- both matches and non-matches. +When you pass `document_field_comparisons=True`, the result includes a `field_comparisons` list documenting every individual field comparison -- both matches and non-matches. For a list there is one row per element of a primitive, dict or plain-model list, one row per leaf of a TP `StructuredModel` item, and one object row per FD, FN or FA item ([Reports](../../Advanced/classification-logic.md#list-contract)). Inside a list item, a nested list or object gets one row instead of being expanded, a [known gap](../../Advanced/classification-logic.md#list-contract). ```python result = ground_truth.compare_with(prediction, document_field_comparisons=True) @@ -388,9 +388,9 @@ Each entry contains: | `expected_value` | any | The ground truth value. | | `actual_key` | string | Field path in prediction (may differ for list items due to Hungarian matching). | | `actual_value` | any | The predicted value. | -| `match` | bool | Whether the score met the threshold. | -| `score` | float | Raw similarity score. | -| `weighted_score` | float | Score multiplied by the field's weight. | +| `match` | bool | Whether the row's own classification is TP or TN: a value or object row met its threshold; a list row had every element paired as a TP ([Reports](../../Advanced/classification-logic.md#list-contract)). | +| `score` | float | Raw similarity score. Inside a list item it is the clipped score, a [known gap](../../Advanced/classification-logic.md#list-contract). | +| `weighted_score` | float | For a value row, the clipped score multiplied by the field's weight. A list element row ignores the list field's weight: a primitive element row carries its raw, unclipped similarity, an object row carries its score, and a leaf of a TP item uses the leaf's own weight. | | `reason` | string | Human-readable explanation. | This is useful for comprehensive auditing of all comparisons, not just failures. diff --git a/src/stickler/auto/README.md b/src/stickler/auto/README.md index 44724cca..d1b5001e 100644 --- a/src/stickler/auto/README.md +++ b/src/stickler/auto/README.md @@ -79,7 +79,7 @@ call yields both `field_scores`/`overall_score` **and** precision/recall/f1/accu | `str` | Levenshtein | 0.7 | yes | | nested `BaseModel` | recurse → child shadow model | `match_threshold` | **no** (partial credit, consistent with the same object inside a list) | | nested `StructuredModel` | used as configured, never re-inferred | (its own) | (its own) | - | `List[BaseModel]` | Hungarian object matching | (element `match_threshold`) | n/a | + | `List[BaseModel]` | Hungarian object matching | (element `match_threshold`) | no effect, although `explain()` reports `True` (a known gap) | | `List[primitive]` | element comparator | element | yes | | `dict` / `Dict[...]` / `Mapping[...]` | **ANLS\*** over the mapping itself (structural, partial credit) | `match_threshold` | **no** (partial credit, same policy as a nested object) | | `tuple` / `set` / `Any` / multi-arm unions | Exact over a canonical JSON string (sorted keys; sets also sort elements) | 1.0 | n/a (Exact is all-or-nothing) | @@ -174,8 +174,8 @@ first. Both name a blocker the caller has to fix. ## Known limitations - **`List[BaseModel]` semantics** use Hungarian matching (order-independent), - which differs from `anls_score`'s ordering-based path. This is intentional and - documented so scores are explainable. + not ANLS\*. Neither depends on order: a reordered list scores `1.0` both here + and under `anls_score`. - **Inference heuristics may be tuned across releases**, which can change scores for unconfigured models. Benchmark against a pinned stickler version, or graduate to an explicit `StructuredModel` (whose configuration this layer diff --git a/src/stickler/auto/facade.py b/src/stickler/auto/facade.py index 16c1590d..6180a781 100644 --- a/src/stickler/auto/facade.py +++ b/src/stickler/auto/facade.py @@ -279,15 +279,21 @@ def eval_for( weights stay uniform and precision/recall are not skewed by guessed business-criticality). Ignored for ``StructuredModel`` classes. match_threshold: The similarity score at or above which an OBJECT - counts as a match. It drives ``EvalResult.matched`` and, for - ``List[Model]`` fields, the Hungarian TP/FN/FA classification of - each element (at every nesting level). It does NOT change - per-field similarity scores or ``overall_score``. + counts as a match. It drives ``EvalResult.matched``. For a plain + pydantic class it also decides TP vs FD for each ``List[Model]`` + and ``List[dict]`` element at every nesting level, and sets the + field threshold of nested plain-model and ``dict`` fields; a + primitive list keeps its inferred threshold. + ``EvalSpec.explain()`` shows the resolved values. On a + ``StructuredModel`` class this value drives only ``matched``: + list pairing and field thresholds keep their class values. It + does NOT change per-field similarity scores or ``overall_score``. Left unset, a ``StructuredModel`` subclass's own declared ``match_threshold`` wins, so the AS CONFIGURED promise above holds for this knob too; any other class gets - ``DEFAULT_MATCH_THRESHOLD``. Passing a value overrides both. + ``DEFAULT_MATCH_THRESHOLD``. Passing a value overrides both for + ``matched``. """ if isinstance(cls, type) and issubclass(cls, StructuredModel): # Explicit configuration wins: never re-infer over a model the user @@ -327,10 +333,13 @@ class (or a compatible superset, so extra/missing fields are tolerated). The prediction: The instance to score (e.g. a Strands ``response_model``). weight_hints: Enable name-token weight heuristics (default off). match_threshold: The similarity score at or above which an object - counts as a match (drives ``EvalResult.matched`` and list-element - TP/FN classification; does not change similarity scores). Left - unset, a ``StructuredModel``'s own declaration wins; see - :func:`eval_for`. + counts as a match (drives ``EvalResult.matched`` and, for a plain + pydantic class, ``List[Model]`` and ``List[dict]`` element TP/FD + classification and the field threshold of nested plain-model and + ``dict`` fields; on a + ``StructuredModel`` class it drives only ``matched``; does not + change similarity scores). Left unset, a ``StructuredModel``'s own + declaration wins; see :func:`eval_for`. Returns: An :class:`EvalResult` with ``overall_score``, ``precision``,