generated from nhsengland/analyticsunit-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfull_pipeline_example.ipynb
590 lines (590 loc) · 18.6 KB
/
full_pipeline_example.ipynb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Example PrivacyFingerprint Workflow\n",
"\n",
"This notebook walks you through a potential end-to-end workflow, to introduce a user to how each component can be loaded and how they can be configured"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import sys\n",
"from spacy import displacy\n",
"from pycanon.anonymity import k_anonymity, t_closeness, l_diversity\n",
"\n",
"path_root = os.path.dirname(os.getcwd())\n",
"\n",
"if path_root not in sys.path:\n",
" sys.path.append(path_root)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from src.generate.synthea import GenerateSynthea\n",
"from src.generate.llm import GenerateLLM\n",
"from src.extraction.extraction import Extraction\n",
"from src.standardise_extraction.standardise_extraction import (\n",
" StandardiseExtraction,\n",
")\n",
"from src.privacy_risk_scorer.privacy_risk_scorer import PrivacyRiskScorer\n",
"from src.privacy_risk_explainer.privacy_risk_explainer import (\n",
" PrivacyRiskExplainer,\n",
")\n",
"\n",
"from src.config.experimental_config import load_experimental_config\n",
"from src.config.global_config import load_global_config"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Importing and Loading Global and Experimental Config\n",
"\n",
"**global_config_path** this is the location of the global config path and then the output folder name is redefined to ensure the example experiments are out in the open. (Normally the default output folder should be used for your own experiments.)\n",
"\n",
"**default_config_path** is given so the user can point to the default experimental config values. Currently the pipeline copies the original experimental config down into the folder, and if this exists, only uses the experimental config defined in that folder."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"# Loads global config and redefines the outputs to go to an example_output (normally default to an outputs folder which is git ignored in this repo.)\n",
"global_config_path = \"../config/global_config.yaml\"\n",
"global_config = load_global_config(global_config_path)\n",
"global_config.output_paths.output_folder = \"../example_output\"\n",
"\n",
"\n",
"default_config_path = \"../config/experimental_config.yaml\"\n",
"experimental_config = load_experimental_config(default_config_path)\n",
"experimental_config.outputs.experiment_name = \"example_pipeline_05_08_24\"\n",
"experimental_folder = f\"{global_config.output_paths.output_folder}/{experimental_config.outputs.experiment_name}\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Privacy Fingerprint End-to-End Overview\n",
"\n",
"The Pipeline has been broken down into four components:\n",
"1. **GenerateSynthea**: This generates a list of dictionary of synthetic patient records.\n",
"2. **GenerateLLM**: This generates medical notes using the outputs created from **GenerateSynthea**.\n",
"3. **Extraction**: This currently uses an LLM that is specialised to extract given entities from the synthetic medical notes produced by **GenerativeLLM**\n",
"4. **StandardiseExtraction**: This standardises the results extracted from the medical text.\n",
"5. **PrivacyRiskScorer**: This scores the uniqueness of standardised entity values extracted.\n",
"6. **PrivacyRiskExplainer**: Takes in the predicted transformed values, and transformed dataset generater from the gaussian copula, and calculates shapley values. \n",
"\n",
"Additionally each class will also take a path for the input required to create their output. This allows the user to break-up the pipeline and run from specific points in the pipeline."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. GenerateSynthea: Generating Synthetic Patient Data using Synthea "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Synthea-international is an expansion of Synthea, which is an open-source synthetic patient generator that produces de-identified health records for synthetic patients.\n",
"\n",
"GenerateSynthea is a class used to run Synthea. You will need to follow the instructions on the README to ensure Synthea is installed."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"experimental_config.synthea.path_output = f\"{experimental_folder}/synthea.json\"\n",
"experimental_config.synthea.population_num = \"10\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"output_synthea = GenerateSynthea(\n",
" global_config=global_config, syntheaconfig=experimental_config.synthea\n",
").run_or_load()\n",
"output_synthea"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. GenerateLLM: Generating Synthetic Patient Medical Notes "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This component uses a LLM model either hosted via Ollama to generate synthetic patient medical notes depending on the prompt template given below."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create Prompt Templates used in the Experimental Pipeline.\n",
"\n",
"This defines the template you want the generate component to use. In this example we use Llama2, and this is a prompt template that can be used to support this."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Functions needed to create prompt templates and save them for the experiments.\n",
"from src.config.prompt_template_handler import (\n",
" save_generate_template_to_json,\n",
" load_and_validate_generate_prompt_template,\n",
")\n",
"\n",
"# We are using llama 3.1 8B, which uses a llama 3 prompt template.\n",
"# Defines the path of where llama3 template lives in the generate folder.\n",
"# A llama2 template can also be used. However, you will need to change the experimental config.\n",
"generate_template_path = (\n",
" f\"{global_config.output_paths.generate_template}llama3_template.json\"\n",
")\n",
"\n",
"# This defines a template used by LLama3\n",
"generate_template = \"\"\"<|begin_of_text|>\n",
"<|start_header_id|>system<|end_header_id|>\n",
"You are a medical student answering an exam question about writing clinical notes for patients.\n",
"<|eot_id|>\n",
"\n",
"<|start_header_id|>user<|end_header_id|>\n",
"Keep in mind that your answer will be assessed based on incorporating all the provided information and the quality of prose.\n",
"\n",
"1. Use prose to write an example clinical note for this patient's doctor.\n",
"2. Use less than three sentences.\n",
"3. Do not provide recommendations.\n",
"4. Use the following information:\n",
"\n",
"{data}\n",
"<|eot_id|>\n",
"\n",
"<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n",
"\"\"\"\n",
"\n",
"# Saves the template to the path defined.\n",
"save_generate_template_to_json(\n",
" template_str=generate_template, file_path=generate_template_path\n",
")\n",
"\n",
"# Loads the template so the user can inspect the template saved.\n",
"loaded_generate_template = load_and_validate_generate_prompt_template(\n",
" filename=generate_template_path\n",
")\n",
"print(loaded_generate_template)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This runs GenerateLLM using the synthea output from the previous run, and saves the LLM output to the given path_output_llm.\n",
"\n",
"You can set **verbose** to true or false depending on whether you want outputs to print to the screen on run. "
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"experimental_config.generate.synthea_path = (\n",
" experimental_config.synthea.path_output\n",
")\n",
"experimental_config.generate.path_output = f\"{experimental_folder}/llm.json\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"output_llm = GenerateLLM(\n",
" global_config=global_config, generateconfig=experimental_config.generate\n",
").run_or_load()\n",
"output_llm"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. Extraction: Re-extracting Entities from the Patient Medical Notes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This uses a package called GliNER to extract out entities from the synthetic medical notes.\n",
"\n",
"Changing inputs to the **experimental_config.extraction.entity_list** allows you to look for more entities"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"experimental_config.extraction.llm_path = (\n",
" experimental_config.generate.path_output\n",
")\n",
"experimental_config.extraction.path_output = (\n",
" f\"{experimental_folder}/extraction.json\"\n",
")\n",
"experimental_config.extraction.entity_list = [\n",
" \"nhs number\",\n",
" \"person\",\n",
" \"date of birth\",\n",
" \"diagnosis\",\n",
"]\n",
"experimental_config.extraction.server_model_type = \"gliner\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"output_extraction = Extraction(\n",
" global_config=global_config,\n",
" extractionconfig=experimental_config.extraction,\n",
").run_or_load()\n",
"output_extraction"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Visualising Entities using DisplaCy\n",
"\n",
"This visualises the entities in an example clinical note using DisplaCy.\n",
"\n",
"We format the extracted entities into a dictionary compatable with DisplaCy, and display the string."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for string_id in ids:\n",
"\n",
" ents_dict = {\n",
" \"text\": output_llm[string_id],\n",
" \"ents\": output_extraction[string_id][\"Entities\"],\n",
" }\n",
"\n",
" displacy.render(ents_dict, manual=True, style=\"ent\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. StandardiseExtraction: Normalising Entities Extracted for Scoring"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This takes in the above List of Dictionary entities and begins to normalise the responses into a dataframe format.\n",
"\n",
"The standardisation process is broken down into many parts:\n",
"1. Entities are extracted from the object created from **Extraction**, and a set of functions can be applied to clean them during this process.\n",
"2. This creates a list of cleaned entities. Multiple entities can be extracted from the same person for a given entity type, for example diagnosis. Currently the codebase only takes the first entity given.\n",
"3. Next the outputs are normalised i.e. Dates can be written in multiple formats but have the same meaning.\n",
"4. Lastly the data is encoded and formatted as a numpy array ready for PyCorrectMatch\n",
"\n",
"In the src/config.py file:\n",
"\n",
"extra_preprocess_functions_per_entity defines how entities are cleaned while extracted from the extraction_output.\n",
"\n",
"```\n",
"extra_preprocess_functions_per_entity = {\"person\": [clean_name.remove_titles]}\n",
"```\n",
"\n",
"standardise_functions_per_entity defines how entities are extracted, and defines any normalisation process you may want on a column of entities.\n",
"```\n",
"standardise_functions_per_entity = {\n",
" \"person\": [extract_first_entity_from_list],\n",
" \"nhs number\": [extract_first_entity_from_list],\n",
" \"date of birth\": [\n",
" extract_first_entity_from_list,\n",
" normalise_columns.normalise_date_column,\n",
" ],\n",
" \"diagnosis\": [extract_first_entity_from_list],\n",
"}\n",
"```\n",
"\n",
"This uses the output_extraction value created by the **Extraction** class and saves the outputs of the normalisation process as a .csv to the given path."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"path_output_standardisation = f\"{experimental_folder}/standardisation.csv\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"output_standards = StandardiseExtraction(\n",
" extraction_input=output_extraction,\n",
" path_output=path_output_standardisation,\n",
" save_output=True,\n",
").run()\n",
"output_standards"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This loads an extraction input from the extraction_path provided, and creates the output_standards."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"output_standards = StandardiseExtraction(\n",
" extraction_path=experimental_config.extraction.path_output,\n",
" path_output=path_output_standardisation,\n",
" save_output=False,\n",
").run()\n",
"output_standards"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This loads a pre-saved output_standards from the given path provided."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"output_standards = StandardiseExtraction(\n",
" path_output=path_output_standardisation\n",
").load()\n",
"output_standards"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5. PrivacyRiskScorer: This scores the uniqueness of standardised entity values extracted."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try:\n",
" scorer = PrivacyRiskScorer(\n",
" scorer_config=experimental_config.pycorrectmatch\n",
" )\n",
"except ValueError as e:\n",
" print(e)"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {},
"outputs": [],
"source": [
"# Here we fit the model, this has to happen first before calculating scores or transforming\n",
"scorer.fit(output_standards)\n",
"# This is the transformed dataset from the real record values to the marginal values\n",
"transformed_dataset = scorer.map_records_to_copula(output_standards)\n",
"N_FEATURES = output_standards.shape[1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 6. PrivacyRiskExplainer: Takes in the predicted transformed values, and transformed dataset generater from the gaussian copula, and calculates shapley values. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# SHAP takes a while to run - a progress bar appears when running SHAP\n",
"try:\n",
" explainer = PrivacyRiskExplainer(\n",
" scorer.predict_transformed,\n",
" N_FEATURES,\n",
" explainer_config=experimental_config.explainers,\n",
" )\n",
"except ValueError as e:\n",
" print(e)\n",
"\n",
"# Calculating shapley values using the transformed_dataset\n",
"local_shapley_df, global_shap, exp_obj = explainer.explain(\n",
" transformed_dataset[[\"person\", \"nhs number\", \"date of birth\", \"diagnosis\"]]\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"global_shap"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Plot the mean shap values - global explanation\n",
"explainer.plot_global_explanation(exp_obj)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Plot the local shap values for a particular record\n",
"explainer.plot_local_explanation(exp_obj, 49)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 7. PyCanon \n",
"\n",
"Pycanon asseses the values of common privacy measuring metrics, such as K-Anonymity, I-Diversity and t-Closeness. \n",
"\n",
"For more information on these metrics see `docs/pycanon/pycanon_and_privacy_metrics.md`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Each entity used in extraction should be added to `config/experimental_config.yaml` under `pycanon` in order to be used for the following analysis. "
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [],
"source": [
"identifiers = experimental_config.pycanon.identifiers\n",
"quasi_identifiers = experimental_config.pycanon.quasi_identifiers\n",
"sensitive_attributes = experimental_config.pycanon.sensitive_attributes"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(\"K-Anonymity: \", k_anonymity(output_standards, quasi_identifiers))\n",
"print(\n",
" \"t-Closeness: \",\n",
" t_closeness(output_standards, quasi_identifiers, sensitive_attributes),\n",
")\n",
"print(\n",
" \"l-Diversity: \",\n",
" l_diversity(output_standards, quasi_identifiers, sensitive_attributes),\n",
")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "privfp-experiments",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.9"
}
},
"nbformat": 4,
"nbformat_minor": 4
}