llmvalidate 0.5.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.
- {llmvalidate-0.5.0/src/llmvalidate.egg-info → llmvalidate-0.7.0}/PKG-INFO +80 -18
- {llmvalidate-0.5.0 → llmvalidate-0.7.0}/pyproject.toml +1 -1
- {llmvalidate-0.5.0 → llmvalidate-0.7.0}/readme.md +80 -18
- {llmvalidate-0.5.0 → llmvalidate-0.7.0}/src/llmvalidate/validation.py +88 -37
- {llmvalidate-0.5.0 → llmvalidate-0.7.0/src/llmvalidate.egg-info}/PKG-INFO +80 -18
- {llmvalidate-0.5.0 → llmvalidate-0.7.0}/LICENSE +0 -0
- {llmvalidate-0.5.0 → llmvalidate-0.7.0}/setup.cfg +0 -0
- {llmvalidate-0.5.0 → llmvalidate-0.7.0}/src/llmvalidate/__init__.py +0 -0
- {llmvalidate-0.5.0 → llmvalidate-0.7.0}/src/llmvalidate/structured.py +0 -0
- {llmvalidate-0.5.0 → llmvalidate-0.7.0}/src/llmvalidate/utils.py +0 -0
- {llmvalidate-0.5.0 → llmvalidate-0.7.0}/src/llmvalidate.egg-info/SOURCES.txt +0 -0
- {llmvalidate-0.5.0 → llmvalidate-0.7.0}/src/llmvalidate.egg-info/dependency_links.txt +0 -0
- {llmvalidate-0.5.0 → llmvalidate-0.7.0}/src/llmvalidate.egg-info/requires.txt +0 -0
- {llmvalidate-0.5.0 → llmvalidate-0.7.0}/src/llmvalidate.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: llmvalidate
|
|
3
|
-
Version: 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
|
|
@@ -24,20 +24,28 @@ Dynamic: license-file
|
|
|
24
24
|
|
|
25
25
|
# LLM Validation Framework
|
|
26
26
|
|
|
27
|
-
[](https://github.com/Oncoshot/llm-validation-framework/actions)
|
|
28
28
|
[](https://pypi.org/project/llmvalidate/)
|
|
29
29
|
[](https://pypi.org/project/llmvalidate/)
|
|
30
|
-
[](https://github.com/Oncoshot/llm-validation-framework/blob/master/LICENSE)
|
|
31
|
+
[](https://github.com/Oncoshot/llm-validation-framework/stargazers)
|
|
32
32
|
|
|
33
33
|
A comprehensive Python framework for evaluating LLM-extracted structured data against ground truth labels. Supports binary classification, scalar values, and list fields with detailed performance metrics, confidence-based evaluation, and statistical uncertainty quantification via non-parametric bootstrap confidence intervals.
|
|
34
34
|
|
|
35
|
+
## 📄 Paper
|
|
36
|
+
|
|
37
|
+
The methodology behind this framework is described in a medRxiv preprint:
|
|
38
|
+
[medRxiv 2026.05.18.26353541](https://www.medrxiv.org/content/10.64898/2026.05.18.26353541v1) — DOI: [10.64898/2026.05.18.26353541](https://doi.org/10.64898/2026.05.18.26353541)
|
|
39
|
+
|
|
35
40
|
## ✨ Key Features
|
|
36
41
|
|
|
37
42
|
- **Multi-field validation** - Binary (True/False), scalar (single values), and list (multiple values) data types
|
|
43
|
+
- **Coded field support** - Score a value together with its code (ICD-10 / ICD-O-3, RxNorm) as two independent facets
|
|
38
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".
|
|
39
47
|
- **Dual usage modes** - Validate pre-computed results OR run live LLM inference with validation
|
|
40
|
-
- **Comprehensive metrics** - Precision, recall, F1/F2, accuracy, specificity with
|
|
48
|
+
- **Comprehensive metrics** - Precision, recall, F1/F2, accuracy, specificity, with micro and macro aggregation where applicable
|
|
41
49
|
- **Confidence analysis** - Automatic performance breakdown by confidence levels
|
|
42
50
|
- **Statistical uncertainty** - Non-parametric bootstrap confidence intervals for all performance metrics
|
|
43
51
|
- **Production ready** - Parallel processing, intelligent caching, detailed progress tracking
|
|
@@ -60,14 +68,14 @@ python runme.py
|
|
|
60
68
|
|
|
61
69
|
Processes the included [samples.csv](samples.csv) (14 test cases covering all validation scenarios) and outputs timestamped results to `validation_results/samples/`:
|
|
62
70
|
|
|
63
|
-
- **[Results CSV](validation_results/samples/2026-
|
|
64
|
-
- **[Metrics CSV](validation_results/samples/2026-
|
|
65
|
-
- **[CI Metrics CSV](validation_results/samples/2026-
|
|
71
|
+
- **[Results CSV](validation_results/samples/2026-07-13%2001-12-18%20results.csv)** - Row-by-row comparison with confusion matrix counts and item-level details
|
|
72
|
+
- **[Metrics CSV](validation_results/samples/2026-07-13%2001-12-18%20metrics.csv)** - Aggregated performance statistics with confidence breakdowns
|
|
73
|
+
- **[CI Metrics CSV](validation_results/samples/2026-07-13%2001-12-18%20CI%20metrics.csv)** - Confidence intervals for metrics
|
|
66
74
|
|
|
67
75
|
| Rows | Field Type | Test Scenarios |
|
|
68
76
|
|------|------------|----------------|
|
|
69
77
|
| **1-4** | Binary (`Has metastasis`) | True Positive, True Negative, False Positive, False Negative |
|
|
70
|
-
| **5-9** | Scalar (`Diagnosis`, `Histology`) | Correct, incorrect, missing, spurious, and empty extractions |
|
|
78
|
+
| **5-9** | Scalar (`Diagnosis`, `Histology`) | Correct, incorrect, missing, spurious, and correct-empty (TN) extractions |
|
|
71
79
|
| **10-14** | List (`Treatment Drugs`, `Test Results`) | Perfect match, spurious items, missing items, correct empty, mixed results |
|
|
72
80
|
|
|
73
81
|
## 📊 Usage Modes
|
|
@@ -77,7 +85,7 @@ When you have LLM predictions in `Res: {Field Name}` columns:
|
|
|
77
85
|
|
|
78
86
|
```python
|
|
79
87
|
import pandas as pd
|
|
80
|
-
from
|
|
88
|
+
from llmvalidate import validate
|
|
81
89
|
|
|
82
90
|
df = pd.read_csv("data.csv", index_col="Patient ID")
|
|
83
91
|
# df must contain: "Field Name" and "Res: Field Name" columns
|
|
@@ -93,8 +101,8 @@ results_df, metrics_df = validate(
|
|
|
93
101
|
### Mode 2: Live LLM Inference + Validation
|
|
94
102
|
|
|
95
103
|
```python
|
|
96
|
-
from
|
|
97
|
-
from
|
|
104
|
+
from llmvalidate.structured import StructuredResult, StructuredGroup, StructuredField
|
|
105
|
+
from llmvalidate.utils import flatten_structured_result
|
|
98
106
|
|
|
99
107
|
def llm_callback(row, i, raw_text_column_name):
|
|
100
108
|
raw_text = row[raw_text_column_name]
|
|
@@ -164,6 +172,14 @@ with the `-value` / `-code` label columns.
|
|
|
164
172
|
- **`null/empty/NaN`** = Field not labeled/evaluated (supports partial labeling where different cases may have labels for different field subsets)
|
|
165
173
|
- **Lists** - Can be Python lists `["a", "b"]` or stringified `"['a', 'b']"` (auto-converted)
|
|
166
174
|
|
|
175
|
+
The `"-"`-vs-empty distinction above applies to **label** columns only. In **prediction** (`Res:`)
|
|
176
|
+
columns there is no "not evaluated" state: `"-"`, `""`, `null`/`NaN`, whitespace-only strings and
|
|
177
|
+
`[]` are all treated identically as "nothing extracted" (scoring Mis against a labeled value, or
|
|
178
|
+
TN when the label is `"-"`). We still recommend emitting `"-"` uniformly, to keep predictions
|
|
179
|
+
symmetric with labels. **Exception — binary fields:** predictions must be an explicit
|
|
180
|
+
`True`/`False`; an empty prediction is "not True / not False", so it scores FN against a `True`
|
|
181
|
+
label and **FP** against a `False` label.
|
|
182
|
+
|
|
167
183
|
### Partial Labeling Support
|
|
168
184
|
The framework supports partial labeling scenarios where:
|
|
169
185
|
- Not every case needs labels for every field
|
|
@@ -174,7 +190,7 @@ The framework supports partial labeling scenarios where:
|
|
|
174
190
|
|
|
175
191
|
## 📈 Output Files
|
|
176
192
|
|
|
177
|
-
|
|
193
|
+
A `validate()` run generates two timestamped CSV files (a third, CI metrics, is added when you also run `bootstrap_CI` — see the demo above):
|
|
178
194
|
|
|
179
195
|
### 1. Results CSV (`YYYY-MM-DD HH-MM-SS results.csv`)
|
|
180
196
|
**Row-level analysis** with detailed per-case metrics:
|
|
@@ -188,8 +204,9 @@ The framework generates two timestamped CSV files for each validation run:
|
|
|
188
204
|
- `TP/FP/FN/TN: {Field}` - Confusion matrix counts (1 or 0 per row)
|
|
189
205
|
|
|
190
206
|
**Non-Binary Fields:**
|
|
191
|
-
- `Cor/
|
|
207
|
+
- `Cor/Mis/Spu: {Field}` - Item counts per row (Inc and TN are None for list fields)
|
|
192
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))
|
|
193
210
|
- `Precision/Recall/F1/F2: {Field}` - Per-row metrics (list fields only)
|
|
194
211
|
|
|
195
212
|
**System Columns:**
|
|
@@ -208,9 +225,14 @@ The framework generates two timestamped CSV files for each validation run:
|
|
|
208
225
|
|
|
209
226
|
**Binary Metrics:** `TP`, `TN`, `FP`, `FN`, `precision`, `recall`, `F1/F2`, `accuracy`, `specificity`
|
|
210
227
|
|
|
211
|
-
**Non-Binary Metrics:** `cor`, `inc`, `mis`, `spu`, `precision/recall/F1/F2 (micro
|
|
228
|
+
**Non-Binary Metrics:** `cor`, `inc`, `mis`, `spu`, `TN`, `precision/recall/F1/F2 (micro and macro)`, `specificity`
|
|
229
|
+
|
|
230
|
+
Applicability: `cor`, `mis`, `spu` and the `(micro)` precision/recall/F-scores apply to all non-binary fields; `inc`, `TN` and `specificity` are meaningful for **scalar fields only**; the `(macro)` metrics are averages of the per-row metrics and exist for **list fields only**. `accuracy` and `specificity` carry no `(micro)`/`(macro)` tag: they are only ever computed one way (pooled counts), since a per-row version would be a 0/1 indicator whose average equals the pooled value.
|
|
212
231
|
|
|
213
232
|
## ⚡ Performance Metrics Explained
|
|
233
|
+
|
|
234
|
+

|
|
235
|
+
|
|
214
236
|
### Binary Classification Metrics
|
|
215
237
|
|
|
216
238
|
For fields with True/False values (e.g., "Has metastasis"):
|
|
@@ -241,6 +263,7 @@ For scalar and list fields (e.g., "Diagnosis", "Treatment Drugs"):
|
|
|
241
263
|
| **Missing (Mis)** | Items present in label but not extracted | (Same example) → Mis=1 (DrugB missing) |
|
|
242
264
|
| **Spurious (Spu)** | Items extracted but not in label | Label: `["DrugA"]`, Prediction: `["DrugA", "DrugC"]` → Spu=1 |
|
|
243
265
|
| **Incorrect (Inc)** | Wrong values for scalar fields | Label: `"Cancer"`, Prediction: `"Diabetes"` → Inc=1 |
|
|
266
|
+
| **True Negative (TN)** | Scalar fields only: field correctly left empty | Label: `"-"`, Prediction: `""`/`"-"` → TN=1 |
|
|
244
267
|
|
|
245
268
|
#### Structured Extraction Formulas
|
|
246
269
|
|
|
@@ -248,8 +271,9 @@ For scalar and list fields (e.g., "Diagnosis", "Treatment Drugs"):
|
|
|
248
271
|
|--------|---------|---------|
|
|
249
272
|
| **Precision** | `Cor / (Cor + Spu + Inc)` | Of all extracted items, how many were correct? |
|
|
250
273
|
| **Recall** | `Cor / (Cor + Mis + Inc)` | Of all labeled items, how many were correctly extracted? |
|
|
274
|
+
| **Specificity** | `TN / (TN + Spu)` | Scalar fields only: of all cases labeled as having no information, how many were correctly left empty? |
|
|
251
275
|
|
|
252
|
-
**Note:**
|
|
276
|
+
**Note:** Inc and TN (and therefore specificity) are defined only for scalar fields. For list fields, extracted items are always classified as correct, missing, or spurious — Inc stays empty and no TN column is emitted.
|
|
253
277
|
|
|
254
278
|
The following formulas apply to both binary classification and structured extraction metrics:
|
|
255
279
|
|
|
@@ -260,13 +284,51 @@ The following formulas apply to both binary classification and structured extrac
|
|
|
260
284
|
|
|
261
285
|
Where P = Precision and R = Recall (calculated differently for each metric type).
|
|
262
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
|
+
|
|
263
325
|
## Bootstrap Confidence Intervals
|
|
264
326
|
|
|
265
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.
|
|
266
328
|
|
|
267
329
|
### Usage
|
|
268
330
|
```python
|
|
269
|
-
from
|
|
331
|
+
from llmvalidate import bootstrap_CI
|
|
270
332
|
|
|
271
333
|
# After running validation to get results_df
|
|
272
334
|
ci_results = bootstrap_CI(
|
|
@@ -347,7 +409,7 @@ pip install -r requirements.txt
|
|
|
347
409
|
pytest
|
|
348
410
|
|
|
349
411
|
# Run with coverage reporting
|
|
350
|
-
pytest --cov=
|
|
412
|
+
pytest --cov=llmvalidate
|
|
351
413
|
|
|
352
414
|
# Run specific test modules
|
|
353
415
|
pytest tests/validate_test.py # Core validation logic
|
|
@@ -1,19 +1,27 @@
|
|
|
1
1
|
# LLM Validation Framework
|
|
2
2
|
|
|
3
|
-
[](https://github.com/Oncoshot/llm-validation-framework/actions)
|
|
4
4
|
[](https://pypi.org/project/llmvalidate/)
|
|
5
5
|
[](https://pypi.org/project/llmvalidate/)
|
|
6
|
-
[](https://github.com/Oncoshot/llm-validation-framework/blob/master/LICENSE)
|
|
7
|
+
[](https://github.com/Oncoshot/llm-validation-framework/stargazers)
|
|
8
8
|
|
|
9
9
|
A comprehensive Python framework for evaluating LLM-extracted structured data against ground truth labels. Supports binary classification, scalar values, and list fields with detailed performance metrics, confidence-based evaluation, and statistical uncertainty quantification via non-parametric bootstrap confidence intervals.
|
|
10
10
|
|
|
11
|
+
## 📄 Paper
|
|
12
|
+
|
|
13
|
+
The methodology behind this framework is described in a medRxiv preprint:
|
|
14
|
+
[medRxiv 2026.05.18.26353541](https://www.medrxiv.org/content/10.64898/2026.05.18.26353541v1) — DOI: [10.64898/2026.05.18.26353541](https://doi.org/10.64898/2026.05.18.26353541)
|
|
15
|
+
|
|
11
16
|
## ✨ Key Features
|
|
12
17
|
|
|
13
18
|
- **Multi-field validation** - Binary (True/False), scalar (single values), and list (multiple values) data types
|
|
19
|
+
- **Coded field support** - Score a value together with its code (ICD-10 / ICD-O-3, RxNorm) as two independent facets
|
|
14
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".
|
|
15
23
|
- **Dual usage modes** - Validate pre-computed results OR run live LLM inference with validation
|
|
16
|
-
- **Comprehensive metrics** - Precision, recall, F1/F2, accuracy, specificity with
|
|
24
|
+
- **Comprehensive metrics** - Precision, recall, F1/F2, accuracy, specificity, with micro and macro aggregation where applicable
|
|
17
25
|
- **Confidence analysis** - Automatic performance breakdown by confidence levels
|
|
18
26
|
- **Statistical uncertainty** - Non-parametric bootstrap confidence intervals for all performance metrics
|
|
19
27
|
- **Production ready** - Parallel processing, intelligent caching, detailed progress tracking
|
|
@@ -36,14 +44,14 @@ python runme.py
|
|
|
36
44
|
|
|
37
45
|
Processes the included [samples.csv](samples.csv) (14 test cases covering all validation scenarios) and outputs timestamped results to `validation_results/samples/`:
|
|
38
46
|
|
|
39
|
-
- **[Results CSV](validation_results/samples/2026-
|
|
40
|
-
- **[Metrics CSV](validation_results/samples/2026-
|
|
41
|
-
- **[CI Metrics CSV](validation_results/samples/2026-
|
|
47
|
+
- **[Results CSV](validation_results/samples/2026-07-13%2001-12-18%20results.csv)** - Row-by-row comparison with confusion matrix counts and item-level details
|
|
48
|
+
- **[Metrics CSV](validation_results/samples/2026-07-13%2001-12-18%20metrics.csv)** - Aggregated performance statistics with confidence breakdowns
|
|
49
|
+
- **[CI Metrics CSV](validation_results/samples/2026-07-13%2001-12-18%20CI%20metrics.csv)** - Confidence intervals for metrics
|
|
42
50
|
|
|
43
51
|
| Rows | Field Type | Test Scenarios |
|
|
44
52
|
|------|------------|----------------|
|
|
45
53
|
| **1-4** | Binary (`Has metastasis`) | True Positive, True Negative, False Positive, False Negative |
|
|
46
|
-
| **5-9** | Scalar (`Diagnosis`, `Histology`) | Correct, incorrect, missing, spurious, and empty extractions |
|
|
54
|
+
| **5-9** | Scalar (`Diagnosis`, `Histology`) | Correct, incorrect, missing, spurious, and correct-empty (TN) extractions |
|
|
47
55
|
| **10-14** | List (`Treatment Drugs`, `Test Results`) | Perfect match, spurious items, missing items, correct empty, mixed results |
|
|
48
56
|
|
|
49
57
|
## 📊 Usage Modes
|
|
@@ -53,7 +61,7 @@ When you have LLM predictions in `Res: {Field Name}` columns:
|
|
|
53
61
|
|
|
54
62
|
```python
|
|
55
63
|
import pandas as pd
|
|
56
|
-
from
|
|
64
|
+
from llmvalidate import validate
|
|
57
65
|
|
|
58
66
|
df = pd.read_csv("data.csv", index_col="Patient ID")
|
|
59
67
|
# df must contain: "Field Name" and "Res: Field Name" columns
|
|
@@ -69,8 +77,8 @@ results_df, metrics_df = validate(
|
|
|
69
77
|
### Mode 2: Live LLM Inference + Validation
|
|
70
78
|
|
|
71
79
|
```python
|
|
72
|
-
from
|
|
73
|
-
from
|
|
80
|
+
from llmvalidate.structured import StructuredResult, StructuredGroup, StructuredField
|
|
81
|
+
from llmvalidate.utils import flatten_structured_result
|
|
74
82
|
|
|
75
83
|
def llm_callback(row, i, raw_text_column_name):
|
|
76
84
|
raw_text = row[raw_text_column_name]
|
|
@@ -140,6 +148,14 @@ with the `-value` / `-code` label columns.
|
|
|
140
148
|
- **`null/empty/NaN`** = Field not labeled/evaluated (supports partial labeling where different cases may have labels for different field subsets)
|
|
141
149
|
- **Lists** - Can be Python lists `["a", "b"]` or stringified `"['a', 'b']"` (auto-converted)
|
|
142
150
|
|
|
151
|
+
The `"-"`-vs-empty distinction above applies to **label** columns only. In **prediction** (`Res:`)
|
|
152
|
+
columns there is no "not evaluated" state: `"-"`, `""`, `null`/`NaN`, whitespace-only strings and
|
|
153
|
+
`[]` are all treated identically as "nothing extracted" (scoring Mis against a labeled value, or
|
|
154
|
+
TN when the label is `"-"`). We still recommend emitting `"-"` uniformly, to keep predictions
|
|
155
|
+
symmetric with labels. **Exception — binary fields:** predictions must be an explicit
|
|
156
|
+
`True`/`False`; an empty prediction is "not True / not False", so it scores FN against a `True`
|
|
157
|
+
label and **FP** against a `False` label.
|
|
158
|
+
|
|
143
159
|
### Partial Labeling Support
|
|
144
160
|
The framework supports partial labeling scenarios where:
|
|
145
161
|
- Not every case needs labels for every field
|
|
@@ -150,7 +166,7 @@ The framework supports partial labeling scenarios where:
|
|
|
150
166
|
|
|
151
167
|
## 📈 Output Files
|
|
152
168
|
|
|
153
|
-
|
|
169
|
+
A `validate()` run generates two timestamped CSV files (a third, CI metrics, is added when you also run `bootstrap_CI` — see the demo above):
|
|
154
170
|
|
|
155
171
|
### 1. Results CSV (`YYYY-MM-DD HH-MM-SS results.csv`)
|
|
156
172
|
**Row-level analysis** with detailed per-case metrics:
|
|
@@ -164,8 +180,9 @@ The framework generates two timestamped CSV files for each validation run:
|
|
|
164
180
|
- `TP/FP/FN/TN: {Field}` - Confusion matrix counts (1 or 0 per row)
|
|
165
181
|
|
|
166
182
|
**Non-Binary Fields:**
|
|
167
|
-
- `Cor/
|
|
183
|
+
- `Cor/Mis/Spu: {Field}` - Item counts per row (Inc and TN are None for list fields)
|
|
168
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))
|
|
169
186
|
- `Precision/Recall/F1/F2: {Field}` - Per-row metrics (list fields only)
|
|
170
187
|
|
|
171
188
|
**System Columns:**
|
|
@@ -184,9 +201,14 @@ The framework generates two timestamped CSV files for each validation run:
|
|
|
184
201
|
|
|
185
202
|
**Binary Metrics:** `TP`, `TN`, `FP`, `FN`, `precision`, `recall`, `F1/F2`, `accuracy`, `specificity`
|
|
186
203
|
|
|
187
|
-
**Non-Binary Metrics:** `cor`, `inc`, `mis`, `spu`, `precision/recall/F1/F2 (micro
|
|
204
|
+
**Non-Binary Metrics:** `cor`, `inc`, `mis`, `spu`, `TN`, `precision/recall/F1/F2 (micro and macro)`, `specificity`
|
|
205
|
+
|
|
206
|
+
Applicability: `cor`, `mis`, `spu` and the `(micro)` precision/recall/F-scores apply to all non-binary fields; `inc`, `TN` and `specificity` are meaningful for **scalar fields only**; the `(macro)` metrics are averages of the per-row metrics and exist for **list fields only**. `accuracy` and `specificity` carry no `(micro)`/`(macro)` tag: they are only ever computed one way (pooled counts), since a per-row version would be a 0/1 indicator whose average equals the pooled value.
|
|
188
207
|
|
|
189
208
|
## ⚡ Performance Metrics Explained
|
|
209
|
+
|
|
210
|
+

|
|
211
|
+
|
|
190
212
|
### Binary Classification Metrics
|
|
191
213
|
|
|
192
214
|
For fields with True/False values (e.g., "Has metastasis"):
|
|
@@ -217,6 +239,7 @@ For scalar and list fields (e.g., "Diagnosis", "Treatment Drugs"):
|
|
|
217
239
|
| **Missing (Mis)** | Items present in label but not extracted | (Same example) → Mis=1 (DrugB missing) |
|
|
218
240
|
| **Spurious (Spu)** | Items extracted but not in label | Label: `["DrugA"]`, Prediction: `["DrugA", "DrugC"]` → Spu=1 |
|
|
219
241
|
| **Incorrect (Inc)** | Wrong values for scalar fields | Label: `"Cancer"`, Prediction: `"Diabetes"` → Inc=1 |
|
|
242
|
+
| **True Negative (TN)** | Scalar fields only: field correctly left empty | Label: `"-"`, Prediction: `""`/`"-"` → TN=1 |
|
|
220
243
|
|
|
221
244
|
#### Structured Extraction Formulas
|
|
222
245
|
|
|
@@ -224,8 +247,9 @@ For scalar and list fields (e.g., "Diagnosis", "Treatment Drugs"):
|
|
|
224
247
|
|--------|---------|---------|
|
|
225
248
|
| **Precision** | `Cor / (Cor + Spu + Inc)` | Of all extracted items, how many were correct? |
|
|
226
249
|
| **Recall** | `Cor / (Cor + Mis + Inc)` | Of all labeled items, how many were correctly extracted? |
|
|
250
|
+
| **Specificity** | `TN / (TN + Spu)` | Scalar fields only: of all cases labeled as having no information, how many were correctly left empty? |
|
|
227
251
|
|
|
228
|
-
**Note:**
|
|
252
|
+
**Note:** Inc and TN (and therefore specificity) are defined only for scalar fields. For list fields, extracted items are always classified as correct, missing, or spurious — Inc stays empty and no TN column is emitted.
|
|
229
253
|
|
|
230
254
|
The following formulas apply to both binary classification and structured extraction metrics:
|
|
231
255
|
|
|
@@ -236,13 +260,51 @@ The following formulas apply to both binary classification and structured extrac
|
|
|
236
260
|
|
|
237
261
|
Where P = Precision and R = Recall (calculated differently for each metric type).
|
|
238
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
|
+
|
|
239
301
|
## Bootstrap Confidence Intervals
|
|
240
302
|
|
|
241
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.
|
|
242
304
|
|
|
243
305
|
### Usage
|
|
244
306
|
```python
|
|
245
|
-
from
|
|
307
|
+
from llmvalidate import bootstrap_CI
|
|
246
308
|
|
|
247
309
|
# After running validation to get results_df
|
|
248
310
|
ci_results = bootstrap_CI(
|
|
@@ -323,7 +385,7 @@ pip install -r requirements.txt
|
|
|
323
385
|
pytest
|
|
324
386
|
|
|
325
387
|
# Run with coverage reporting
|
|
326
|
-
pytest --cov=
|
|
388
|
+
pytest --cov=llmvalidate
|
|
327
389
|
|
|
328
390
|
# Run specific test modules
|
|
329
391
|
pytest tests/validate_test.py # Core validation logic
|
|
@@ -359,4 +421,4 @@ llm-validation-framework/
|
|
|
359
421
|
|
|
360
422
|
## 📄 License
|
|
361
423
|
|
|
362
|
-
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
424
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
@@ -63,31 +63,55 @@ 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,
|
|
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
|
-
'
|
|
73
|
-
|
|
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
|
|
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
|
|
83
|
+
'Par: ' for Partial (only when the field has a hierarchy entry)
|
|
84
|
+
'TN: ' for True Negative (scalar fields only; not defined for list fields)
|
|
82
85
|
"""
|
|
83
86
|
|
|
84
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)
|
|
85
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
|
+
|
|
86
100
|
# Determine which fields are binary by looking at the unique non-empty expected values.
|
|
87
101
|
binary_fields = {}
|
|
88
102
|
for field in fields:
|
|
89
103
|
binary_fields[field] = pd.api.types.is_bool_dtype(pd.api.types.infer_dtype(df[field].dropna()))
|
|
90
104
|
|
|
105
|
+
# Determine which fields are list fields (any label or result value is a list).
|
|
106
|
+
# TN is only defined for scalar fields, so list fields never get a 'TN: ' column.
|
|
107
|
+
list_fields = {}
|
|
108
|
+
for field in fields:
|
|
109
|
+
is_list = df[field].map(type).eq(list).any()
|
|
110
|
+
res_col = 'Res: ' + field
|
|
111
|
+
if not is_list and res_col in df.columns:
|
|
112
|
+
is_list = df[res_col].map(type).eq(list).any()
|
|
113
|
+
list_fields[field] = is_list
|
|
114
|
+
|
|
91
115
|
# Create a list to store modified rows
|
|
92
116
|
modified_rows = []
|
|
93
117
|
# Iterate over the rows of the DataFrame
|
|
@@ -101,12 +125,15 @@ def compare_results_all(df, fields, parents={}, comparison_callback=None, raw_te
|
|
|
101
125
|
|
|
102
126
|
actual = row['Res: ' + field]
|
|
103
127
|
|
|
104
|
-
|
|
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]:
|
|
105
132
|
# For binary fields, use the binary comparison function.
|
|
106
133
|
res = compare_results_binary(expected, actual)
|
|
107
134
|
res_items = {}
|
|
108
135
|
else:
|
|
109
|
-
res_items = compare_results(expected, actual,
|
|
136
|
+
res_items = compare_results(expected, actual, field_hierarchy)
|
|
110
137
|
|
|
111
138
|
# Convert lists to counts, preserving None values
|
|
112
139
|
res = {key: len(value) if value is not None else None for key, value in res_items.items()}
|
|
@@ -124,16 +151,33 @@ def compare_results_all(df, fields, parents={}, comparison_callback=None, raw_te
|
|
|
124
151
|
row['F1 score: ' + field] = f1_score
|
|
125
152
|
row['F2 score: ' + field] = f2_score
|
|
126
153
|
|
|
127
|
-
if not
|
|
128
|
-
#we don't want useless columns if no
|
|
154
|
+
if not field_hierarchy:
|
|
155
|
+
#we don't want useless columns if no hierarchy for this field anyway
|
|
129
156
|
del res['Incorrect'] #incorrect appear only if parent mismatch (only for lists)
|
|
130
157
|
del res_items['Incorrect']
|
|
131
158
|
|
|
132
|
-
if not
|
|
133
|
-
#we don't want useless columns if no
|
|
159
|
+
if not field_hierarchy:
|
|
160
|
+
#we don't want useless columns if no hierarchy for this field anyway
|
|
134
161
|
del res['Partial'] #partial appear only if parent match
|
|
135
162
|
del res_items['Partial']
|
|
136
163
|
|
|
164
|
+
if not list_fields[field]:
|
|
165
|
+
# Scalar field: report per-case TN so true negatives (field correctly
|
|
166
|
+
# left empty) are visible row by row. TN = 1 if the case was labeled
|
|
167
|
+
# as "No information" (label '-') AND the prediction is empty.
|
|
168
|
+
# None (undefined) when the case was not labeled for this field.
|
|
169
|
+
# TN is not defined for list fields (see get_metrics).
|
|
170
|
+
if res['Correct'] is None:
|
|
171
|
+
row['TN: ' + field] = None
|
|
172
|
+
#row['TN: ' + field + ' items'] = None
|
|
173
|
+
else:
|
|
174
|
+
TN_case = 1 if (is_scalar_empty(normalize(expected))
|
|
175
|
+
and is_scalar_empty(normalize(actual))) else 0
|
|
176
|
+
row['TN: ' + field] = TN_case
|
|
177
|
+
# a TN case has no extracted item: the matched "item" is the
|
|
178
|
+
# no-information marker itself therefore pointless to add
|
|
179
|
+
# row['TN: ' + field + ' items'] = ['-'] if TN_case else []
|
|
180
|
+
|
|
137
181
|
# Iterate over the key-value pairs in the result dictionary
|
|
138
182
|
for key, value in res.items():
|
|
139
183
|
# Create a new column in the DataFrame using the key
|
|
@@ -264,7 +308,7 @@ def get_metrics(res_df, fields):
|
|
|
264
308
|
'labeled cases': labeled_cases,
|
|
265
309
|
'field-present cases': exceptions_no,
|
|
266
310
|
'TP': None, 'TN': None, 'FP': None, 'FN': None,
|
|
267
|
-
'precision (micro)': None, 'recall (micro)': None, 'F1 score (micro)': None, 'F2 score (micro)': None, 'accuracy
|
|
311
|
+
'precision (micro)': None, 'recall (micro)': None, 'F1 score (micro)': None, 'F2 score (micro)': None, 'accuracy': None, 'specificity': None,
|
|
268
312
|
'cor': None, 'inc': None, 'mis': None, 'spu': None, 'par': None,
|
|
269
313
|
'precision (macro)': None, 'recall (macro)': None, 'F1 score (macro)': None, 'F2 score (macro)': None
|
|
270
314
|
})
|
|
@@ -330,6 +374,7 @@ def get_metrics(res_df, fields):
|
|
|
330
374
|
mis = field_df['Mis: ' + field].sum()
|
|
331
375
|
spu = field_df['Spu: ' + field].sum()
|
|
332
376
|
par = field_df['Par: ' + field].sum() if 'Par: ' + field in field_df else None
|
|
377
|
+
TN = field_df['TN: ' + field].sum() if 'TN: ' + field in field_df else None
|
|
333
378
|
|
|
334
379
|
if 'Precision: ' + field in field_df:
|
|
335
380
|
# if Precision present it means that it is a list field
|
|
@@ -337,15 +382,8 @@ def get_metrics(res_df, fields):
|
|
|
337
382
|
recall_macro = field_df['Recall: ' + field].mean()
|
|
338
383
|
f1_score_macro = field_df['F1 score: ' + field].mean()
|
|
339
384
|
f2_score_macro = field_df['F2 score: ' + field].mean()
|
|
340
|
-
|
|
341
|
-
# TN is not defined for list values (e.g. label ['apple'] and prediction ['orange', 'banana'] will produce SPU=2)
|
|
342
|
-
TN_field = None
|
|
343
|
-
else:
|
|
344
|
-
# scalar field
|
|
345
|
-
TN_field = labeled_cases - field_present_cases - spu
|
|
346
|
-
|
|
347
385
|
precision_micro, recall_micro, f1_score_micro, f2_score_micro, specificity_micro = calculate_metrics(
|
|
348
|
-
cor, par or 0, inc or 0, spu, mis,
|
|
386
|
+
cor, par or 0, inc or 0, spu, mis, TN
|
|
349
387
|
)
|
|
350
388
|
|
|
351
389
|
# Append computed row as a dictionary
|
|
@@ -362,8 +400,8 @@ def get_metrics(res_df, fields):
|
|
|
362
400
|
'recall (micro)': recall_micro,
|
|
363
401
|
'F1 score (micro)': f1_score_micro,
|
|
364
402
|
'F2 score (micro)': f2_score_micro,
|
|
365
|
-
'accuracy
|
|
366
|
-
'specificity
|
|
403
|
+
'accuracy': accuracy_micro,
|
|
404
|
+
'specificity': specificity_micro,
|
|
367
405
|
'cor': cor,
|
|
368
406
|
'inc': inc,
|
|
369
407
|
'mis': mis,
|
|
@@ -386,7 +424,7 @@ def get_metrics(res_df, fields):
|
|
|
386
424
|
|
|
387
425
|
return metrics
|
|
388
426
|
|
|
389
|
-
def compare_results(expected, actual,
|
|
427
|
+
def compare_results(expected, actual, hierarchy={}):
|
|
390
428
|
"""
|
|
391
429
|
Compares expected results with actual results, ignoring duplicates.
|
|
392
430
|
|
|
@@ -405,7 +443,7 @@ def compare_results(expected, actual, parents={}):
|
|
|
405
443
|
Args:
|
|
406
444
|
expected (int, float, str, list): The expected result.
|
|
407
445
|
actual (int, float, str, list): The actual result.
|
|
408
|
-
|
|
446
|
+
hierarchy : A flat dictionary where key is a child and value is a parent for partial match
|
|
409
447
|
|
|
410
448
|
Returns:
|
|
411
449
|
dict: A dictionary with keys 'Correct', 'Incorrect', 'Missing', 'Spurious', and 'Partial', mapping to their respective lists.
|
|
@@ -446,8 +484,10 @@ def compare_results(expected, actual, parents={}):
|
|
|
446
484
|
[a] None None None None None
|
|
447
485
|
"""
|
|
448
486
|
|
|
449
|
-
#
|
|
450
|
-
|
|
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()}
|
|
451
491
|
|
|
452
492
|
output = {'Correct': [], 'Incorrect': [], 'Missing': [], 'Spurious': [], 'Partial': []}
|
|
453
493
|
|
|
@@ -458,21 +498,21 @@ def compare_results(expected, actual, parents={}):
|
|
|
458
498
|
# Convert all elements to lowercase strings for case-insensitive comparison
|
|
459
499
|
# and remove duplicates by converting to sets.
|
|
460
500
|
expected_set = normalize_list(expected)
|
|
461
|
-
expected_parents_set = {
|
|
462
|
-
|
|
501
|
+
expected_parents_set = {hierarchy[s] for s in expected_set if s in hierarchy}
|
|
502
|
+
|
|
463
503
|
actual_set = normalize_list(actual)
|
|
464
|
-
actual_parents_set = {
|
|
504
|
+
actual_parents_set = {hierarchy[s] for s in actual_set if s in hierarchy}
|
|
465
505
|
|
|
466
506
|
output['Correct'] = list(expected_set & actual_set) # matching exactly
|
|
467
507
|
|
|
468
508
|
for missing in expected_set - actual_set - actual_parents_set:
|
|
469
|
-
if missing in
|
|
509
|
+
if missing in hierarchy and hierarchy[missing] in actual_set:
|
|
470
510
|
output['Partial'].append(missing) # actual set has parent value therefore Partial
|
|
471
511
|
else:
|
|
472
512
|
output['Missing'].append(missing)
|
|
473
513
|
|
|
474
514
|
for spurious in actual_set - expected_set - expected_parents_set:
|
|
475
|
-
if spurious in
|
|
515
|
+
if spurious in hierarchy and hierarchy[spurious] in expected_set:
|
|
476
516
|
output['Incorrect'].append(spurious) # expected set has parent value therefore Incorrect
|
|
477
517
|
else:
|
|
478
518
|
output['Spurious'].append(spurious)
|
|
@@ -494,7 +534,7 @@ def compare_results(expected, actual, parents={}):
|
|
|
494
534
|
output['Spurious'] = [actual]
|
|
495
535
|
elif not is_scalar_empty(expected) and is_scalar_empty(actual):
|
|
496
536
|
output['Missing'] = [expected]
|
|
497
|
-
elif expected in
|
|
537
|
+
elif expected in hierarchy and hierarchy[expected] == actual:
|
|
498
538
|
output['Partial'] = [expected] # actual value is a parent of expected
|
|
499
539
|
else:
|
|
500
540
|
output['Incorrect'] = [actual]
|
|
@@ -613,7 +653,7 @@ def _reorder_result_columns(df: pd.DataFrame) -> pd.DataFrame:
|
|
|
613
653
|
res_cols_all = [c for c in cols if c.startswith('Res: ')]
|
|
614
654
|
|
|
615
655
|
metric_prefixes_binary_counts = ["TP: ", "FP: ", "FN: ", "TN: "]
|
|
616
|
-
metric_prefixes_non_binary_counts = ["Cor: ", "Inc: ", "Mis: ", "Spu: ", "Par: "]
|
|
656
|
+
metric_prefixes_non_binary_counts = ["Cor: ", "Inc: ", "Mis: ", "Spu: ", "Par: ", "TN: "]
|
|
617
657
|
metric_prefixes = ["Precision: ", "Recall: ", "Accuracy: ", "F1 score: ", "F2 score: ", "Specificity: "]
|
|
618
658
|
|
|
619
659
|
metric_prefixes_all = metric_prefixes_binary_counts + metric_prefixes_non_binary_counts + metric_prefixes
|
|
@@ -799,7 +839,8 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
|
|
|
799
839
|
raw_text_column_name = 'raw_text',
|
|
800
840
|
comparison_callback = None,
|
|
801
841
|
max_workers: int | None = 1,
|
|
802
|
-
use_threads: bool = True
|
|
842
|
+
use_threads: bool = True,
|
|
843
|
+
hierarchy = {}):
|
|
803
844
|
"""
|
|
804
845
|
Performs validation by applying a structuring callback to an input dataset and evaluating performance.
|
|
805
846
|
|
|
@@ -823,10 +864,20 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
|
|
|
823
864
|
A callback function that will be applied to each row to generate structured predictions.
|
|
824
865
|
If None, assumes that source_df already contains "Res: " columns with results.
|
|
825
866
|
|
|
826
|
-
- **comparison_callback (callable, optional)**:
|
|
867
|
+
- **comparison_callback (callable, optional)**:
|
|
827
868
|
A callback function that will be applied to each row to generate comparison results.
|
|
828
869
|
|
|
829
|
-
- **
|
|
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)**:
|
|
830
881
|
Directory where the output CSV files will be saved.
|
|
831
882
|
If not provided, results will only be returned as DataFrames.
|
|
832
883
|
|
|
@@ -895,7 +946,7 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
|
|
|
895
946
|
|
|
896
947
|
###################################
|
|
897
948
|
# Analyse the results and calculate the metrics
|
|
898
|
-
res_df = compare_results_all(res_df, fields,
|
|
949
|
+
res_df = compare_results_all(res_df, fields, hierarchy=hierarchy, comparison_callback=comparison_callback, raw_text_column_name=raw_text_column_name)
|
|
899
950
|
|
|
900
951
|
# Save results
|
|
901
952
|
if output_folder:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: llmvalidate
|
|
3
|
-
Version: 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
|
|
@@ -24,20 +24,28 @@ Dynamic: license-file
|
|
|
24
24
|
|
|
25
25
|
# LLM Validation Framework
|
|
26
26
|
|
|
27
|
-
[](https://github.com/Oncoshot/llm-validation-framework/actions)
|
|
28
28
|
[](https://pypi.org/project/llmvalidate/)
|
|
29
29
|
[](https://pypi.org/project/llmvalidate/)
|
|
30
|
-
[](https://github.com/Oncoshot/llm-validation-framework/blob/master/LICENSE)
|
|
31
|
+
[](https://github.com/Oncoshot/llm-validation-framework/stargazers)
|
|
32
32
|
|
|
33
33
|
A comprehensive Python framework for evaluating LLM-extracted structured data against ground truth labels. Supports binary classification, scalar values, and list fields with detailed performance metrics, confidence-based evaluation, and statistical uncertainty quantification via non-parametric bootstrap confidence intervals.
|
|
34
34
|
|
|
35
|
+
## 📄 Paper
|
|
36
|
+
|
|
37
|
+
The methodology behind this framework is described in a medRxiv preprint:
|
|
38
|
+
[medRxiv 2026.05.18.26353541](https://www.medrxiv.org/content/10.64898/2026.05.18.26353541v1) — DOI: [10.64898/2026.05.18.26353541](https://doi.org/10.64898/2026.05.18.26353541)
|
|
39
|
+
|
|
35
40
|
## ✨ Key Features
|
|
36
41
|
|
|
37
42
|
- **Multi-field validation** - Binary (True/False), scalar (single values), and list (multiple values) data types
|
|
43
|
+
- **Coded field support** - Score a value together with its code (ICD-10 / ICD-O-3, RxNorm) as two independent facets
|
|
38
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".
|
|
39
47
|
- **Dual usage modes** - Validate pre-computed results OR run live LLM inference with validation
|
|
40
|
-
- **Comprehensive metrics** - Precision, recall, F1/F2, accuracy, specificity with
|
|
48
|
+
- **Comprehensive metrics** - Precision, recall, F1/F2, accuracy, specificity, with micro and macro aggregation where applicable
|
|
41
49
|
- **Confidence analysis** - Automatic performance breakdown by confidence levels
|
|
42
50
|
- **Statistical uncertainty** - Non-parametric bootstrap confidence intervals for all performance metrics
|
|
43
51
|
- **Production ready** - Parallel processing, intelligent caching, detailed progress tracking
|
|
@@ -60,14 +68,14 @@ python runme.py
|
|
|
60
68
|
|
|
61
69
|
Processes the included [samples.csv](samples.csv) (14 test cases covering all validation scenarios) and outputs timestamped results to `validation_results/samples/`:
|
|
62
70
|
|
|
63
|
-
- **[Results CSV](validation_results/samples/2026-
|
|
64
|
-
- **[Metrics CSV](validation_results/samples/2026-
|
|
65
|
-
- **[CI Metrics CSV](validation_results/samples/2026-
|
|
71
|
+
- **[Results CSV](validation_results/samples/2026-07-13%2001-12-18%20results.csv)** - Row-by-row comparison with confusion matrix counts and item-level details
|
|
72
|
+
- **[Metrics CSV](validation_results/samples/2026-07-13%2001-12-18%20metrics.csv)** - Aggregated performance statistics with confidence breakdowns
|
|
73
|
+
- **[CI Metrics CSV](validation_results/samples/2026-07-13%2001-12-18%20CI%20metrics.csv)** - Confidence intervals for metrics
|
|
66
74
|
|
|
67
75
|
| Rows | Field Type | Test Scenarios |
|
|
68
76
|
|------|------------|----------------|
|
|
69
77
|
| **1-4** | Binary (`Has metastasis`) | True Positive, True Negative, False Positive, False Negative |
|
|
70
|
-
| **5-9** | Scalar (`Diagnosis`, `Histology`) | Correct, incorrect, missing, spurious, and empty extractions |
|
|
78
|
+
| **5-9** | Scalar (`Diagnosis`, `Histology`) | Correct, incorrect, missing, spurious, and correct-empty (TN) extractions |
|
|
71
79
|
| **10-14** | List (`Treatment Drugs`, `Test Results`) | Perfect match, spurious items, missing items, correct empty, mixed results |
|
|
72
80
|
|
|
73
81
|
## 📊 Usage Modes
|
|
@@ -77,7 +85,7 @@ When you have LLM predictions in `Res: {Field Name}` columns:
|
|
|
77
85
|
|
|
78
86
|
```python
|
|
79
87
|
import pandas as pd
|
|
80
|
-
from
|
|
88
|
+
from llmvalidate import validate
|
|
81
89
|
|
|
82
90
|
df = pd.read_csv("data.csv", index_col="Patient ID")
|
|
83
91
|
# df must contain: "Field Name" and "Res: Field Name" columns
|
|
@@ -93,8 +101,8 @@ results_df, metrics_df = validate(
|
|
|
93
101
|
### Mode 2: Live LLM Inference + Validation
|
|
94
102
|
|
|
95
103
|
```python
|
|
96
|
-
from
|
|
97
|
-
from
|
|
104
|
+
from llmvalidate.structured import StructuredResult, StructuredGroup, StructuredField
|
|
105
|
+
from llmvalidate.utils import flatten_structured_result
|
|
98
106
|
|
|
99
107
|
def llm_callback(row, i, raw_text_column_name):
|
|
100
108
|
raw_text = row[raw_text_column_name]
|
|
@@ -164,6 +172,14 @@ with the `-value` / `-code` label columns.
|
|
|
164
172
|
- **`null/empty/NaN`** = Field not labeled/evaluated (supports partial labeling where different cases may have labels for different field subsets)
|
|
165
173
|
- **Lists** - Can be Python lists `["a", "b"]` or stringified `"['a', 'b']"` (auto-converted)
|
|
166
174
|
|
|
175
|
+
The `"-"`-vs-empty distinction above applies to **label** columns only. In **prediction** (`Res:`)
|
|
176
|
+
columns there is no "not evaluated" state: `"-"`, `""`, `null`/`NaN`, whitespace-only strings and
|
|
177
|
+
`[]` are all treated identically as "nothing extracted" (scoring Mis against a labeled value, or
|
|
178
|
+
TN when the label is `"-"`). We still recommend emitting `"-"` uniformly, to keep predictions
|
|
179
|
+
symmetric with labels. **Exception — binary fields:** predictions must be an explicit
|
|
180
|
+
`True`/`False`; an empty prediction is "not True / not False", so it scores FN against a `True`
|
|
181
|
+
label and **FP** against a `False` label.
|
|
182
|
+
|
|
167
183
|
### Partial Labeling Support
|
|
168
184
|
The framework supports partial labeling scenarios where:
|
|
169
185
|
- Not every case needs labels for every field
|
|
@@ -174,7 +190,7 @@ The framework supports partial labeling scenarios where:
|
|
|
174
190
|
|
|
175
191
|
## 📈 Output Files
|
|
176
192
|
|
|
177
|
-
|
|
193
|
+
A `validate()` run generates two timestamped CSV files (a third, CI metrics, is added when you also run `bootstrap_CI` — see the demo above):
|
|
178
194
|
|
|
179
195
|
### 1. Results CSV (`YYYY-MM-DD HH-MM-SS results.csv`)
|
|
180
196
|
**Row-level analysis** with detailed per-case metrics:
|
|
@@ -188,8 +204,9 @@ The framework generates two timestamped CSV files for each validation run:
|
|
|
188
204
|
- `TP/FP/FN/TN: {Field}` - Confusion matrix counts (1 or 0 per row)
|
|
189
205
|
|
|
190
206
|
**Non-Binary Fields:**
|
|
191
|
-
- `Cor/
|
|
207
|
+
- `Cor/Mis/Spu: {Field}` - Item counts per row (Inc and TN are None for list fields)
|
|
192
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))
|
|
193
210
|
- `Precision/Recall/F1/F2: {Field}` - Per-row metrics (list fields only)
|
|
194
211
|
|
|
195
212
|
**System Columns:**
|
|
@@ -208,9 +225,14 @@ The framework generates two timestamped CSV files for each validation run:
|
|
|
208
225
|
|
|
209
226
|
**Binary Metrics:** `TP`, `TN`, `FP`, `FN`, `precision`, `recall`, `F1/F2`, `accuracy`, `specificity`
|
|
210
227
|
|
|
211
|
-
**Non-Binary Metrics:** `cor`, `inc`, `mis`, `spu`, `precision/recall/F1/F2 (micro
|
|
228
|
+
**Non-Binary Metrics:** `cor`, `inc`, `mis`, `spu`, `TN`, `precision/recall/F1/F2 (micro and macro)`, `specificity`
|
|
229
|
+
|
|
230
|
+
Applicability: `cor`, `mis`, `spu` and the `(micro)` precision/recall/F-scores apply to all non-binary fields; `inc`, `TN` and `specificity` are meaningful for **scalar fields only**; the `(macro)` metrics are averages of the per-row metrics and exist for **list fields only**. `accuracy` and `specificity` carry no `(micro)`/`(macro)` tag: they are only ever computed one way (pooled counts), since a per-row version would be a 0/1 indicator whose average equals the pooled value.
|
|
212
231
|
|
|
213
232
|
## ⚡ Performance Metrics Explained
|
|
233
|
+
|
|
234
|
+

|
|
235
|
+
|
|
214
236
|
### Binary Classification Metrics
|
|
215
237
|
|
|
216
238
|
For fields with True/False values (e.g., "Has metastasis"):
|
|
@@ -241,6 +263,7 @@ For scalar and list fields (e.g., "Diagnosis", "Treatment Drugs"):
|
|
|
241
263
|
| **Missing (Mis)** | Items present in label but not extracted | (Same example) → Mis=1 (DrugB missing) |
|
|
242
264
|
| **Spurious (Spu)** | Items extracted but not in label | Label: `["DrugA"]`, Prediction: `["DrugA", "DrugC"]` → Spu=1 |
|
|
243
265
|
| **Incorrect (Inc)** | Wrong values for scalar fields | Label: `"Cancer"`, Prediction: `"Diabetes"` → Inc=1 |
|
|
266
|
+
| **True Negative (TN)** | Scalar fields only: field correctly left empty | Label: `"-"`, Prediction: `""`/`"-"` → TN=1 |
|
|
244
267
|
|
|
245
268
|
#### Structured Extraction Formulas
|
|
246
269
|
|
|
@@ -248,8 +271,9 @@ For scalar and list fields (e.g., "Diagnosis", "Treatment Drugs"):
|
|
|
248
271
|
|--------|---------|---------|
|
|
249
272
|
| **Precision** | `Cor / (Cor + Spu + Inc)` | Of all extracted items, how many were correct? |
|
|
250
273
|
| **Recall** | `Cor / (Cor + Mis + Inc)` | Of all labeled items, how many were correctly extracted? |
|
|
274
|
+
| **Specificity** | `TN / (TN + Spu)` | Scalar fields only: of all cases labeled as having no information, how many were correctly left empty? |
|
|
251
275
|
|
|
252
|
-
**Note:**
|
|
276
|
+
**Note:** Inc and TN (and therefore specificity) are defined only for scalar fields. For list fields, extracted items are always classified as correct, missing, or spurious — Inc stays empty and no TN column is emitted.
|
|
253
277
|
|
|
254
278
|
The following formulas apply to both binary classification and structured extraction metrics:
|
|
255
279
|
|
|
@@ -260,13 +284,51 @@ The following formulas apply to both binary classification and structured extrac
|
|
|
260
284
|
|
|
261
285
|
Where P = Precision and R = Recall (calculated differently for each metric type).
|
|
262
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
|
+
|
|
263
325
|
## Bootstrap Confidence Intervals
|
|
264
326
|
|
|
265
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.
|
|
266
328
|
|
|
267
329
|
### Usage
|
|
268
330
|
```python
|
|
269
|
-
from
|
|
331
|
+
from llmvalidate import bootstrap_CI
|
|
270
332
|
|
|
271
333
|
# After running validation to get results_df
|
|
272
334
|
ci_results = bootstrap_CI(
|
|
@@ -347,7 +409,7 @@ pip install -r requirements.txt
|
|
|
347
409
|
pytest
|
|
348
410
|
|
|
349
411
|
# Run with coverage reporting
|
|
350
|
-
pytest --cov=
|
|
412
|
+
pytest --cov=llmvalidate
|
|
351
413
|
|
|
352
414
|
# Run specific test modules
|
|
353
415
|
pytest tests/validate_test.py # Core validation logic
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|