llmvalidate 0.6.0__tar.gz → 0.7.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: llmvalidate
3
- Version: 0.6.0
3
+ Version: 0.7.0
4
4
  Summary: Oncoshot LLM validation framework
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://github.com/Oncoshot/llm-validation-framework
@@ -42,6 +42,8 @@ The methodology behind this framework is described in a medRxiv preprint:
42
42
  - **Multi-field validation** - Binary (True/False), scalar (single values), and list (multiple values) data types
43
43
  - **Coded field support** - Score a value together with its code (ICD-10 / ICD-O-3, RxNorm) as two independent facets
44
44
  - **Partial labeling support** - Handle datasets where different cases have labels for different subsets of fields
45
+ - **Parent matching** - Hierarchical dictionaries: a prediction that is the parent of the labeled value scores a partial match (0.5) instead of incorrect.
46
+ E.g. for ICD-10: `C00` "Malignant neoplasm of lip" is partially correct for label `C00.1` "Malignant neoplasm, external lower lip".
45
47
  - **Dual usage modes** - Validate pre-computed results OR run live LLM inference with validation
46
48
  - **Comprehensive metrics** - Precision, recall, F1/F2, accuracy, specificity, with micro and macro aggregation where applicable
47
49
  - **Confidence analysis** - Automatic performance breakdown by confidence levels
@@ -204,6 +206,7 @@ A `validate()` run generates two timestamped CSV files (a third, CI metrics, is
204
206
  **Non-Binary Fields:**
205
207
  - `Cor/Mis/Spu: {Field}` - Item counts per row (Inc and TN are None for list fields)
206
208
  - `Cor/Inc/Mis/Spu: {Field} items` - Actual item lists
209
+ - `Par: {Field}` / `Par: {Field} items` - Partial-match count and the labeled items whose parent was predicted (only when the field has a `hierarchy` entry; see [Hierarchical / partial match](#hierarchical--partial-match))
207
210
  - `Precision/Recall/F1/F2: {Field}` - Per-row metrics (list fields only)
208
211
 
209
212
  **System Columns:**
@@ -281,6 +284,44 @@ The following formulas apply to both binary classification and structured extrac
281
284
 
282
285
  Where P = Precision and R = Recall (calculated differently for each metric type).
283
286
 
287
+ ### Hierarchical / Partial Match
288
+
289
+ Some concepts are hierarchical: a prediction can be *correct but less specific* than the label
290
+ (e.g. label `TNBC` (Triple Negative Breast Cancer), prediction `BC` (Breast Cancer)). Pass a **per-field** hierarchy to `validate` to credit
291
+ these as **partial** matches instead of outright wrong:
292
+
293
+ ```python
294
+ results_df, metrics_df = validate(
295
+ source_df=df,
296
+ fields=["Diagnosis", "Stage"],
297
+ structure_callback=None,
298
+ hierarchy={
299
+ "Diagnosis": {"TNBC": "BC"}, # {child: parent} for this field
300
+ # fields absent here get no partial matching (default behavior)
301
+ },
302
+ )
303
+ ```
304
+
305
+ When a prediction equals the **parent** of the labeled child, the case scores as a **Partial**
306
+ (`Par`) worth `0.5` in precision and recall rather than Incorrect:
307
+
308
+ | Metric | Formula |
309
+ |--------|---------|
310
+ | **Precision** | `(cor + 0.5 × par) / (cor + inc + par + spu)` |
311
+ | **Recall** | `(cor + 0.5 × par) / (cor + inc + par + mis)` |
312
+
313
+ A single case that is purely a parent-hit therefore scores `0.5` precision, `0.5` recall → `0.5` F1.
314
+
315
+ Two semantic properties:
316
+ - **One level only** — only a *direct* parent counts; a grandparent scores as Incorrect.
317
+ - **Direction matters** — credit is asymmetric: it is granted only when the prediction is the
318
+ parent of the label (less specific than the truth), **not** when the prediction is more
319
+ specific (a child) than the label.
320
+
321
+ Output: for each field that has a hierarchy entry, results get a per-row `Par: {Field}` column
322
+ and the metrics table gets a `par` column (aggregated partial count). Fields without a hierarchy
323
+ entry produce identical output to a run with no hierarchy at all (no `Par:`/`Inc:` columns).
324
+
284
325
  ## Bootstrap Confidence Intervals
285
326
 
286
327
  The framework includes statistical confidence interval estimation using non-parametric bootstrap resampling at the case level. This provides uncertainty quantification for all validation metrics.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "llmvalidate"
7
- version = "0.6.0"
7
+ version = "0.7.0"
8
8
  description = "Oncoshot LLM validation framework"
9
9
  readme = "readme.md"
10
10
  requires-python = ">=3.11"
@@ -18,6 +18,8 @@ The methodology behind this framework is described in a medRxiv preprint:
18
18
  - **Multi-field validation** - Binary (True/False), scalar (single values), and list (multiple values) data types
19
19
  - **Coded field support** - Score a value together with its code (ICD-10 / ICD-O-3, RxNorm) as two independent facets
20
20
  - **Partial labeling support** - Handle datasets where different cases have labels for different subsets of fields
21
+ - **Parent matching** - Hierarchical dictionaries: a prediction that is the parent of the labeled value scores a partial match (0.5) instead of incorrect.
22
+ E.g. for ICD-10: `C00` "Malignant neoplasm of lip" is partially correct for label `C00.1` "Malignant neoplasm, external lower lip".
21
23
  - **Dual usage modes** - Validate pre-computed results OR run live LLM inference with validation
22
24
  - **Comprehensive metrics** - Precision, recall, F1/F2, accuracy, specificity, with micro and macro aggregation where applicable
23
25
  - **Confidence analysis** - Automatic performance breakdown by confidence levels
@@ -180,6 +182,7 @@ A `validate()` run generates two timestamped CSV files (a third, CI metrics, is
180
182
  **Non-Binary Fields:**
181
183
  - `Cor/Mis/Spu: {Field}` - Item counts per row (Inc and TN are None for list fields)
182
184
  - `Cor/Inc/Mis/Spu: {Field} items` - Actual item lists
185
+ - `Par: {Field}` / `Par: {Field} items` - Partial-match count and the labeled items whose parent was predicted (only when the field has a `hierarchy` entry; see [Hierarchical / partial match](#hierarchical--partial-match))
183
186
  - `Precision/Recall/F1/F2: {Field}` - Per-row metrics (list fields only)
184
187
 
185
188
  **System Columns:**
@@ -257,6 +260,44 @@ The following formulas apply to both binary classification and structured extrac
257
260
 
258
261
  Where P = Precision and R = Recall (calculated differently for each metric type).
259
262
 
263
+ ### Hierarchical / Partial Match
264
+
265
+ Some concepts are hierarchical: a prediction can be *correct but less specific* than the label
266
+ (e.g. label `TNBC` (Triple Negative Breast Cancer), prediction `BC` (Breast Cancer)). Pass a **per-field** hierarchy to `validate` to credit
267
+ these as **partial** matches instead of outright wrong:
268
+
269
+ ```python
270
+ results_df, metrics_df = validate(
271
+ source_df=df,
272
+ fields=["Diagnosis", "Stage"],
273
+ structure_callback=None,
274
+ hierarchy={
275
+ "Diagnosis": {"TNBC": "BC"}, # {child: parent} for this field
276
+ # fields absent here get no partial matching (default behavior)
277
+ },
278
+ )
279
+ ```
280
+
281
+ When a prediction equals the **parent** of the labeled child, the case scores as a **Partial**
282
+ (`Par`) worth `0.5` in precision and recall rather than Incorrect:
283
+
284
+ | Metric | Formula |
285
+ |--------|---------|
286
+ | **Precision** | `(cor + 0.5 × par) / (cor + inc + par + spu)` |
287
+ | **Recall** | `(cor + 0.5 × par) / (cor + inc + par + mis)` |
288
+
289
+ A single case that is purely a parent-hit therefore scores `0.5` precision, `0.5` recall → `0.5` F1.
290
+
291
+ Two semantic properties:
292
+ - **One level only** — only a *direct* parent counts; a grandparent scores as Incorrect.
293
+ - **Direction matters** — credit is asymmetric: it is granted only when the prediction is the
294
+ parent of the label (less specific than the truth), **not** when the prediction is more
295
+ specific (a child) than the label.
296
+
297
+ Output: for each field that has a hierarchy entry, results get a per-row `Par: {Field}` column
298
+ and the metrics table gets a `par` column (aggregated partial count). Fields without a hierarchy
299
+ entry produce identical output to a run with no hierarchy at all (no `Par:`/`Inc:` columns).
300
+
260
301
  ## Bootstrap Confidence Intervals
261
302
 
262
303
  The framework includes statistical confidence interval estimation using non-parametric bootstrap resampling at the case level. This provides uncertainty quantification for all validation metrics.
@@ -63,27 +63,40 @@ def calculate_binary_metrics(TP, FP, FN, TN):
63
63
 
64
64
  return precision, recall, f1_score, f2_score, accuracy, specificity
65
65
 
66
- def compare_results_all(df, fields, parents={}, comparison_callback=None, raw_text_column_name: str = "raw_text"):
66
+ def compare_results_all(df, fields, hierarchy={}, comparison_callback=None, raw_text_column_name: str = "raw_text"):
67
67
  """ For each case from df calls and for each field from 'fields' compares results with 'Res: '+field
68
68
  and adds columns 'Inc: '+field, 'Cor: '+field, 'Mis: '+field, 'Spu: '+field, 'Par: '+field
69
69
  Input
70
70
  'df' - pandas dataframe with input, labeled data and results in 'Res: ' columns
71
71
  'fields' - fields to compare results
72
- 'parents' - A dictionary where key is a child and value is a parent for partial match
73
- - **comparison_callback (callable, optional)**:
72
+ 'hierarchy' - A PER-FIELD nested dictionary {field_name: {child: parent}} for partial
73
+ match. Each field is scored against its own {child: parent} map; fields absent from
74
+ 'hierarchy' get no partial matching (default {} = no partial matching for any field).
75
+ - **comparison_callback (callable, optional)**:
74
76
  A callback function that will be applied to each row to generate comparison results.
75
77
 
76
78
  Returns pandas data frame same as df but with added columns:
77
79
  'Cor: ' for Correct
78
- 'Inc: ' for Incorrect (scalar fields; for list fields only when 'parents' is provided)
80
+ 'Inc: ' for Incorrect (scalar fields; for list fields only when the field has a hierarchy entry)
79
81
  'Mis: ' for Missing
80
82
  'Spu: ' for Spurious
81
- 'Par: ' for Partial (only when 'parents' is provided)
83
+ 'Par: ' for Partial (only when the field has a hierarchy entry)
82
84
  'TN: ' for True Negative (scalar fields only; not defined for list fields)
83
85
  """
84
86
 
85
87
  fields = [f for f in fields if f in df] #ignore fields which are not in columns (they may be added later by comparison_callback)
86
88
 
89
+ # hierarchy is a per-field map {field: {child: parent}}; fail fast with a clear
90
+ # message if a caller passes a flat {child: parent} (the pre-1.0 shape) or any
91
+ # non-dict value, rather than a cryptic .items() error deep in the row loop.
92
+ # None is tolerated per field (treated as "no hierarchy for this field").
93
+ bad_hierarchy = {f: v for f, v in hierarchy.items() if v is not None and not isinstance(v, dict)}
94
+ if bad_hierarchy:
95
+ raise TypeError(
96
+ "hierarchy must be a per-field map {field: {child: parent}}; "
97
+ f"these entries are not dicts: {sorted(bad_hierarchy)}"
98
+ )
99
+
87
100
  # Determine which fields are binary by looking at the unique non-empty expected values.
88
101
  binary_fields = {}
89
102
  for field in fields:
@@ -112,12 +125,15 @@ def compare_results_all(df, fields, parents={}, comparison_callback=None, raw_te
112
125
 
113
126
  actual = row['Res: ' + field]
114
127
 
115
- if binary_fields[field]:
128
+ # Shape already validated up front; None/missing -> no hierarchy for this field.
129
+ field_hierarchy = hierarchy.get(field) or {}
130
+
131
+ if binary_fields[field]:
116
132
  # For binary fields, use the binary comparison function.
117
133
  res = compare_results_binary(expected, actual)
118
134
  res_items = {}
119
135
  else:
120
- res_items = compare_results(expected, actual, parents)
136
+ res_items = compare_results(expected, actual, field_hierarchy)
121
137
 
122
138
  # Convert lists to counts, preserving None values
123
139
  res = {key: len(value) if value is not None else None for key, value in res_items.items()}
@@ -135,13 +151,13 @@ def compare_results_all(df, fields, parents={}, comparison_callback=None, raw_te
135
151
  row['F1 score: ' + field] = f1_score
136
152
  row['F2 score: ' + field] = f2_score
137
153
 
138
- if not parents:
139
- #we don't want useless columns if no parents anyway
154
+ if not field_hierarchy:
155
+ #we don't want useless columns if no hierarchy for this field anyway
140
156
  del res['Incorrect'] #incorrect appear only if parent mismatch (only for lists)
141
157
  del res_items['Incorrect']
142
158
 
143
- if not parents:
144
- #we don't want useless columns if no parents anyway
159
+ if not field_hierarchy:
160
+ #we don't want useless columns if no hierarchy for this field anyway
145
161
  del res['Partial'] #partial appear only if parent match
146
162
  del res_items['Partial']
147
163
 
@@ -408,7 +424,7 @@ def get_metrics(res_df, fields):
408
424
 
409
425
  return metrics
410
426
 
411
- def compare_results(expected, actual, parents={}):
427
+ def compare_results(expected, actual, hierarchy={}):
412
428
  """
413
429
  Compares expected results with actual results, ignoring duplicates.
414
430
 
@@ -427,7 +443,7 @@ def compare_results(expected, actual, parents={}):
427
443
  Args:
428
444
  expected (int, float, str, list): The expected result.
429
445
  actual (int, float, str, list): The actual result.
430
- parents : A dictionary where key is a child and value is a parent for partial match
446
+ hierarchy : A flat dictionary where key is a child and value is a parent for partial match
431
447
 
432
448
  Returns:
433
449
  dict: A dictionary with keys 'Correct', 'Incorrect', 'Missing', 'Spurious', and 'Partial', mapping to their respective lists.
@@ -468,8 +484,10 @@ def compare_results(expected, actual, parents={}):
468
484
  [a] None None None None None
469
485
  """
470
486
 
471
- # Convert dictionary keys to casefold for case-insensitive matching
472
- parents = {k.casefold(): v.casefold() for k, v in parents.items()}
487
+ # Normalize keys/values the same way as expected/actual (float-parse then casefold),
488
+ # so the hierarchy matches however the compared values were normalized and tolerates
489
+ # non-string codes (e.g. numeric-coded enums) instead of raising on .casefold().
490
+ hierarchy = {normalize(k): normalize(v) for k, v in hierarchy.items()}
473
491
 
474
492
  output = {'Correct': [], 'Incorrect': [], 'Missing': [], 'Spurious': [], 'Partial': []}
475
493
 
@@ -480,21 +498,21 @@ def compare_results(expected, actual, parents={}):
480
498
  # Convert all elements to lowercase strings for case-insensitive comparison
481
499
  # and remove duplicates by converting to sets.
482
500
  expected_set = normalize_list(expected)
483
- expected_parents_set = {parents[s] for s in expected_set if s in parents}
484
-
501
+ expected_parents_set = {hierarchy[s] for s in expected_set if s in hierarchy}
502
+
485
503
  actual_set = normalize_list(actual)
486
- actual_parents_set = {parents[s] for s in actual_set if s in parents}
504
+ actual_parents_set = {hierarchy[s] for s in actual_set if s in hierarchy}
487
505
 
488
506
  output['Correct'] = list(expected_set & actual_set) # matching exactly
489
507
 
490
508
  for missing in expected_set - actual_set - actual_parents_set:
491
- if missing in parents and parents[missing] in actual_set:
509
+ if missing in hierarchy and hierarchy[missing] in actual_set:
492
510
  output['Partial'].append(missing) # actual set has parent value therefore Partial
493
511
  else:
494
512
  output['Missing'].append(missing)
495
513
 
496
514
  for spurious in actual_set - expected_set - expected_parents_set:
497
- if spurious in parents and parents[spurious] in expected_set:
515
+ if spurious in hierarchy and hierarchy[spurious] in expected_set:
498
516
  output['Incorrect'].append(spurious) # expected set has parent value therefore Incorrect
499
517
  else:
500
518
  output['Spurious'].append(spurious)
@@ -516,7 +534,7 @@ def compare_results(expected, actual, parents={}):
516
534
  output['Spurious'] = [actual]
517
535
  elif not is_scalar_empty(expected) and is_scalar_empty(actual):
518
536
  output['Missing'] = [expected]
519
- elif expected in parents and parents[expected] == actual:
537
+ elif expected in hierarchy and hierarchy[expected] == actual:
520
538
  output['Partial'] = [expected] # actual value is a parent of expected
521
539
  else:
522
540
  output['Incorrect'] = [actual]
@@ -821,7 +839,8 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
821
839
  raw_text_column_name = 'raw_text',
822
840
  comparison_callback = None,
823
841
  max_workers: int | None = 1,
824
- use_threads: bool = True):
842
+ use_threads: bool = True,
843
+ hierarchy = {}):
825
844
  """
826
845
  Performs validation by applying a structuring callback to an input dataset and evaluating performance.
827
846
 
@@ -845,10 +864,20 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
845
864
  A callback function that will be applied to each row to generate structured predictions.
846
865
  If None, assumes that source_df already contains "Res: " columns with results.
847
866
 
848
- - **comparison_callback (callable, optional)**:
867
+ - **comparison_callback (callable, optional)**:
849
868
  A callback function that will be applied to each row to generate comparison results.
850
869
 
851
- - **output_folder (str, optional)**:
870
+ - **hierarchy (dict, optional)**:
871
+ A PER-FIELD nested map ``{field: {child: parent}}`` enabling partial (hierarchical)
872
+ matching. Default ``{}`` means no partial matching (current behavior). For a given
873
+ field, when a prediction equals the *parent* of the labeled child (i.e. the prediction
874
+ is less specific than the truth), it scores as a **Partial** match worth 0.5 in both
875
+ precision and recall — ``(cor + 0.5*par)/denom`` — instead of Incorrect. Two semantic
876
+ properties: (1) only DIRECT parent matches (one level) count — a grandparent does not;
877
+ (2) credit is asymmetric — it is granted only when the prediction is the parent of the
878
+ label, not when the prediction is more specific (a child) than the label.
879
+
880
+ - **output_folder (str, optional)**:
852
881
  Directory where the output CSV files will be saved.
853
882
  If not provided, results will only be returned as DataFrames.
854
883
 
@@ -917,7 +946,7 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
917
946
 
918
947
  ###################################
919
948
  # Analyse the results and calculate the metrics
920
- res_df = compare_results_all(res_df, fields, parents={}, comparison_callback=comparison_callback, raw_text_column_name=raw_text_column_name)
949
+ res_df = compare_results_all(res_df, fields, hierarchy=hierarchy, comparison_callback=comparison_callback, raw_text_column_name=raw_text_column_name)
921
950
 
922
951
  # Save results
923
952
  if output_folder:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: llmvalidate
3
- Version: 0.6.0
3
+ Version: 0.7.0
4
4
  Summary: Oncoshot LLM validation framework
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://github.com/Oncoshot/llm-validation-framework
@@ -42,6 +42,8 @@ The methodology behind this framework is described in a medRxiv preprint:
42
42
  - **Multi-field validation** - Binary (True/False), scalar (single values), and list (multiple values) data types
43
43
  - **Coded field support** - Score a value together with its code (ICD-10 / ICD-O-3, RxNorm) as two independent facets
44
44
  - **Partial labeling support** - Handle datasets where different cases have labels for different subsets of fields
45
+ - **Parent matching** - Hierarchical dictionaries: a prediction that is the parent of the labeled value scores a partial match (0.5) instead of incorrect.
46
+ E.g. for ICD-10: `C00` "Malignant neoplasm of lip" is partially correct for label `C00.1` "Malignant neoplasm, external lower lip".
45
47
  - **Dual usage modes** - Validate pre-computed results OR run live LLM inference with validation
46
48
  - **Comprehensive metrics** - Precision, recall, F1/F2, accuracy, specificity, with micro and macro aggregation where applicable
47
49
  - **Confidence analysis** - Automatic performance breakdown by confidence levels
@@ -204,6 +206,7 @@ A `validate()` run generates two timestamped CSV files (a third, CI metrics, is
204
206
  **Non-Binary Fields:**
205
207
  - `Cor/Mis/Spu: {Field}` - Item counts per row (Inc and TN are None for list fields)
206
208
  - `Cor/Inc/Mis/Spu: {Field} items` - Actual item lists
209
+ - `Par: {Field}` / `Par: {Field} items` - Partial-match count and the labeled items whose parent was predicted (only when the field has a `hierarchy` entry; see [Hierarchical / partial match](#hierarchical--partial-match))
207
210
  - `Precision/Recall/F1/F2: {Field}` - Per-row metrics (list fields only)
208
211
 
209
212
  **System Columns:**
@@ -281,6 +284,44 @@ The following formulas apply to both binary classification and structured extrac
281
284
 
282
285
  Where P = Precision and R = Recall (calculated differently for each metric type).
283
286
 
287
+ ### Hierarchical / Partial Match
288
+
289
+ Some concepts are hierarchical: a prediction can be *correct but less specific* than the label
290
+ (e.g. label `TNBC` (Triple Negative Breast Cancer), prediction `BC` (Breast Cancer)). Pass a **per-field** hierarchy to `validate` to credit
291
+ these as **partial** matches instead of outright wrong:
292
+
293
+ ```python
294
+ results_df, metrics_df = validate(
295
+ source_df=df,
296
+ fields=["Diagnosis", "Stage"],
297
+ structure_callback=None,
298
+ hierarchy={
299
+ "Diagnosis": {"TNBC": "BC"}, # {child: parent} for this field
300
+ # fields absent here get no partial matching (default behavior)
301
+ },
302
+ )
303
+ ```
304
+
305
+ When a prediction equals the **parent** of the labeled child, the case scores as a **Partial**
306
+ (`Par`) worth `0.5` in precision and recall rather than Incorrect:
307
+
308
+ | Metric | Formula |
309
+ |--------|---------|
310
+ | **Precision** | `(cor + 0.5 × par) / (cor + inc + par + spu)` |
311
+ | **Recall** | `(cor + 0.5 × par) / (cor + inc + par + mis)` |
312
+
313
+ A single case that is purely a parent-hit therefore scores `0.5` precision, `0.5` recall → `0.5` F1.
314
+
315
+ Two semantic properties:
316
+ - **One level only** — only a *direct* parent counts; a grandparent scores as Incorrect.
317
+ - **Direction matters** — credit is asymmetric: it is granted only when the prediction is the
318
+ parent of the label (less specific than the truth), **not** when the prediction is more
319
+ specific (a child) than the label.
320
+
321
+ Output: for each field that has a hierarchy entry, results get a per-row `Par: {Field}` column
322
+ and the metrics table gets a `par` column (aggregated partial count). Fields without a hierarchy
323
+ entry produce identical output to a run with no hierarchy at all (no `Par:`/`Inc:` columns).
324
+
284
325
  ## Bootstrap Confidence Intervals
285
326
 
286
327
  The framework includes statistical confidence interval estimation using non-parametric bootstrap resampling at the case level. This provides uncertainty quantification for all validation metrics.
File without changes
File without changes