llmvalidate 0.4.6__tar.gz → 0.6.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.4.6/src/llmvalidate.egg-info → llmvalidate-0.6.0}/PKG-INFO +64 -20
- {llmvalidate-0.4.6 → llmvalidate-0.6.0}/pyproject.toml +1 -1
- {llmvalidate-0.4.6 → llmvalidate-0.6.0}/readme.md +64 -20
- {llmvalidate-0.4.6 → llmvalidate-0.6.0}/src/llmvalidate/structured.py +4 -0
- {llmvalidate-0.4.6 → llmvalidate-0.6.0}/src/llmvalidate/utils.py +23 -9
- {llmvalidate-0.4.6 → llmvalidate-0.6.0}/src/llmvalidate/validation.py +61 -19
- {llmvalidate-0.4.6 → llmvalidate-0.6.0/src/llmvalidate.egg-info}/PKG-INFO +64 -20
- {llmvalidate-0.4.6 → llmvalidate-0.6.0}/LICENSE +0 -0
- {llmvalidate-0.4.6 → llmvalidate-0.6.0}/setup.cfg +0 -0
- {llmvalidate-0.4.6 → llmvalidate-0.6.0}/src/llmvalidate/__init__.py +0 -0
- {llmvalidate-0.4.6 → llmvalidate-0.6.0}/src/llmvalidate.egg-info/SOURCES.txt +0 -0
- {llmvalidate-0.4.6 → llmvalidate-0.6.0}/src/llmvalidate.egg-info/dependency_links.txt +0 -0
- {llmvalidate-0.4.6 → llmvalidate-0.6.0}/src/llmvalidate.egg-info/requires.txt +0 -0
- {llmvalidate-0.4.6 → llmvalidate-0.6.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.6.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,26 @@ 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
|
|
39
45
|
- **Dual usage modes** - Validate pre-computed results OR run live LLM inference with validation
|
|
40
|
-
- **Comprehensive metrics** - Precision, recall, F1/F2, accuracy, specificity with
|
|
46
|
+
- **Comprehensive metrics** - Precision, recall, F1/F2, accuracy, specificity, with micro and macro aggregation where applicable
|
|
41
47
|
- **Confidence analysis** - Automatic performance breakdown by confidence levels
|
|
42
48
|
- **Statistical uncertainty** - Non-parametric bootstrap confidence intervals for all performance metrics
|
|
43
49
|
- **Production ready** - Parallel processing, intelligent caching, detailed progress tracking
|
|
@@ -60,14 +66,14 @@ python runme.py
|
|
|
60
66
|
|
|
61
67
|
Processes the included [samples.csv](samples.csv) (14 test cases covering all validation scenarios) and outputs timestamped results to `validation_results/samples/`:
|
|
62
68
|
|
|
63
|
-
- **[Results CSV](validation_results/samples/2026-
|
|
64
|
-
- **[Metrics CSV](validation_results/samples/2026-
|
|
65
|
-
- **[CI Metrics CSV](validation_results/samples/2026-
|
|
69
|
+
- **[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
|
|
70
|
+
- **[Metrics CSV](validation_results/samples/2026-07-13%2001-12-18%20metrics.csv)** - Aggregated performance statistics with confidence breakdowns
|
|
71
|
+
- **[CI Metrics CSV](validation_results/samples/2026-07-13%2001-12-18%20CI%20metrics.csv)** - Confidence intervals for metrics
|
|
66
72
|
|
|
67
73
|
| Rows | Field Type | Test Scenarios |
|
|
68
74
|
|------|------------|----------------|
|
|
69
75
|
| **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 |
|
|
76
|
+
| **5-9** | Scalar (`Diagnosis`, `Histology`) | Correct, incorrect, missing, spurious, and correct-empty (TN) extractions |
|
|
71
77
|
| **10-14** | List (`Treatment Drugs`, `Test Results`) | Perfect match, spurious items, missing items, correct empty, mixed results |
|
|
72
78
|
|
|
73
79
|
## 📊 Usage Modes
|
|
@@ -77,7 +83,7 @@ When you have LLM predictions in `Res: {Field Name}` columns:
|
|
|
77
83
|
|
|
78
84
|
```python
|
|
79
85
|
import pandas as pd
|
|
80
|
-
from
|
|
86
|
+
from llmvalidate import validate
|
|
81
87
|
|
|
82
88
|
df = pd.read_csv("data.csv", index_col="Patient ID")
|
|
83
89
|
# df must contain: "Field Name" and "Res: Field Name" columns
|
|
@@ -93,8 +99,8 @@ results_df, metrics_df = validate(
|
|
|
93
99
|
### Mode 2: Live LLM Inference + Validation
|
|
94
100
|
|
|
95
101
|
```python
|
|
96
|
-
from
|
|
97
|
-
from
|
|
102
|
+
from llmvalidate.structured import StructuredResult, StructuredGroup, StructuredField
|
|
103
|
+
from llmvalidate.utils import flatten_structured_result
|
|
98
104
|
|
|
99
105
|
def llm_callback(row, i, raw_text_column_name):
|
|
100
106
|
raw_text = row[raw_text_column_name]
|
|
@@ -135,12 +141,43 @@ results_df, metrics_df = validate(
|
|
|
135
141
|
| **Binary** | True/False detection | `True`, `False` | `True`, `False` |
|
|
136
142
|
| **Scalar** | Single text/numeric value | `"Lung Cancer"` <br> `42` | `"Breast Cancer"` <br> `38` |
|
|
137
143
|
| **List** | Multiple values | `["Drug A", "Drug B"]` <br> `"['Item1', 'Item2']"` | `["Drug A"]` <br> `[]` |
|
|
144
|
+
| **Coded** | A value **and** its code (ICD-10 / ICD-O-3, RxNorm) — scored as two facets | `X-value`: "Adenocarcinoma" <br> `X-code`: "8140/3" | via `StructuredField(..., code=...)` |
|
|
145
|
+
|
|
146
|
+
### Coded Fields (value + code)
|
|
147
|
+
|
|
148
|
+
A `StructuredField` may carry an optional **`code`** alongside its `value` — for coded
|
|
149
|
+
concepts such as ICD-10 / ICD-O-3 topography-morphology or RxNorm drug codes:
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
StructuredField(name="Primary Histology", value="Adenocarcinoma", code="8140/3",
|
|
153
|
+
confidence="High")
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
When `code` is set, the field flattens to **two scored facets** — `Primary Histology-value`
|
|
157
|
+
and `Primary Histology-code` — each compared against the label column of the same name.
|
|
158
|
+
`confidence` / `justification` stay attached to the logical field (a single
|
|
159
|
+
`Res: Primary Histology confidence` column), and its confidence breakdown is applied to
|
|
160
|
+
**both** facets. `value` and `code` may be lists (e.g. drug names + their RxNorm codes),
|
|
161
|
+
scored set-wise per facet.
|
|
162
|
+
|
|
163
|
+
When `code` is `None` (the default) the field flattens to a single `<name>` column as
|
|
164
|
+
before — fully backward-compatible. A coded field whose code is genuinely unknown should
|
|
165
|
+
still pass `code="-"` (the no-information sentinel), **not** `None`, so it keeps aligning
|
|
166
|
+
with the `-value` / `-code` label columns.
|
|
138
167
|
|
|
139
168
|
### Special Value Handling
|
|
140
169
|
- **`"-"`** = Labeled as "No information is available in the source document"
|
|
141
170
|
- **`null/empty/NaN`** = Field not labeled/evaluated (supports partial labeling where different cases may have labels for different field subsets)
|
|
142
171
|
- **Lists** - Can be Python lists `["a", "b"]` or stringified `"['a', 'b']"` (auto-converted)
|
|
143
172
|
|
|
173
|
+
The `"-"`-vs-empty distinction above applies to **label** columns only. In **prediction** (`Res:`)
|
|
174
|
+
columns there is no "not evaluated" state: `"-"`, `""`, `null`/`NaN`, whitespace-only strings and
|
|
175
|
+
`[]` are all treated identically as "nothing extracted" (scoring Mis against a labeled value, or
|
|
176
|
+
TN when the label is `"-"`). We still recommend emitting `"-"` uniformly, to keep predictions
|
|
177
|
+
symmetric with labels. **Exception — binary fields:** predictions must be an explicit
|
|
178
|
+
`True`/`False`; an empty prediction is "not True / not False", so it scores FN against a `True`
|
|
179
|
+
label and **FP** against a `False` label.
|
|
180
|
+
|
|
144
181
|
### Partial Labeling Support
|
|
145
182
|
The framework supports partial labeling scenarios where:
|
|
146
183
|
- Not every case needs labels for every field
|
|
@@ -151,21 +188,21 @@ The framework supports partial labeling scenarios where:
|
|
|
151
188
|
|
|
152
189
|
## 📈 Output Files
|
|
153
190
|
|
|
154
|
-
|
|
191
|
+
A `validate()` run generates two timestamped CSV files (a third, CI metrics, is added when you also run `bootstrap_CI` — see the demo above):
|
|
155
192
|
|
|
156
193
|
### 1. Results CSV (`YYYY-MM-DD HH-MM-SS results.csv`)
|
|
157
194
|
**Row-level analysis** with detailed per-case metrics:
|
|
158
195
|
|
|
159
196
|
**Original Data:**
|
|
160
197
|
- All input columns (labels, raw text, etc.)
|
|
161
|
-
- `Res: {Field}` columns with LLM predictions
|
|
162
|
-
- `Res: {Field} confidence` and `Res: {Field} justification` (if available)
|
|
198
|
+
- `Res: {Field}` columns with LLM predictions (coded fields split into `Res: {Field}-value` and `Res: {Field}-code`)
|
|
199
|
+
- `Res: {Field} confidence` and `Res: {Field} justification` (if available; kept per logical field, and shared across a coded field's two facets)
|
|
163
200
|
|
|
164
201
|
**Binary Fields:**
|
|
165
202
|
- `TP/FP/FN/TN: {Field}` - Confusion matrix counts (1 or 0 per row)
|
|
166
203
|
|
|
167
204
|
**Non-Binary Fields:**
|
|
168
|
-
- `Cor/
|
|
205
|
+
- `Cor/Mis/Spu: {Field}` - Item counts per row (Inc and TN are None for list fields)
|
|
169
206
|
- `Cor/Inc/Mis/Spu: {Field} items` - Actual item lists
|
|
170
207
|
- `Precision/Recall/F1/F2: {Field}` - Per-row metrics (list fields only)
|
|
171
208
|
|
|
@@ -185,9 +222,14 @@ The framework generates two timestamped CSV files for each validation run:
|
|
|
185
222
|
|
|
186
223
|
**Binary Metrics:** `TP`, `TN`, `FP`, `FN`, `precision`, `recall`, `F1/F2`, `accuracy`, `specificity`
|
|
187
224
|
|
|
188
|
-
**Non-Binary Metrics:** `cor`, `inc`, `mis`, `spu`, `precision/recall/F1/F2 (micro
|
|
225
|
+
**Non-Binary Metrics:** `cor`, `inc`, `mis`, `spu`, `TN`, `precision/recall/F1/F2 (micro and macro)`, `specificity`
|
|
226
|
+
|
|
227
|
+
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.
|
|
189
228
|
|
|
190
229
|
## ⚡ Performance Metrics Explained
|
|
230
|
+
|
|
231
|
+

|
|
232
|
+
|
|
191
233
|
### Binary Classification Metrics
|
|
192
234
|
|
|
193
235
|
For fields with True/False values (e.g., "Has metastasis"):
|
|
@@ -218,6 +260,7 @@ For scalar and list fields (e.g., "Diagnosis", "Treatment Drugs"):
|
|
|
218
260
|
| **Missing (Mis)** | Items present in label but not extracted | (Same example) → Mis=1 (DrugB missing) |
|
|
219
261
|
| **Spurious (Spu)** | Items extracted but not in label | Label: `["DrugA"]`, Prediction: `["DrugA", "DrugC"]` → Spu=1 |
|
|
220
262
|
| **Incorrect (Inc)** | Wrong values for scalar fields | Label: `"Cancer"`, Prediction: `"Diabetes"` → Inc=1 |
|
|
263
|
+
| **True Negative (TN)** | Scalar fields only: field correctly left empty | Label: `"-"`, Prediction: `""`/`"-"` → TN=1 |
|
|
221
264
|
|
|
222
265
|
#### Structured Extraction Formulas
|
|
223
266
|
|
|
@@ -225,8 +268,9 @@ For scalar and list fields (e.g., "Diagnosis", "Treatment Drugs"):
|
|
|
225
268
|
|--------|---------|---------|
|
|
226
269
|
| **Precision** | `Cor / (Cor + Spu + Inc)` | Of all extracted items, how many were correct? |
|
|
227
270
|
| **Recall** | `Cor / (Cor + Mis + Inc)` | Of all labeled items, how many were correctly extracted? |
|
|
271
|
+
| **Specificity** | `TN / (TN + Spu)` | Scalar fields only: of all cases labeled as having no information, how many were correctly left empty? |
|
|
228
272
|
|
|
229
|
-
**Note:**
|
|
273
|
+
**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.
|
|
230
274
|
|
|
231
275
|
The following formulas apply to both binary classification and structured extraction metrics:
|
|
232
276
|
|
|
@@ -243,7 +287,7 @@ The framework includes statistical confidence interval estimation using non-para
|
|
|
243
287
|
|
|
244
288
|
### Usage
|
|
245
289
|
```python
|
|
246
|
-
from
|
|
290
|
+
from llmvalidate import bootstrap_CI
|
|
247
291
|
|
|
248
292
|
# After running validation to get results_df
|
|
249
293
|
ci_results = bootstrap_CI(
|
|
@@ -324,7 +368,7 @@ pip install -r requirements.txt
|
|
|
324
368
|
pytest
|
|
325
369
|
|
|
326
370
|
# Run with coverage reporting
|
|
327
|
-
pytest --cov=
|
|
371
|
+
pytest --cov=llmvalidate
|
|
328
372
|
|
|
329
373
|
# Run specific test modules
|
|
330
374
|
pytest tests/validate_test.py # Core validation logic
|
|
@@ -1,19 +1,25 @@
|
|
|
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
|
|
15
21
|
- **Dual usage modes** - Validate pre-computed results OR run live LLM inference with validation
|
|
16
|
-
- **Comprehensive metrics** - Precision, recall, F1/F2, accuracy, specificity with
|
|
22
|
+
- **Comprehensive metrics** - Precision, recall, F1/F2, accuracy, specificity, with micro and macro aggregation where applicable
|
|
17
23
|
- **Confidence analysis** - Automatic performance breakdown by confidence levels
|
|
18
24
|
- **Statistical uncertainty** - Non-parametric bootstrap confidence intervals for all performance metrics
|
|
19
25
|
- **Production ready** - Parallel processing, intelligent caching, detailed progress tracking
|
|
@@ -36,14 +42,14 @@ python runme.py
|
|
|
36
42
|
|
|
37
43
|
Processes the included [samples.csv](samples.csv) (14 test cases covering all validation scenarios) and outputs timestamped results to `validation_results/samples/`:
|
|
38
44
|
|
|
39
|
-
- **[Results CSV](validation_results/samples/2026-
|
|
40
|
-
- **[Metrics CSV](validation_results/samples/2026-
|
|
41
|
-
- **[CI Metrics CSV](validation_results/samples/2026-
|
|
45
|
+
- **[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
|
|
46
|
+
- **[Metrics CSV](validation_results/samples/2026-07-13%2001-12-18%20metrics.csv)** - Aggregated performance statistics with confidence breakdowns
|
|
47
|
+
- **[CI Metrics CSV](validation_results/samples/2026-07-13%2001-12-18%20CI%20metrics.csv)** - Confidence intervals for metrics
|
|
42
48
|
|
|
43
49
|
| Rows | Field Type | Test Scenarios |
|
|
44
50
|
|------|------------|----------------|
|
|
45
51
|
| **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 |
|
|
52
|
+
| **5-9** | Scalar (`Diagnosis`, `Histology`) | Correct, incorrect, missing, spurious, and correct-empty (TN) extractions |
|
|
47
53
|
| **10-14** | List (`Treatment Drugs`, `Test Results`) | Perfect match, spurious items, missing items, correct empty, mixed results |
|
|
48
54
|
|
|
49
55
|
## 📊 Usage Modes
|
|
@@ -53,7 +59,7 @@ When you have LLM predictions in `Res: {Field Name}` columns:
|
|
|
53
59
|
|
|
54
60
|
```python
|
|
55
61
|
import pandas as pd
|
|
56
|
-
from
|
|
62
|
+
from llmvalidate import validate
|
|
57
63
|
|
|
58
64
|
df = pd.read_csv("data.csv", index_col="Patient ID")
|
|
59
65
|
# df must contain: "Field Name" and "Res: Field Name" columns
|
|
@@ -69,8 +75,8 @@ results_df, metrics_df = validate(
|
|
|
69
75
|
### Mode 2: Live LLM Inference + Validation
|
|
70
76
|
|
|
71
77
|
```python
|
|
72
|
-
from
|
|
73
|
-
from
|
|
78
|
+
from llmvalidate.structured import StructuredResult, StructuredGroup, StructuredField
|
|
79
|
+
from llmvalidate.utils import flatten_structured_result
|
|
74
80
|
|
|
75
81
|
def llm_callback(row, i, raw_text_column_name):
|
|
76
82
|
raw_text = row[raw_text_column_name]
|
|
@@ -111,12 +117,43 @@ results_df, metrics_df = validate(
|
|
|
111
117
|
| **Binary** | True/False detection | `True`, `False` | `True`, `False` |
|
|
112
118
|
| **Scalar** | Single text/numeric value | `"Lung Cancer"` <br> `42` | `"Breast Cancer"` <br> `38` |
|
|
113
119
|
| **List** | Multiple values | `["Drug A", "Drug B"]` <br> `"['Item1', 'Item2']"` | `["Drug A"]` <br> `[]` |
|
|
120
|
+
| **Coded** | A value **and** its code (ICD-10 / ICD-O-3, RxNorm) — scored as two facets | `X-value`: "Adenocarcinoma" <br> `X-code`: "8140/3" | via `StructuredField(..., code=...)` |
|
|
121
|
+
|
|
122
|
+
### Coded Fields (value + code)
|
|
123
|
+
|
|
124
|
+
A `StructuredField` may carry an optional **`code`** alongside its `value` — for coded
|
|
125
|
+
concepts such as ICD-10 / ICD-O-3 topography-morphology or RxNorm drug codes:
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
StructuredField(name="Primary Histology", value="Adenocarcinoma", code="8140/3",
|
|
129
|
+
confidence="High")
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
When `code` is set, the field flattens to **two scored facets** — `Primary Histology-value`
|
|
133
|
+
and `Primary Histology-code` — each compared against the label column of the same name.
|
|
134
|
+
`confidence` / `justification` stay attached to the logical field (a single
|
|
135
|
+
`Res: Primary Histology confidence` column), and its confidence breakdown is applied to
|
|
136
|
+
**both** facets. `value` and `code` may be lists (e.g. drug names + their RxNorm codes),
|
|
137
|
+
scored set-wise per facet.
|
|
138
|
+
|
|
139
|
+
When `code` is `None` (the default) the field flattens to a single `<name>` column as
|
|
140
|
+
before — fully backward-compatible. A coded field whose code is genuinely unknown should
|
|
141
|
+
still pass `code="-"` (the no-information sentinel), **not** `None`, so it keeps aligning
|
|
142
|
+
with the `-value` / `-code` label columns.
|
|
114
143
|
|
|
115
144
|
### Special Value Handling
|
|
116
145
|
- **`"-"`** = Labeled as "No information is available in the source document"
|
|
117
146
|
- **`null/empty/NaN`** = Field not labeled/evaluated (supports partial labeling where different cases may have labels for different field subsets)
|
|
118
147
|
- **Lists** - Can be Python lists `["a", "b"]` or stringified `"['a', 'b']"` (auto-converted)
|
|
119
148
|
|
|
149
|
+
The `"-"`-vs-empty distinction above applies to **label** columns only. In **prediction** (`Res:`)
|
|
150
|
+
columns there is no "not evaluated" state: `"-"`, `""`, `null`/`NaN`, whitespace-only strings and
|
|
151
|
+
`[]` are all treated identically as "nothing extracted" (scoring Mis against a labeled value, or
|
|
152
|
+
TN when the label is `"-"`). We still recommend emitting `"-"` uniformly, to keep predictions
|
|
153
|
+
symmetric with labels. **Exception — binary fields:** predictions must be an explicit
|
|
154
|
+
`True`/`False`; an empty prediction is "not True / not False", so it scores FN against a `True`
|
|
155
|
+
label and **FP** against a `False` label.
|
|
156
|
+
|
|
120
157
|
### Partial Labeling Support
|
|
121
158
|
The framework supports partial labeling scenarios where:
|
|
122
159
|
- Not every case needs labels for every field
|
|
@@ -127,21 +164,21 @@ The framework supports partial labeling scenarios where:
|
|
|
127
164
|
|
|
128
165
|
## 📈 Output Files
|
|
129
166
|
|
|
130
|
-
|
|
167
|
+
A `validate()` run generates two timestamped CSV files (a third, CI metrics, is added when you also run `bootstrap_CI` — see the demo above):
|
|
131
168
|
|
|
132
169
|
### 1. Results CSV (`YYYY-MM-DD HH-MM-SS results.csv`)
|
|
133
170
|
**Row-level analysis** with detailed per-case metrics:
|
|
134
171
|
|
|
135
172
|
**Original Data:**
|
|
136
173
|
- All input columns (labels, raw text, etc.)
|
|
137
|
-
- `Res: {Field}` columns with LLM predictions
|
|
138
|
-
- `Res: {Field} confidence` and `Res: {Field} justification` (if available)
|
|
174
|
+
- `Res: {Field}` columns with LLM predictions (coded fields split into `Res: {Field}-value` and `Res: {Field}-code`)
|
|
175
|
+
- `Res: {Field} confidence` and `Res: {Field} justification` (if available; kept per logical field, and shared across a coded field's two facets)
|
|
139
176
|
|
|
140
177
|
**Binary Fields:**
|
|
141
178
|
- `TP/FP/FN/TN: {Field}` - Confusion matrix counts (1 or 0 per row)
|
|
142
179
|
|
|
143
180
|
**Non-Binary Fields:**
|
|
144
|
-
- `Cor/
|
|
181
|
+
- `Cor/Mis/Spu: {Field}` - Item counts per row (Inc and TN are None for list fields)
|
|
145
182
|
- `Cor/Inc/Mis/Spu: {Field} items` - Actual item lists
|
|
146
183
|
- `Precision/Recall/F1/F2: {Field}` - Per-row metrics (list fields only)
|
|
147
184
|
|
|
@@ -161,9 +198,14 @@ The framework generates two timestamped CSV files for each validation run:
|
|
|
161
198
|
|
|
162
199
|
**Binary Metrics:** `TP`, `TN`, `FP`, `FN`, `precision`, `recall`, `F1/F2`, `accuracy`, `specificity`
|
|
163
200
|
|
|
164
|
-
**Non-Binary Metrics:** `cor`, `inc`, `mis`, `spu`, `precision/recall/F1/F2 (micro
|
|
201
|
+
**Non-Binary Metrics:** `cor`, `inc`, `mis`, `spu`, `TN`, `precision/recall/F1/F2 (micro and macro)`, `specificity`
|
|
202
|
+
|
|
203
|
+
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.
|
|
165
204
|
|
|
166
205
|
## ⚡ Performance Metrics Explained
|
|
206
|
+
|
|
207
|
+

|
|
208
|
+
|
|
167
209
|
### Binary Classification Metrics
|
|
168
210
|
|
|
169
211
|
For fields with True/False values (e.g., "Has metastasis"):
|
|
@@ -194,6 +236,7 @@ For scalar and list fields (e.g., "Diagnosis", "Treatment Drugs"):
|
|
|
194
236
|
| **Missing (Mis)** | Items present in label but not extracted | (Same example) → Mis=1 (DrugB missing) |
|
|
195
237
|
| **Spurious (Spu)** | Items extracted but not in label | Label: `["DrugA"]`, Prediction: `["DrugA", "DrugC"]` → Spu=1 |
|
|
196
238
|
| **Incorrect (Inc)** | Wrong values for scalar fields | Label: `"Cancer"`, Prediction: `"Diabetes"` → Inc=1 |
|
|
239
|
+
| **True Negative (TN)** | Scalar fields only: field correctly left empty | Label: `"-"`, Prediction: `""`/`"-"` → TN=1 |
|
|
197
240
|
|
|
198
241
|
#### Structured Extraction Formulas
|
|
199
242
|
|
|
@@ -201,8 +244,9 @@ For scalar and list fields (e.g., "Diagnosis", "Treatment Drugs"):
|
|
|
201
244
|
|--------|---------|---------|
|
|
202
245
|
| **Precision** | `Cor / (Cor + Spu + Inc)` | Of all extracted items, how many were correct? |
|
|
203
246
|
| **Recall** | `Cor / (Cor + Mis + Inc)` | Of all labeled items, how many were correctly extracted? |
|
|
247
|
+
| **Specificity** | `TN / (TN + Spu)` | Scalar fields only: of all cases labeled as having no information, how many were correctly left empty? |
|
|
204
248
|
|
|
205
|
-
**Note:**
|
|
249
|
+
**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.
|
|
206
250
|
|
|
207
251
|
The following formulas apply to both binary classification and structured extraction metrics:
|
|
208
252
|
|
|
@@ -219,7 +263,7 @@ The framework includes statistical confidence interval estimation using non-para
|
|
|
219
263
|
|
|
220
264
|
### Usage
|
|
221
265
|
```python
|
|
222
|
-
from
|
|
266
|
+
from llmvalidate import bootstrap_CI
|
|
223
267
|
|
|
224
268
|
# After running validation to get results_df
|
|
225
269
|
ci_results = bootstrap_CI(
|
|
@@ -300,7 +344,7 @@ pip install -r requirements.txt
|
|
|
300
344
|
pytest
|
|
301
345
|
|
|
302
346
|
# Run with coverage reporting
|
|
303
|
-
pytest --cov=
|
|
347
|
+
pytest --cov=llmvalidate
|
|
304
348
|
|
|
305
349
|
# Run specific test modules
|
|
306
350
|
pytest tests/validate_test.py # Core validation logic
|
|
@@ -336,4 +380,4 @@ llm-validation-framework/
|
|
|
336
380
|
|
|
337
381
|
## 📄 License
|
|
338
382
|
|
|
339
|
-
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
383
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
@@ -9,6 +9,10 @@ from typing import Any, List, Dict, Optional, Union
|
|
|
9
9
|
class StructuredField(BaseModel):
|
|
10
10
|
name: str
|
|
11
11
|
value: Any
|
|
12
|
+
# Optional coded value for a dictionary-backed concept (ICD-10 / ICD-O-3 / RxNorm).
|
|
13
|
+
# When set, the field flattens to two scored facets `<name>-value` and `<name>-code`
|
|
14
|
+
# (see flatten_structured_result); when None, the field flattens to a single `<name>`.
|
|
15
|
+
code: Optional[Any] = None
|
|
12
16
|
justification: Optional[str] = None
|
|
13
17
|
confidence: Optional[str] = None
|
|
14
18
|
|
|
@@ -35,9 +35,15 @@ def flatten_structured_result(structured_result: StructuredResult, remove_quotes
|
|
|
35
35
|
Flatten a StructuredResult into a flat dictionary ignoring groups.
|
|
36
36
|
|
|
37
37
|
Output format (for each field with name N):
|
|
38
|
-
N: <value>
|
|
39
|
-
N
|
|
40
|
-
N
|
|
38
|
+
N: <value> (when `code` is None)
|
|
39
|
+
N-value: <value>, N-code: <code> (when `code` is set — a coded concept)
|
|
40
|
+
N confidence: <confidence> (only if provided; stays keyed by N, not per-facet)
|
|
41
|
+
N justification: <justification> (only if provided; stays keyed by N)
|
|
42
|
+
|
|
43
|
+
A field carrying a `code` (e.g. an ICD-10 / ICD-O-3 / RxNorm concept) flattens to
|
|
44
|
+
two scored facets, `N-value` and `N-code`, each compared against the label column of
|
|
45
|
+
the same name. `confidence` / `justification` remain keyed by the logical field N (a
|
|
46
|
+
single column), and `get_metrics` bins both facets by that one confidence column.
|
|
41
47
|
|
|
42
48
|
Later duplicates overwrite earlier ones (last one wins).
|
|
43
49
|
|
|
@@ -45,6 +51,11 @@ def flatten_structured_result(structured_result: StructuredResult, remove_quotes
|
|
|
45
51
|
remove_quotes (bool): If True, remove double quotes inside stringified lists
|
|
46
52
|
(e.g., '["A", "B"]' -> '[A, B]').
|
|
47
53
|
"""
|
|
54
|
+
def _dequote(v):
|
|
55
|
+
if remove_quotes and isinstance(v, str) and re.match(r'^\[.*\]$', v.strip()):
|
|
56
|
+
return re.sub(r'"\s*([^"]*?)\s*"', r'\1', v)
|
|
57
|
+
return v
|
|
58
|
+
|
|
48
59
|
flat: Dict[str, Any] = {}
|
|
49
60
|
if not structured_result or not structured_result.groups:
|
|
50
61
|
return flat
|
|
@@ -59,14 +70,17 @@ def flatten_structured_result(structured_result: StructuredResult, remove_quotes
|
|
|
59
70
|
if not base_name:
|
|
60
71
|
continue
|
|
61
72
|
|
|
62
|
-
|
|
63
|
-
value = field.value
|
|
64
|
-
|
|
65
|
-
if remove_quotes and isinstance(value, str) and re.match(r'^\[.*\]$', value.strip()):
|
|
66
|
-
value = re.sub(r'"\s*([^"]*?)\s*"', r'\1', value)
|
|
73
|
+
value = _dequote(field.value)
|
|
67
74
|
|
|
68
|
-
|
|
75
|
+
if field.code is not None:
|
|
76
|
+
# Coded concept -> two scored facets; label columns are named the same.
|
|
77
|
+
flat[f"{base_name}-value"] = value
|
|
78
|
+
flat[f"{base_name}-code"] = _dequote(field.code)
|
|
79
|
+
else:
|
|
80
|
+
flat[base_name] = value
|
|
69
81
|
|
|
82
|
+
# confidence / justification stay keyed by the logical field N (single column,
|
|
83
|
+
# applied to both facets by get_metrics), not duplicated per facet.
|
|
70
84
|
if field.confidence is not None:
|
|
71
85
|
flat[f"{base_name} confidence"] = field.confidence
|
|
72
86
|
if field.justification is not None:
|
|
@@ -75,10 +75,11 @@ def compare_results_all(df, fields, parents={}, comparison_callback=None, raw_te
|
|
|
75
75
|
|
|
76
76
|
Returns pandas data frame same as df but with added columns:
|
|
77
77
|
'Cor: ' for Correct
|
|
78
|
-
'Inc: ' for Incorrect
|
|
78
|
+
'Inc: ' for Incorrect (scalar fields; for list fields only when 'parents' is provided)
|
|
79
79
|
'Mis: ' for Missing
|
|
80
80
|
'Spu: ' for Spurious
|
|
81
|
-
'Par: ' for Partial
|
|
81
|
+
'Par: ' for Partial (only when 'parents' is provided)
|
|
82
|
+
'TN: ' for True Negative (scalar fields only; not defined for list fields)
|
|
82
83
|
"""
|
|
83
84
|
|
|
84
85
|
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)
|
|
@@ -88,6 +89,16 @@ def compare_results_all(df, fields, parents={}, comparison_callback=None, raw_te
|
|
|
88
89
|
for field in fields:
|
|
89
90
|
binary_fields[field] = pd.api.types.is_bool_dtype(pd.api.types.infer_dtype(df[field].dropna()))
|
|
90
91
|
|
|
92
|
+
# Determine which fields are list fields (any label or result value is a list).
|
|
93
|
+
# TN is only defined for scalar fields, so list fields never get a 'TN: ' column.
|
|
94
|
+
list_fields = {}
|
|
95
|
+
for field in fields:
|
|
96
|
+
is_list = df[field].map(type).eq(list).any()
|
|
97
|
+
res_col = 'Res: ' + field
|
|
98
|
+
if not is_list and res_col in df.columns:
|
|
99
|
+
is_list = df[res_col].map(type).eq(list).any()
|
|
100
|
+
list_fields[field] = is_list
|
|
101
|
+
|
|
91
102
|
# Create a list to store modified rows
|
|
92
103
|
modified_rows = []
|
|
93
104
|
# Iterate over the rows of the DataFrame
|
|
@@ -134,6 +145,23 @@ def compare_results_all(df, fields, parents={}, comparison_callback=None, raw_te
|
|
|
134
145
|
del res['Partial'] #partial appear only if parent match
|
|
135
146
|
del res_items['Partial']
|
|
136
147
|
|
|
148
|
+
if not list_fields[field]:
|
|
149
|
+
# Scalar field: report per-case TN so true negatives (field correctly
|
|
150
|
+
# left empty) are visible row by row. TN = 1 if the case was labeled
|
|
151
|
+
# as "No information" (label '-') AND the prediction is empty.
|
|
152
|
+
# None (undefined) when the case was not labeled for this field.
|
|
153
|
+
# TN is not defined for list fields (see get_metrics).
|
|
154
|
+
if res['Correct'] is None:
|
|
155
|
+
row['TN: ' + field] = None
|
|
156
|
+
#row['TN: ' + field + ' items'] = None
|
|
157
|
+
else:
|
|
158
|
+
TN_case = 1 if (is_scalar_empty(normalize(expected))
|
|
159
|
+
and is_scalar_empty(normalize(actual))) else 0
|
|
160
|
+
row['TN: ' + field] = TN_case
|
|
161
|
+
# a TN case has no extracted item: the matched "item" is the
|
|
162
|
+
# no-information marker itself therefore pointless to add
|
|
163
|
+
# row['TN: ' + field + ' items'] = ['-'] if TN_case else []
|
|
164
|
+
|
|
137
165
|
# Iterate over the key-value pairs in the result dictionary
|
|
138
166
|
for key, value in res.items():
|
|
139
167
|
# Create a new column in the DataFrame using the key
|
|
@@ -221,6 +249,26 @@ def calculate_metrics(cor, par, inc, spu, mis, TN):
|
|
|
221
249
|
|
|
222
250
|
return precision, recall, f1_score, f2_score, specificity
|
|
223
251
|
|
|
252
|
+
def _confidence_column(field, columns):
|
|
253
|
+
"""The `Res: ... confidence` column used to bin `field`, or None.
|
|
254
|
+
|
|
255
|
+
Prefer the field's own `Res: <field> confidence`. If absent and `<field>` is a coded
|
|
256
|
+
facet (`<base>-value` / `<base>-code`), fall back to the parent `Res: <base> confidence`
|
|
257
|
+
so both facets of a coded concept share the single confidence column emitted by
|
|
258
|
+
flatten_structured_result. Non-facet fields are unaffected (they only use the direct
|
|
259
|
+
column), so this is backward-compatible.
|
|
260
|
+
"""
|
|
261
|
+
direct = f'Res: {field} confidence'
|
|
262
|
+
if direct in columns:
|
|
263
|
+
return direct
|
|
264
|
+
for suffix in ("-value", "-code"):
|
|
265
|
+
if field.endswith(suffix):
|
|
266
|
+
parent = f'Res: {field[:-len(suffix)]} confidence'
|
|
267
|
+
if parent in columns:
|
|
268
|
+
return parent
|
|
269
|
+
return None
|
|
270
|
+
|
|
271
|
+
|
|
224
272
|
def get_metrics(res_df, fields):
|
|
225
273
|
""" For results dataframe generated by validate
|
|
226
274
|
produces dataframe with metrics for all available confidence levels and overall
|
|
@@ -244,7 +292,7 @@ def get_metrics(res_df, fields):
|
|
|
244
292
|
'labeled cases': labeled_cases,
|
|
245
293
|
'field-present cases': exceptions_no,
|
|
246
294
|
'TP': None, 'TN': None, 'FP': None, 'FN': None,
|
|
247
|
-
'precision (micro)': None, 'recall (micro)': None, 'F1 score (micro)': None, 'F2 score (micro)': None, 'accuracy
|
|
295
|
+
'precision (micro)': None, 'recall (micro)': None, 'F1 score (micro)': None, 'F2 score (micro)': None, 'accuracy': None, 'specificity': None,
|
|
248
296
|
'cor': None, 'inc': None, 'mis': None, 'spu': None, 'par': None,
|
|
249
297
|
'precision (macro)': None, 'recall (macro)': None, 'F1 score (macro)': None, 'F2 score (macro)': None
|
|
250
298
|
})
|
|
@@ -252,17 +300,17 @@ def get_metrics(res_df, fields):
|
|
|
252
300
|
# Find all unique confidence levels across all fields
|
|
253
301
|
all_confidence_levels = set()
|
|
254
302
|
for field in fields:
|
|
255
|
-
confidence_col =
|
|
256
|
-
if confidence_col
|
|
303
|
+
confidence_col = _confidence_column(field, clean_df.columns)
|
|
304
|
+
if confidence_col:
|
|
257
305
|
confidence_values = clean_df[confidence_col].dropna().unique()
|
|
258
306
|
all_confidence_levels.update(confidence_values)
|
|
259
|
-
|
|
307
|
+
|
|
260
308
|
# Convert to sorted list for consistent ordering
|
|
261
309
|
confidence_levels = ['Overall'] + sorted(list(all_confidence_levels))
|
|
262
310
|
|
|
263
311
|
for field in fields:
|
|
264
|
-
confidence_field_name =
|
|
265
|
-
has_confidence = confidence_field_name
|
|
312
|
+
confidence_field_name = _confidence_column(field, clean_df.columns)
|
|
313
|
+
has_confidence = confidence_field_name is not None
|
|
266
314
|
|
|
267
315
|
for confidence_level in confidence_levels:
|
|
268
316
|
# Filter data based on confidence level
|
|
@@ -310,6 +358,7 @@ def get_metrics(res_df, fields):
|
|
|
310
358
|
mis = field_df['Mis: ' + field].sum()
|
|
311
359
|
spu = field_df['Spu: ' + field].sum()
|
|
312
360
|
par = field_df['Par: ' + field].sum() if 'Par: ' + field in field_df else None
|
|
361
|
+
TN = field_df['TN: ' + field].sum() if 'TN: ' + field in field_df else None
|
|
313
362
|
|
|
314
363
|
if 'Precision: ' + field in field_df:
|
|
315
364
|
# if Precision present it means that it is a list field
|
|
@@ -317,15 +366,8 @@ def get_metrics(res_df, fields):
|
|
|
317
366
|
recall_macro = field_df['Recall: ' + field].mean()
|
|
318
367
|
f1_score_macro = field_df['F1 score: ' + field].mean()
|
|
319
368
|
f2_score_macro = field_df['F2 score: ' + field].mean()
|
|
320
|
-
|
|
321
|
-
# TN is not defined for list values (e.g. label ['apple'] and prediction ['orange', 'banana'] will produce SPU=2)
|
|
322
|
-
TN_field = None
|
|
323
|
-
else:
|
|
324
|
-
# scalar field
|
|
325
|
-
TN_field = labeled_cases - field_present_cases - spu
|
|
326
|
-
|
|
327
369
|
precision_micro, recall_micro, f1_score_micro, f2_score_micro, specificity_micro = calculate_metrics(
|
|
328
|
-
cor, par or 0, inc or 0, spu, mis,
|
|
370
|
+
cor, par or 0, inc or 0, spu, mis, TN
|
|
329
371
|
)
|
|
330
372
|
|
|
331
373
|
# Append computed row as a dictionary
|
|
@@ -342,8 +384,8 @@ def get_metrics(res_df, fields):
|
|
|
342
384
|
'recall (micro)': recall_micro,
|
|
343
385
|
'F1 score (micro)': f1_score_micro,
|
|
344
386
|
'F2 score (micro)': f2_score_micro,
|
|
345
|
-
'accuracy
|
|
346
|
-
'specificity
|
|
387
|
+
'accuracy': accuracy_micro,
|
|
388
|
+
'specificity': specificity_micro,
|
|
347
389
|
'cor': cor,
|
|
348
390
|
'inc': inc,
|
|
349
391
|
'mis': mis,
|
|
@@ -593,7 +635,7 @@ def _reorder_result_columns(df: pd.DataFrame) -> pd.DataFrame:
|
|
|
593
635
|
res_cols_all = [c for c in cols if c.startswith('Res: ')]
|
|
594
636
|
|
|
595
637
|
metric_prefixes_binary_counts = ["TP: ", "FP: ", "FN: ", "TN: "]
|
|
596
|
-
metric_prefixes_non_binary_counts = ["Cor: ", "Inc: ", "Mis: ", "Spu: ", "Par: "]
|
|
638
|
+
metric_prefixes_non_binary_counts = ["Cor: ", "Inc: ", "Mis: ", "Spu: ", "Par: ", "TN: "]
|
|
597
639
|
metric_prefixes = ["Precision: ", "Recall: ", "Accuracy: ", "F1 score: ", "F2 score: ", "Specificity: "]
|
|
598
640
|
|
|
599
641
|
metric_prefixes_all = metric_prefixes_binary_counts + metric_prefixes_non_binary_counts + metric_prefixes
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: llmvalidate
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.6.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,26 @@ 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
|
|
39
45
|
- **Dual usage modes** - Validate pre-computed results OR run live LLM inference with validation
|
|
40
|
-
- **Comprehensive metrics** - Precision, recall, F1/F2, accuracy, specificity with
|
|
46
|
+
- **Comprehensive metrics** - Precision, recall, F1/F2, accuracy, specificity, with micro and macro aggregation where applicable
|
|
41
47
|
- **Confidence analysis** - Automatic performance breakdown by confidence levels
|
|
42
48
|
- **Statistical uncertainty** - Non-parametric bootstrap confidence intervals for all performance metrics
|
|
43
49
|
- **Production ready** - Parallel processing, intelligent caching, detailed progress tracking
|
|
@@ -60,14 +66,14 @@ python runme.py
|
|
|
60
66
|
|
|
61
67
|
Processes the included [samples.csv](samples.csv) (14 test cases covering all validation scenarios) and outputs timestamped results to `validation_results/samples/`:
|
|
62
68
|
|
|
63
|
-
- **[Results CSV](validation_results/samples/2026-
|
|
64
|
-
- **[Metrics CSV](validation_results/samples/2026-
|
|
65
|
-
- **[CI Metrics CSV](validation_results/samples/2026-
|
|
69
|
+
- **[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
|
|
70
|
+
- **[Metrics CSV](validation_results/samples/2026-07-13%2001-12-18%20metrics.csv)** - Aggregated performance statistics with confidence breakdowns
|
|
71
|
+
- **[CI Metrics CSV](validation_results/samples/2026-07-13%2001-12-18%20CI%20metrics.csv)** - Confidence intervals for metrics
|
|
66
72
|
|
|
67
73
|
| Rows | Field Type | Test Scenarios |
|
|
68
74
|
|------|------------|----------------|
|
|
69
75
|
| **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 |
|
|
76
|
+
| **5-9** | Scalar (`Diagnosis`, `Histology`) | Correct, incorrect, missing, spurious, and correct-empty (TN) extractions |
|
|
71
77
|
| **10-14** | List (`Treatment Drugs`, `Test Results`) | Perfect match, spurious items, missing items, correct empty, mixed results |
|
|
72
78
|
|
|
73
79
|
## 📊 Usage Modes
|
|
@@ -77,7 +83,7 @@ When you have LLM predictions in `Res: {Field Name}` columns:
|
|
|
77
83
|
|
|
78
84
|
```python
|
|
79
85
|
import pandas as pd
|
|
80
|
-
from
|
|
86
|
+
from llmvalidate import validate
|
|
81
87
|
|
|
82
88
|
df = pd.read_csv("data.csv", index_col="Patient ID")
|
|
83
89
|
# df must contain: "Field Name" and "Res: Field Name" columns
|
|
@@ -93,8 +99,8 @@ results_df, metrics_df = validate(
|
|
|
93
99
|
### Mode 2: Live LLM Inference + Validation
|
|
94
100
|
|
|
95
101
|
```python
|
|
96
|
-
from
|
|
97
|
-
from
|
|
102
|
+
from llmvalidate.structured import StructuredResult, StructuredGroup, StructuredField
|
|
103
|
+
from llmvalidate.utils import flatten_structured_result
|
|
98
104
|
|
|
99
105
|
def llm_callback(row, i, raw_text_column_name):
|
|
100
106
|
raw_text = row[raw_text_column_name]
|
|
@@ -135,12 +141,43 @@ results_df, metrics_df = validate(
|
|
|
135
141
|
| **Binary** | True/False detection | `True`, `False` | `True`, `False` |
|
|
136
142
|
| **Scalar** | Single text/numeric value | `"Lung Cancer"` <br> `42` | `"Breast Cancer"` <br> `38` |
|
|
137
143
|
| **List** | Multiple values | `["Drug A", "Drug B"]` <br> `"['Item1', 'Item2']"` | `["Drug A"]` <br> `[]` |
|
|
144
|
+
| **Coded** | A value **and** its code (ICD-10 / ICD-O-3, RxNorm) — scored as two facets | `X-value`: "Adenocarcinoma" <br> `X-code`: "8140/3" | via `StructuredField(..., code=...)` |
|
|
145
|
+
|
|
146
|
+
### Coded Fields (value + code)
|
|
147
|
+
|
|
148
|
+
A `StructuredField` may carry an optional **`code`** alongside its `value` — for coded
|
|
149
|
+
concepts such as ICD-10 / ICD-O-3 topography-morphology or RxNorm drug codes:
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
StructuredField(name="Primary Histology", value="Adenocarcinoma", code="8140/3",
|
|
153
|
+
confidence="High")
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
When `code` is set, the field flattens to **two scored facets** — `Primary Histology-value`
|
|
157
|
+
and `Primary Histology-code` — each compared against the label column of the same name.
|
|
158
|
+
`confidence` / `justification` stay attached to the logical field (a single
|
|
159
|
+
`Res: Primary Histology confidence` column), and its confidence breakdown is applied to
|
|
160
|
+
**both** facets. `value` and `code` may be lists (e.g. drug names + their RxNorm codes),
|
|
161
|
+
scored set-wise per facet.
|
|
162
|
+
|
|
163
|
+
When `code` is `None` (the default) the field flattens to a single `<name>` column as
|
|
164
|
+
before — fully backward-compatible. A coded field whose code is genuinely unknown should
|
|
165
|
+
still pass `code="-"` (the no-information sentinel), **not** `None`, so it keeps aligning
|
|
166
|
+
with the `-value` / `-code` label columns.
|
|
138
167
|
|
|
139
168
|
### Special Value Handling
|
|
140
169
|
- **`"-"`** = Labeled as "No information is available in the source document"
|
|
141
170
|
- **`null/empty/NaN`** = Field not labeled/evaluated (supports partial labeling where different cases may have labels for different field subsets)
|
|
142
171
|
- **Lists** - Can be Python lists `["a", "b"]` or stringified `"['a', 'b']"` (auto-converted)
|
|
143
172
|
|
|
173
|
+
The `"-"`-vs-empty distinction above applies to **label** columns only. In **prediction** (`Res:`)
|
|
174
|
+
columns there is no "not evaluated" state: `"-"`, `""`, `null`/`NaN`, whitespace-only strings and
|
|
175
|
+
`[]` are all treated identically as "nothing extracted" (scoring Mis against a labeled value, or
|
|
176
|
+
TN when the label is `"-"`). We still recommend emitting `"-"` uniformly, to keep predictions
|
|
177
|
+
symmetric with labels. **Exception — binary fields:** predictions must be an explicit
|
|
178
|
+
`True`/`False`; an empty prediction is "not True / not False", so it scores FN against a `True`
|
|
179
|
+
label and **FP** against a `False` label.
|
|
180
|
+
|
|
144
181
|
### Partial Labeling Support
|
|
145
182
|
The framework supports partial labeling scenarios where:
|
|
146
183
|
- Not every case needs labels for every field
|
|
@@ -151,21 +188,21 @@ The framework supports partial labeling scenarios where:
|
|
|
151
188
|
|
|
152
189
|
## 📈 Output Files
|
|
153
190
|
|
|
154
|
-
|
|
191
|
+
A `validate()` run generates two timestamped CSV files (a third, CI metrics, is added when you also run `bootstrap_CI` — see the demo above):
|
|
155
192
|
|
|
156
193
|
### 1. Results CSV (`YYYY-MM-DD HH-MM-SS results.csv`)
|
|
157
194
|
**Row-level analysis** with detailed per-case metrics:
|
|
158
195
|
|
|
159
196
|
**Original Data:**
|
|
160
197
|
- All input columns (labels, raw text, etc.)
|
|
161
|
-
- `Res: {Field}` columns with LLM predictions
|
|
162
|
-
- `Res: {Field} confidence` and `Res: {Field} justification` (if available)
|
|
198
|
+
- `Res: {Field}` columns with LLM predictions (coded fields split into `Res: {Field}-value` and `Res: {Field}-code`)
|
|
199
|
+
- `Res: {Field} confidence` and `Res: {Field} justification` (if available; kept per logical field, and shared across a coded field's two facets)
|
|
163
200
|
|
|
164
201
|
**Binary Fields:**
|
|
165
202
|
- `TP/FP/FN/TN: {Field}` - Confusion matrix counts (1 or 0 per row)
|
|
166
203
|
|
|
167
204
|
**Non-Binary Fields:**
|
|
168
|
-
- `Cor/
|
|
205
|
+
- `Cor/Mis/Spu: {Field}` - Item counts per row (Inc and TN are None for list fields)
|
|
169
206
|
- `Cor/Inc/Mis/Spu: {Field} items` - Actual item lists
|
|
170
207
|
- `Precision/Recall/F1/F2: {Field}` - Per-row metrics (list fields only)
|
|
171
208
|
|
|
@@ -185,9 +222,14 @@ The framework generates two timestamped CSV files for each validation run:
|
|
|
185
222
|
|
|
186
223
|
**Binary Metrics:** `TP`, `TN`, `FP`, `FN`, `precision`, `recall`, `F1/F2`, `accuracy`, `specificity`
|
|
187
224
|
|
|
188
|
-
**Non-Binary Metrics:** `cor`, `inc`, `mis`, `spu`, `precision/recall/F1/F2 (micro
|
|
225
|
+
**Non-Binary Metrics:** `cor`, `inc`, `mis`, `spu`, `TN`, `precision/recall/F1/F2 (micro and macro)`, `specificity`
|
|
226
|
+
|
|
227
|
+
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.
|
|
189
228
|
|
|
190
229
|
## ⚡ Performance Metrics Explained
|
|
230
|
+
|
|
231
|
+

|
|
232
|
+
|
|
191
233
|
### Binary Classification Metrics
|
|
192
234
|
|
|
193
235
|
For fields with True/False values (e.g., "Has metastasis"):
|
|
@@ -218,6 +260,7 @@ For scalar and list fields (e.g., "Diagnosis", "Treatment Drugs"):
|
|
|
218
260
|
| **Missing (Mis)** | Items present in label but not extracted | (Same example) → Mis=1 (DrugB missing) |
|
|
219
261
|
| **Spurious (Spu)** | Items extracted but not in label | Label: `["DrugA"]`, Prediction: `["DrugA", "DrugC"]` → Spu=1 |
|
|
220
262
|
| **Incorrect (Inc)** | Wrong values for scalar fields | Label: `"Cancer"`, Prediction: `"Diabetes"` → Inc=1 |
|
|
263
|
+
| **True Negative (TN)** | Scalar fields only: field correctly left empty | Label: `"-"`, Prediction: `""`/`"-"` → TN=1 |
|
|
221
264
|
|
|
222
265
|
#### Structured Extraction Formulas
|
|
223
266
|
|
|
@@ -225,8 +268,9 @@ For scalar and list fields (e.g., "Diagnosis", "Treatment Drugs"):
|
|
|
225
268
|
|--------|---------|---------|
|
|
226
269
|
| **Precision** | `Cor / (Cor + Spu + Inc)` | Of all extracted items, how many were correct? |
|
|
227
270
|
| **Recall** | `Cor / (Cor + Mis + Inc)` | Of all labeled items, how many were correctly extracted? |
|
|
271
|
+
| **Specificity** | `TN / (TN + Spu)` | Scalar fields only: of all cases labeled as having no information, how many were correctly left empty? |
|
|
228
272
|
|
|
229
|
-
**Note:**
|
|
273
|
+
**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.
|
|
230
274
|
|
|
231
275
|
The following formulas apply to both binary classification and structured extraction metrics:
|
|
232
276
|
|
|
@@ -243,7 +287,7 @@ The framework includes statistical confidence interval estimation using non-para
|
|
|
243
287
|
|
|
244
288
|
### Usage
|
|
245
289
|
```python
|
|
246
|
-
from
|
|
290
|
+
from llmvalidate import bootstrap_CI
|
|
247
291
|
|
|
248
292
|
# After running validation to get results_df
|
|
249
293
|
ci_results = bootstrap_CI(
|
|
@@ -324,7 +368,7 @@ pip install -r requirements.txt
|
|
|
324
368
|
pytest
|
|
325
369
|
|
|
326
370
|
# Run with coverage reporting
|
|
327
|
-
pytest --cov=
|
|
371
|
+
pytest --cov=llmvalidate
|
|
328
372
|
|
|
329
373
|
# Run specific test modules
|
|
330
374
|
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
|