-
Notifications
You must be signed in to change notification settings - Fork 105
/
Copy pathcat.py
1823 lines (1596 loc) · 86.8 KB
/
cat.py
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import glob
import shutil
import pickle
import json
import logging
import math
import time
import psutil
from time import sleep
from multiprocess import Process, Manager, cpu_count
from multiprocess.queues import Queue
from multiprocess.synchronize import Lock
from typing import Union, List, Tuple, Optional, Dict, Iterable, Set
from itertools import islice, chain, repeat
from datetime import date
from tqdm.autonotebook import tqdm, trange
from spacy.tokens import Span, Doc, Token
import humanfriendly
from medcat import __version__
from medcat.preprocessing.tokenizers import spacy_split_all
from medcat.pipe import Pipe
from medcat.preprocessing.taggers import tag_skip_and_punct
from medcat.cdb import CDB
from medcat.utils.data_utils import make_mc_train_test, get_false_positives
from medcat.utils.normalizers import BasicSpellChecker
from medcat.utils.checkpoint import Checkpoint, CheckpointConfig, CheckpointManager
from medcat.utils.helpers import tkns_from_doc, get_important_config_parameters, has_new_spacy
from medcat.utils.hasher import Hasher
from medcat.ner.vocab_based_ner import NER
from medcat.linking.context_based_linker import Linker
from medcat.preprocessing.cleaners import prepare_name
from medcat.meta_cat import MetaCAT
from medcat.rel_cat import RelCAT
from medcat.utils.meta_cat.data_utils import json_to_fake_spacy
from medcat.config import Config
from medcat.vocab import Vocab
from medcat.ner.transformers_ner import TransformersNER
from medcat.utils.saving.serializer import SPECIALITY_NAMES, ONE2MANY
from medcat.utils.saving.envsnapshot import get_environment_info, ENV_SNAPSHOT_FILE_NAME
from medcat.stats.stats import get_stats
from medcat.stats.mctexport import count_all_annotations, iter_anns
from medcat.utils.filters import set_project_filters
from medcat.utils.usage_monitoring import UsageMonitor
logger = logging.getLogger(__name__) # separate logger from the package-level one
HAS_NEW_SPACY = has_new_spacy()
MIN_GEN_LEN_FOR_WARN = 10_000
class CAT(object):
"""The main MedCAT class used to annotate documents, it is built on top of spaCy
and works as a spaCy pipeline. Creates an instance of a spaCy pipeline that can
be used as a spacy nlp model.
Args:
cdb (medcat.cdb.CDB):
The concept database that will be used for NER+L
config (medcat.config.Config):
Global configuration for medcat
vocab (medcat.vocab.Vocab, optional):
Vocabulary used for vector embeddings and spelling. Default: None
meta_cats (list of medcat.meta_cat.MetaCAT, optional):
A list of models that will be applied sequentially on each
detected annotation.
rel_cats (list of medcat.rel_cat.RelCAT, optional)
List of models applied sequentially on all detected annotations.
Attributes (limited):
cdb (medcat.cdb.CDB):
Concept database used with this CAT instance, please do not assign
this value directly.
config (medcat.config.Config):
The global configuration for medcat. Usually cdb.config will be used for this
field. WILL BE REMOVED - TEMPORARY PLACEHOLDER
vocab (medcat.utils.vocab.Vocab):
The vocabulary object used with this instance, please do not assign
this value directly.
Examples:
>>> cat = CAT(cdb, vocab)
>>> spacy_doc = cat("Put some text here")
>>> print(spacy_doc.ents) # Detected entities
"""
DEFAULT_MODEL_PACK_NAME = "medcat_model_pack"
def __init__(self,
cdb: CDB,
vocab: Union[Vocab, None] = None,
config: Optional[Config] = None,
meta_cats: List[MetaCAT] = [],
rel_cats: List[RelCAT] = [],
addl_ner: Union[TransformersNER, List[TransformersNER]] = []) -> None:
self.cdb = cdb
self.vocab = vocab
if config is None:
# Take config from the cdb
self.config = cdb.config
else:
# Take the new config and assign it to the CDB also
self.config = config
self.cdb.config = config
self._meta_cats = meta_cats
self._rel_cats = rel_cats
self._addl_ner = addl_ner if isinstance(addl_ner, list) else [addl_ner]
self._create_pipeline(self.config)
self.usage_monitor = UsageMonitor(self.config.version.id, self.config.general.usage_monitor)
def _create_pipeline(self, config: Config):
# Set log level
logger.setLevel(config.general.log_level)
# Build the pipeline
self.pipe = Pipe(tokenizer=spacy_split_all, config=config)
self.pipe.add_tagger(tagger=tag_skip_and_punct,
name='skip_and_punct',
additional_fields=['is_punct'])
if self.vocab is not None:
spell_checker = BasicSpellChecker(cdb_vocab=self.cdb.vocab, config=config, data_vocab=self.vocab)
self.pipe.add_token_normalizer(spell_checker=spell_checker, config=config)
# Add NER
self.ner = NER(self.cdb, config)
self.pipe.add_ner(self.ner)
# Add LINKER
self.linker = Linker(self.cdb, self.vocab, config)
self.pipe.add_linker(self.linker)
# Add addl_ner if they exist
for ner in self._addl_ner:
self.pipe.add_addl_ner(ner, ner.config.general.name)
# Add meta_annotation classes if they exist
for meta_cat in self._meta_cats:
self.pipe.add_meta_cat(meta_cat, meta_cat.config.general.category_name)
for rel_cat in self._rel_cats:
self.pipe.add_rel_cat(rel_cat, "_".join(list(rel_cat.config.general["labels2idx"].keys())))
# Set max document length
self.pipe.spacy_nlp.max_length = config.preprocessing.max_document_length
def get_hash(self, force_recalc: bool = False) -> str:
"""Will not be a deep hash but will try to catch all the changing parts during training.
Able to force recalculation of hash. This is relevant for CDB
the hash for which is otherwise only recalculated if it has changed.
Args:
force_recalc (bool): Whether to force recalculation. Defaults to False.
Returns:
str: The resulting hash
"""
hasher = Hasher()
if self.config.general.simple_hash:
logger.info("Using simplified hashing that only takes into account the model card")
hasher.update(self.get_model_card())
return hasher.hexdigest()
hasher.update(self.cdb.get_hash(force_recalc))
hasher.update(self.config.get_hash())
for mc in self._meta_cats:
hasher.update(mc.get_hash())
for trf in self._addl_ner:
hasher.update(trf.get_hash())
return hasher.hexdigest()
def get_model_card(self, as_dict: bool = False):
"""A minimal model card for MedCAT model packs.
Args:
as_dict (bool):
Whether to return the model card as a dictionary instead of a str (Default value False).
Returns:
str:
The string representation of the JSON object.
OR
dict:
The dict JSON object.
"""
card = {
'Model ID': self.config.version.id,
'Last Modified On': self.config.version.last_modified,
'History (from least to most recent)': self.config.version.history,
'Description': self.config.version.description,
'Source Ontology': self.config.version.ontology,
'Location': self.config.version.location,
'MetaCAT models': self.config.version.meta_cats,
'Basic CDB Stats': self.config.version.cdb_info,
'Performance': self.config.version.performance,
'Important Parameters (Partial view, all available in cat.config)': get_important_config_parameters(self.config),
'MedCAT Version': self.config.version.medcat_version
}
if as_dict:
return card
else:
return json.dumps(card, indent=2, sort_keys=False)
def _versioning(self, force_rehash: bool = False):
# Check version info and do not allow without it
if self.config.version.description == 'No description':
logger.warning("Please consider populating the version information [description, performance, location, ontology] in cat.config.version")
# Fill the stuff automatically that is needed for versioning
m = self.get_hash(force_recalc=force_rehash)
version = self.config.version
if version.id is None or m != version.id:
if version.id is not None:
version.history.append(version['id'])
version.id = m
version.last_modified = date.today().strftime("%d %B %Y")
version.cdb_info = self.cdb.make_stats()
version.meta_cats = [meta_cat.get_model_card(as_dict=True) for meta_cat in self._meta_cats]
version.medcat_version = __version__
logger.warning("Please consider updating [description, performance, location, ontology] in cat.config.version")
def create_model_pack(self, save_dir_path: str, model_pack_name: str = DEFAULT_MODEL_PACK_NAME, force_rehash: bool = False,
cdb_format: str = 'dill') -> str:
"""Will crete a .zip file containing all the models in the current running instance
of MedCAT. This is not the most efficient way, for sure, but good enough for now.
Args:
save_dir_path (str):
An id will be appended to this name
model_pack_name (str):
The model pack name. Defaults to DEFAULT_MODEL_PACK_NAME.
force_rehash (bool):
Force recalculation of hash. Defaults to `False`.
cdb_format (str):
The format of the saved CDB in the model pack.
The available formats are:
- dill
- json
Defaults to 'dill'
Returns:
str:
Model pack name
"""
# Spacy model always should be just the name, but during loading it can be reset to path
self.config.general.spacy_model = os.path.basename(self.config.general.spacy_model)
# Versioning
self._versioning(force_rehash)
model_pack_name += "_{}".format(self.config.version.id)
logger.warning("This will save all models into a zip file, can take some time and require quite a bit of disk space.")
_save_dir_path = save_dir_path
save_dir_path = os.path.join(save_dir_path, model_pack_name)
# Check format
if cdb_format.lower() == 'json':
json_path = save_dir_path # in the same folder!
else:
json_path = None # use dill formatting
logger.info('Saving model pack with CDB in %s format', cdb_format)
# expand user path to make this work with '~'
os.makedirs(os.path.expanduser(save_dir_path), exist_ok=True)
# Save the used spacy model
spacy_path = os.path.join(save_dir_path, self.config.general.spacy_model)
if str(self.pipe.spacy_nlp._path) != spacy_path:
# First remove if something is there
shutil.rmtree(spacy_path, ignore_errors=True)
shutil.copytree(str(self.pipe.spacy_nlp._path), spacy_path)
# Save the CDB
cdb_path = os.path.join(save_dir_path, "cdb.dat")
self.cdb.save(cdb_path, json_path)
# Save the config
config_path = os.path.join(save_dir_path, "config.json")
self.cdb.config.save(config_path)
# Save the Vocab
vocab_path = os.path.join(save_dir_path, "vocab.dat")
if self.vocab is not None:
# We will allow creation of modelpacks without vocabs
self.vocab.save(vocab_path)
# Save addl_ner
for comp in self.pipe.spacy_nlp.components:
if isinstance(comp[1], TransformersNER):
trf_path = os.path.join(save_dir_path, "trf_" + comp[1].config.general.name)
comp[1].save(trf_path)
# Save all meta_cats
for comp in self.pipe.spacy_nlp.components:
if isinstance(comp[1], MetaCAT):
name = comp[0]
meta_path = os.path.join(save_dir_path, "meta_" + name)
comp[1].save(meta_path)
if isinstance(comp[1], RelCAT):
name = comp[0]
rel_path = os.path.join(save_dir_path, "rel_" + name)
comp[1].save(rel_path)
# Add a model card also, why not
model_card_path = os.path.join(save_dir_path, "model_card.json")
with open(model_card_path, 'w') as f:
json.dump(self.get_model_card(as_dict=True), f, indent=2)
# add a dependency snapshot
env_info = get_environment_info()
env_info_path = os.path.join(save_dir_path, ENV_SNAPSHOT_FILE_NAME)
with open(env_info_path, 'w') as f:
json.dump(env_info, f)
# Zip everything
shutil.make_archive(os.path.join(_save_dir_path, model_pack_name), 'zip', root_dir=save_dir_path)
# Log model card and return new name
logger.info(self.get_model_card()) # Print the model card
return model_pack_name
@classmethod
def attempt_unpack(cls, zip_path: str) -> str:
"""Attempt unpack the zip to a folder and get the model pack path.
If the folder already exists, no unpacking is done.
Args:
zip_path (str): The ZIP path
Returns:
str: The model pack path
"""
base_dir = os.path.dirname(zip_path)
filename = os.path.basename(zip_path)
foldername = filename.replace(".zip", '')
model_pack_path = os.path.join(base_dir, foldername)
if os.path.exists(model_pack_path):
logger.info("Found an existing unzipped model pack at: {}, the provided zip will not be touched.".format(model_pack_path))
else:
logger.info("Unziping the model pack and loading models.")
shutil.unpack_archive(zip_path, extract_dir=model_pack_path)
return model_pack_path
@classmethod
def load_model_pack(cls,
zip_path: str,
meta_cat_config_dict: Optional[Dict] = None,
ner_config_dict: Optional[Dict] = None,
medcat_config_dict: Optional[Dict] = None,
load_meta_models: bool = True,
load_addl_ner: bool = True,
load_rel_models: bool = True) -> "CAT":
"""Load everything within the 'model pack', i.e. the CDB, config, vocab and any MetaCAT models
(if present)
Args:
zip_path (str):
The path to model pack zip.
meta_cat_config_dict (Optional[Dict]):
A config dict that will overwrite existing configs in meta_cat.
e.g. meta_cat_config_dict = {'general': {'device': 'cpu'}}.
Defaults to None.
ner_config_dict (Optional[Dict]):
A config dict that will overwrite existing configs in transformers ner.
e.g. ner_config_dict = {'general': {'chunking_overlap_window': 6}.
Defaults to None.
medcat_config_dict (Optional[Dict]):
A config dict that will overwrite existing configs in the main medcat config
before pipe initialisation. This can be useful if wanting to change something
that only takes effect at init time (e.g spacy model). Defaults to None.
load_meta_models (bool):
Whether to load MetaCAT models if present (Default value True).
load_addl_ner (bool):
Whether to load additional NER models if present (Default value True).
load_rel_models (bool):
Whether to load RelCAT models if present (Default value True).
Returns:
CAT: The resulting CAT object.
"""
from medcat.cdb import CDB
from medcat.vocab import Vocab
from medcat.meta_cat import MetaCAT
from medcat.rel_cat import RelCAT
model_pack_path = cls.attempt_unpack(zip_path)
# Load the CDB
cdb: CDB = cls.load_cdb(model_pack_path)
# load config
config_path = os.path.join(model_pack_path, "config.json")
cdb.load_config(config_path, medcat_config_dict)
# TODO load addl_ner
# Modify the config to contain full path to spacy model
cdb.config.general.spacy_model = os.path.join(model_pack_path, os.path.basename(cdb.config.general.spacy_model))
# Load Vocab
vocab_path = os.path.join(model_pack_path, "vocab.dat")
if os.path.exists(vocab_path):
vocab = Vocab.load(vocab_path)
else:
vocab = None
# Find ner models in the model_pack
trf_paths = [os.path.join(model_pack_path, path) for path in os.listdir(model_pack_path) if path.startswith('trf_')] if load_addl_ner else []
addl_ner = []
for trf_path in trf_paths:
trf = TransformersNER.load(save_dir_path=trf_path,config_dict=ner_config_dict)
trf.cdb = cdb # Set the cat.cdb to be the CDB of the TRF model
addl_ner.append(trf)
# Find metacat models in the model_pack
meta_cats: List[MetaCAT] = []
if load_meta_models:
meta_cats = [mc[1] for mc in cls.load_meta_cats(model_pack_path, meta_cat_config_dict)]
# Find Rel models in model_pack
rel_paths = [os.path.join(model_pack_path, path) for path in os.listdir(model_pack_path) if path.startswith('rel_')] if load_rel_models else []
rel_cats = []
for rel_path in rel_paths:
rel_cats.append(RelCAT.load(load_path=rel_path))
cat = cls(cdb=cdb, config=cdb.config, vocab=vocab, meta_cats=meta_cats, addl_ner=addl_ner, rel_cats=rel_cats)
logger.info(cat.get_model_card()) # Print the model card
return cat
@classmethod
def load_cdb(cls, model_pack_path: str) -> CDB:
"""
Loads the concept database from the provided model pack path
Args:
model_pack_path (str): path to model pack, zip or dir.
Returns:
CDB: The loaded concept database
"""
cdb_path = os.path.join(model_pack_path, "cdb.dat")
nr_of_jsons_expected = len(SPECIALITY_NAMES) - len(ONE2MANY)
has_jsons = len(glob.glob(os.path.join(model_pack_path, '*.json'))) >= nr_of_jsons_expected
json_path = model_pack_path if has_jsons else None
logger.info('Loading model pack with %s', 'JSON format' if json_path else 'dill format')
cdb = CDB.load(cdb_path, json_path)
return cdb
@classmethod
def load_meta_cats(cls, model_pack_path: str, meta_cat_config_dict: Optional[Dict] = None) -> List[Tuple[str, MetaCAT]]:
"""
Args:
model_pack_path (str): path to model pack, zip or dir.
meta_cat_config_dict (Optional[Dict]):
A config dict that will overwrite existing configs in meta_cat.
e.g. meta_cat_config_dict = {'general': {'device': 'cpu'}}.
Defaults to None.
Returns:
List[Tuple(str, MetaCAT)]: list of pairs of meta cat model names (i.e. the task name) and the MetaCAT models.
"""
meta_paths = [os.path.join(model_pack_path, path)
for path in os.listdir(model_pack_path) if path.startswith('meta_')]
meta_cats = []
for meta_path in meta_paths:
meta_cats.append(MetaCAT.load(save_dir_path=meta_path,
config_dict=meta_cat_config_dict))
return list(zip(meta_paths, meta_cats))
def __call__(self, text: Optional[str], do_train: bool = False) -> Optional[Doc]:
"""Push the text through the pipeline.
Args:
text (Optional[str]):
The text to be annotated, if the text length is longer than
self.config.preprocessing['max_document_length'] it will be trimmed to that length.
do_train (bool):
This causes so many screwups when not there, so I'll force training
to False. To run training it is much better to use the self.train() function
but for some special cases I'm leaving it here also.
Defaults to `False`.
Returns:
Optional[Doc]:
A single spacy document or multiple spacy documents with the extracted entities
"""
# Should we train - do not use this for training, unless you know what you are doing. Use the
#self.train() function
self.config.linking.train = do_train
if text is None:
logger.error("The input text should be either a string or a sequence of strings but got %s", type(text))
return None
else:
text = str(text) # NOTE: shouldn't be necessary but left it in
if self.config.general.usage_monitor.enabled:
l1 = len(text)
text = self._get_trimmed_text(text)
l2 = len(text)
rval = self.pipe(text)
# NOTE: pipe returns Doc (not List[Doc]) since we passed str (not List[str])
# that's why we ignore type here
# But it could still be None if the text is empty
if rval is None:
nents = 0
elif self.config.general.show_nested_entities:
nents = len(rval._.ents) # type: ignore
else:
nents = len(rval.ents) # type: ignore
self.usage_monitor.log_inference(l1, l2, nents)
return rval # type: ignore
else:
text = self._get_trimmed_text(text)
return self.pipe(text) # type: ignore
def __repr__(self) -> str:
"""Prints the model_card for this CAT instance.
Returns:
str: the 'Model Card' for this CAT instance. This includes NER+L config and any MetaCATs
"""
return self.get_model_card(as_dict=False)
def _print_stats(self,
data: Dict,
epoch: int = 0,
use_project_filters: bool = False,
use_overlaps: bool = False,
use_cui_doc_limit: bool = False,
use_groups: bool = False,
extra_cui_filter: Optional[Set] = None,
do_print: bool = True) -> Tuple:
"""TODO: Refactor and make nice
Print metrics on a dataset (F1, P, R), it will also print the concepts that have the most FP,FN,TP.
Args:
data (Dict):
The json object that we get from MedCATtrainer on export.
epoch (int):
Used during training, so we know what epoch is it.
use_project_filters (bool):
Each project in MedCATtrainer can have filters, do we want to respect those filters
when calculating metrics.
use_overlaps (bool):
Allow overlapping entities, nearly always False as it is very difficult to annotate overlapping entities.
use_cui_doc_limit (bool):
If True the metrics for a CUI will be only calculated if that CUI appears in a document, in other words
if the document was annotated for that CUI. Useful in very specific situations when during the annotation
process the set of CUIs changed.
use_groups (bool):
If True concepts that have groups will be combined and stats will be reported on groups.
extra_cui_filter(Optional[Set]):
This filter will be intersected with all other filters, or if all others are not set then only this one will be used.
do_print (bool):
Whether to print stats out. Defaults to True.
Returns:
fps (dict):
False positives for each CUI.
fns (dict):
False negatives for each CUI.
tps (dict):
True positives for each CUI.
cui_prec (dict):
Precision for each CUI.
cui_rec (dict):
Recall for each CUI.
cui_f1 (dict):
F1 for each CUI.
cui_counts (dict):
Number of occurrence for each CUI.
examples (dict):
Examples for each of the fp, fn, tp. Format will be examples['fp']['cui'][<list_of_examples>].
"""
return get_stats(self, data=data, epoch=epoch, use_project_filters=use_project_filters,
use_overlaps=use_overlaps, use_cui_doc_limit=use_cui_doc_limit,
use_groups=use_groups, extra_cui_filter=extra_cui_filter, do_print=do_print)
def _init_ckpts(self, is_resumed, checkpoint):
if self.config.general.checkpoint.steps is not None or checkpoint is not None:
checkpoint_config = CheckpointConfig(**self.config.general.checkpoint.model_dump())
checkpoint_manager = CheckpointManager('cat_train', checkpoint_config)
if is_resumed:
# TODO: probably remove is_resumed mark and always resume if a checkpoint is provided,
#but I'll leave it for now
checkpoint = checkpoint or checkpoint_manager.get_latest_checkpoint()
logger.info(f"Resume training on the most recent checkpoint at {checkpoint.dir_path}...")
self.cdb = checkpoint.restore_latest_cdb()
self.cdb.config.merge_config(self.config.asdict())
self.config = self.cdb.config
self._create_pipeline(self.config)
else:
checkpoint = checkpoint or checkpoint_manager.create_checkpoint()
logger.info(f"Start new training and checkpoints will be saved at {checkpoint.dir_path}...")
return checkpoint
def train(self,
data_iterator: Iterable,
nepochs: int = 1,
fine_tune: bool = True,
progress_print: int = 1000,
checkpoint: Optional[Checkpoint] = None,
is_resumed: bool = False) -> None:
"""Runs training on the data, note that the maximum length of a line
or document is 1M characters. Anything longer will be trimmed.
Args:
data_iterator (Iterable):
Simple iterator over sentences/documents, e.g. a open file
or an array or anything that we can use in a for loop.
nepochs (int):
Number of epochs for which to run the training.
fine_tune (bool):
If False old training will be removed.
progress_print (int):
Print progress after N lines.
checkpoint (Optional[medcat.utils.checkpoint.CheckpointUT]):
The MedCAT checkpoint object
is_resumed (bool):
If True resume the previous training; If False, start a fresh new training.
"""
if not fine_tune:
logger.info("Removing old training data!")
self.cdb.reset_training()
checkpoint = self._init_ckpts(is_resumed, checkpoint)
# cache train state
_prev_train = self.config.linking.train
latest_trained_step = checkpoint.count if checkpoint is not None else 0
epochal_data_iterator = chain.from_iterable(repeat(data_iterator, nepochs))
for line in islice(epochal_data_iterator, latest_trained_step, None):
if line is not None and line:
# Convert to string
line = str(line).strip()
try:
_ = self(line, do_train=True)
except Exception as e:
logger.warning("LINE: '%s...' \t WAS SKIPPED", line[0:100])
logger.warning("BECAUSE OF: %s", str(e))
else:
logger.warning("EMPTY LINE WAS DETECTED AND SKIPPED")
latest_trained_step += 1
if latest_trained_step % progress_print == 0:
logger.info("DONE: %s", str(latest_trained_step))
if checkpoint is not None and checkpoint.steps is not None and latest_trained_step % checkpoint.steps == 0:
checkpoint.save(cdb=self.cdb, count=latest_trained_step)
self.config.linking.train = _prev_train
def add_cui_to_group(self, cui: str, group_name: str) -> None:
"""Adds a CUI to a group, will appear in cdb.addl_info['cui2group']
Args:
cui (str):
The concept to be added.
group_name (str):
The group to which the concept will be added.
Examples:
>>> cat.add_cui_to_group("S-17", 'pain')
"""
# Add group_name
self.cdb.addl_info['cui2group'][cui] = group_name
def unlink_concept_name(self, cui: str, name: str, preprocessed_name: bool = False) -> None:
"""Unlink a concept name from the CUI (or all CUIs if full_unlink), removes the link from
the Concept Database (CDB). As a consequence medcat will never again link the `name`
to this CUI - meaning the name will not be detected as a concept in the future.
Args:
cui (str):
The CUI from which the `name` will be removed.
name (str):
The span of text to be removed from the linking dictionary.
preprocessed_name (bool):
Whether the name being used is preprocessed.
Examples:
>>> # To never again link C0020538 to HTN
>>> cat.unlink_concept_name('C0020538', 'htn', False)
"""
cuis = [cui]
if preprocessed_name:
names = {name: {'nothing': 'nothing'}}
else:
names = prepare_name(name, self.pipe.spacy_nlp, {}, self.config)
# If full unlink find all CUIs
if self.config.general.full_unlink:
logger.warning("In the config `full_unlink` is set to `True`. "
"Thus removing all CUIs linked to the specified name"
" (%s)", name)
for n in names:
cuis.extend(self.cdb.name2cuis.get(n, []))
# Remove name from all CUIs
for c in cuis:
self.cdb._remove_names(cui=c, names=names.keys())
def add_and_train_concept(self,
cui: str,
name: str,
spacy_doc: Optional[Doc] = None,
spacy_entity: Optional[Union[List[Token], Span]] = None,
ontologies: Set[str] = set(),
name_status: str = 'A',
type_ids: Set[str] = set(),
description: str = '',
full_build: bool = True,
negative: bool = False,
devalue_others: bool = False,
do_add_concept: bool = True) -> None:
r"""Add a name to an existing concept, or add a new concept, or do not do anything if the name or concept already exists. Perform
training if spacy_entity and spacy_doc are set.
Args:
cui (str):
CUI of the concept.
name (str):
Name to be linked to the concept (in the case of MedCATtrainer this is simply the
selected value in text, no preprocessing or anything needed).
spacy_doc (spacy.tokens.Doc):
Spacy representation of the document that was manually annotated.
spacy_entity (Optional[Union[List[Token], Span]]):
Given the spacy document, this is the annotated span of text - list of annotated tokens that are marked with this CUI.
ontologies (Set[str]):
ontologies in which the concept exists (e.g. SNOMEDCT, HPO)
name_status (str):
One of `P`, `N`, `A`
type_ids (Set[str]):
Semantic type identifier (have a look at TUIs in UMLS or SNOMED-CT)
description (str):
Description of this concept.
full_build (bool):
If True the dictionary self.addl_info will also be populated, contains a lot of extra information
about concepts, but can be very memory consuming. This is not necessary
for normal functioning of MedCAT (Default Value `False`).
negative (bool):
Is this a negative or positive example.
devalue_others (bool):
If set, cuis to which this name is assigned and are not `cui` will receive negative training given
that negative=False.
do_add_concept (bool):
Whether to add concept to CDB.
"""
names = prepare_name(name, self.pipe.spacy_nlp, {}, self.config)
if not names and cui not in self.cdb.cui2preferred_name and name_status == 'P':
logger.warning("No names were able to be prepared in CAT.add_and_train_concept "
"method. As such no preferred name will be able to be specifeid. "
"The CUI: '%s' and raw name: '%s'", cui, name)
# Only if not negative, otherwise do not add the new name if in fact it should not be detected
if do_add_concept and not negative:
self.cdb._add_concept(cui=cui, names=names, ontologies=ontologies, name_status=name_status, type_ids=type_ids, description=description,
full_build=full_build)
if spacy_entity is not None and spacy_doc is not None:
# Train Linking
self.linker.context_model.train(cui=cui, entity=spacy_entity, doc=spacy_doc, negative=negative, names=names) # type: ignore
if not negative and devalue_others:
# Find all cuis
cuis = set()
for n in names:
cuis.update(self.cdb.name2cuis.get(n, []))
# Remove the cui for which we just added positive training
if cui in cuis:
cuis.remove(cui)
# Add negative training for all other CUIs that link to these names
for _cui in cuis:
self.linker.context_model.train(cui=_cui, entity=spacy_entity, doc=spacy_doc, negative=True) # type: ignore
def train_supervised_from_json(self,
data_path: str,
reset_cui_count: bool = False,
nepochs: int = 1,
print_stats: int = 0,
use_filters: bool = False,
terminate_last: bool = False,
use_overlaps: bool = False,
use_cui_doc_limit: bool = False,
test_size: int = 0,
devalue_others: bool = False,
use_groups: bool = False,
never_terminate: bool = False,
train_from_false_positives: bool = False,
extra_cui_filter: Optional[Set] = None,
retain_extra_cui_filter: bool = False,
checkpoint: Optional[Checkpoint] = None,
retain_filters: bool = False,
is_resumed: bool = False,
train_meta_cats: bool = False) -> Tuple:
"""
Run supervised training on a dataset from MedCATtrainer in JSON format.
Refer to `train_supervised_raw` for more details.
# noqa: DAR101
# noqa: DAR201
"""
with open(data_path) as f:
data = json.load(f)
return self.train_supervised_raw(data, reset_cui_count, nepochs,
print_stats, use_filters, terminate_last,
use_overlaps, use_cui_doc_limit, test_size,
devalue_others, use_groups, never_terminate,
train_from_false_positives, extra_cui_filter,
retain_extra_cui_filter, checkpoint,
retain_filters, is_resumed, train_meta_cats)
def train_supervised_raw(self,
data: Dict[str, List[Dict[str, dict]]],
reset_cui_count: bool = False,
nepochs: int = 1,
print_stats: int = 0,
use_filters: bool = False,
terminate_last: bool = False,
use_overlaps: bool = False,
use_cui_doc_limit: bool = False,
test_size: float = 0,
devalue_others: bool = False,
use_groups: bool = False,
never_terminate: bool = False,
train_from_false_positives: bool = False,
extra_cui_filter: Optional[Set] = None,
retain_extra_cui_filter: bool = False,
checkpoint: Optional[Checkpoint] = None,
retain_filters: bool = False,
is_resumed: bool = False,
train_meta_cats: bool = False) -> Tuple:
"""Train supervised based on the raw data provided.
The raw data is expected in the following format:
{'projects':
[ # list of projects
{ # project 1
'name': '<some name>',
# list of documents
'documents': [{'name': '<some name>', # document 1
'text': '<text of the document>',
# list of annotations
'annotations': [{'start': -1, # annotation 1
'end': 1,
'cui': 'cui',
'value': '<text value>'}, ...],
}, ...]
}, ...
]
}
Please take care that this is more a simulated online training then supervised.
When filtering, the filters within the CAT model are used first,
then the ones from MedCATtrainer (MCT) export filters,
and finally the extra_cui_filter (if set).
That is to say, the expectation is:
extra_cui_filter ⊆ MCT filter ⊆ Model/config filter.
Args:
data (Dict[str, List[Dict[str, dict]]]):
The raw data, e.g from MedCATtrainer on export.
reset_cui_count (bool):
Used for training with weight_decay (annealing). Each concept has a count that is there
from the beginning of the CDB, that count is used for annealing. Resetting the count will
significantly increase the training impact. This will reset the count only for concepts
that exist in the the training data.
nepochs (int):
Number of epochs for which to run the training.
print_stats (int):
If > 0 it will print stats every print_stats epochs.
use_filters (bool):
Each project in medcattrainer can have filters, do we want to respect those filters
when calculating metrics.
terminate_last (bool):
If true, concept termination will be done after all training.
use_overlaps (bool):
Allow overlapping entities, nearly always False as it is very difficult to annotate overlapping entities.
use_cui_doc_limit (bool):
If True the metrics for a CUI will be only calculated if that CUI appears in a document, in other words
if the document was annotated for that CUI. Useful in very specific situations when during the annotation
process the set of CUIs changed.
test_size (float):
If > 0 the data set will be split into train test based on this ration. Should be between 0 and 1.
Usually 0.1 is fine.
devalue_others(bool):
Check add_name for more details.
use_groups (bool):
If True concepts that have groups will be combined and stats will be reported on groups.
never_terminate (bool):
If True no termination will be applied
train_from_false_positives (bool):
If True it will use false positive examples detected by medcat and train from them as negative examples.
extra_cui_filter(Optional[Set]):
This filter will be intersected with all other filters, or if all others are not set then only this one will be used.
retain_extra_cui_filter(bool):
Whether to retain the extra filters instead of the MedCATtrainer export filters.
This will only have an effect if/when retain_filters is set to True. Defaults to False.
checkpoint (Optional[Optional[medcat.utils.checkpoint.CheckpointST]):
The MedCAT CheckpointST object
retain_filters (bool):
If True, retain the filters in the MedCATtrainer export within this CAT instance. In other words, the
filters defined in the input file will henseforth be saved within config.linking.filters .
This only makes sense if there is only one project in the input data. If that is not the case,
a ValueError is raised. The merging is done in the first epoch.
is_resumed (bool):
If True resume the previous training; If False, start a fresh new training.
train_meta_cats (bool):
If True, also trains the appropriate MetaCATs.
Raises:
ValueError: If attempting to retain filters with while training over multiple projects.
Returns:
Tuple: Consisting of the following parts
fp (dict):
False positives for each CUI.
fn (dict):
False negatives for each CUI.
tp (dict):
True positives for each CUI.
p (dict):
Precision for each CUI.
r (dict):
Recall for each CUI.
f1 (dict):
F1 for each CUI.
cui_counts (dict):
Number of occurrence for each CUI.
examples (dict):
FP/FN examples of sentences for each CUI.
"""
checkpoint = self._init_ckpts(is_resumed, checkpoint)
# the config.linking.filters stuff is used directly in
# medcat.linking.context_based_linker and medcat.linking.vector_context_model
# as such, they need to be kept up to date with per-project filters
# However, the original state needs to be kept track of
# so that it can be restored after training
orig_filters = self.config.linking.filters.copy_of()
local_filters = self.config.linking.filters
fp = fn = tp = p = r = f1 = examples = {}
cui_counts = {}
if retain_filters:
# TODO - allow specifying number of project to retain?
if len(data['projects']) > 1:
raise ValueError('Cannot retain multiple (potentially) different filters from multiple projects')
# will merge with local when loading in project
if test_size == 0:
logger.info("Running without a test set, or train==test")
test_set = data
train_set = data
else:
train_set, test_set, _, _ = make_mc_train_test(data, self.cdb, test_size=test_size)
if print_stats > 0:
fp, fn, tp, p, r, f1, cui_counts, examples = self._print_stats(test_set,
use_project_filters=use_filters,
use_cui_doc_limit=use_cui_doc_limit,
use_overlaps=use_overlaps,
use_groups=use_groups,
extra_cui_filter=extra_cui_filter)
if reset_cui_count:
# Get all CUIs
cuis = []
for project in train_set['projects']:
for doc in project['documents']:
doc_annotations = self._get_doc_annotations(doc)
for ann in doc_annotations:
cuis.append(ann['cui'])
for cui in set(cuis):
if cui in self.cdb.cui2count_train:
self.cdb.cui2count_train[cui] = 100
# Remove entities that were terminated
if not never_terminate: