cehrbert 1.1.0__py3-none-any.whl

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.

Potentially problematic release.


This version of cehrbert might be problematic. Click here for more details.

Files changed (114) hide show
  1. cehrbert/__init__.py +12 -0
  2. cehrbert/config/__init__.py +0 -0
  3. cehrbert/config/grid_search_config.py +13 -0
  4. cehrbert/config/output_names.py +9 -0
  5. cehrbert/const/__init__.py +0 -0
  6. cehrbert/const/common.py +28 -0
  7. cehrbert/data_generators/__init__.py +0 -0
  8. cehrbert/data_generators/data_classes.py +33 -0
  9. cehrbert/data_generators/data_generator_base.py +470 -0
  10. cehrbert/data_generators/graph_sample_method.py +75 -0
  11. cehrbert/data_generators/hf_data_generator/__init__.py +0 -0
  12. cehrbert/data_generators/hf_data_generator/hf_dataset.py +133 -0
  13. cehrbert/data_generators/hf_data_generator/hf_dataset_collator.py +229 -0
  14. cehrbert/data_generators/hf_data_generator/hf_dataset_mapping.py +458 -0
  15. cehrbert/data_generators/hf_data_generator/meds_to_cehrbert_conversion_rules/__init__.py +2 -0
  16. cehrbert/data_generators/hf_data_generator/meds_to_cehrbert_conversion_rules/meds_to_cehrbert_base.py +137 -0
  17. cehrbert/data_generators/hf_data_generator/meds_to_cehrbert_conversion_rules/meds_to_cehrbert_micmic4.py +53 -0
  18. cehrbert/data_generators/hf_data_generator/meds_utils.py +398 -0
  19. cehrbert/data_generators/learning_objective.py +1173 -0
  20. cehrbert/data_generators/tokenizer.py +131 -0
  21. cehrbert/evaluations/__init__.py +0 -0
  22. cehrbert/evaluations/evaluation.py +354 -0
  23. cehrbert/evaluations/evaluation_parameters.py +28 -0
  24. cehrbert/evaluations/evaluation_parse_args.py +255 -0
  25. cehrbert/evaluations/model_evaluators/__init__.py +0 -0
  26. cehrbert/evaluations/model_evaluators/bert_model_evaluators.py +249 -0
  27. cehrbert/evaluations/model_evaluators/frequency_model_evaluators.py +146 -0
  28. cehrbert/evaluations/model_evaluators/hierarchical_bert_evaluators.py +283 -0
  29. cehrbert/evaluations/model_evaluators/model_evaluators.py +91 -0
  30. cehrbert/evaluations/model_evaluators/sequence_model_evaluators.py +444 -0
  31. cehrbert/evaluations/transfer_learning_evaluation.py +13 -0
  32. cehrbert/keras_transformer/__init__.py +0 -0
  33. cehrbert/keras_transformer/bert.py +109 -0
  34. cehrbert/keras_transformer/extras.py +143 -0
  35. cehrbert/keras_transformer/position.py +55 -0
  36. cehrbert/med_extension/__init__.py +0 -0
  37. cehrbert/med_extension/schema_extension.py +36 -0
  38. cehrbert/models/__init__.py +0 -0
  39. cehrbert/models/bert_models.py +169 -0
  40. cehrbert/models/bert_models_visit_prediction.py +208 -0
  41. cehrbert/models/evaluation_models.py +649 -0
  42. cehrbert/models/hf_models/__init__.py +0 -0
  43. cehrbert/models/hf_models/config.py +230 -0
  44. cehrbert/models/hf_models/hf_cehrbert.py +486 -0
  45. cehrbert/models/hf_models/hf_modeling_outputs.py +219 -0
  46. cehrbert/models/hf_models/tokenization_hf_cehrbert.py +349 -0
  47. cehrbert/models/hf_models/tokenization_utils.py +49 -0
  48. cehrbert/models/hierachical_bert_model_v2.py +380 -0
  49. cehrbert/models/hierachical_phenotype_model_new.py +433 -0
  50. cehrbert/models/layers/__init__.py +0 -0
  51. cehrbert/models/layers/custom_layers.py +941 -0
  52. cehrbert/models/layers/hierarchical_custom_layers.py +201 -0
  53. cehrbert/models/loss_schedulers.py +56 -0
  54. cehrbert/models/parse_args.py +430 -0
  55. cehrbert/runners/__init__.py +0 -0
  56. cehrbert/runners/hf_cehrbert_finetune_runner.py +337 -0
  57. cehrbert/runners/hf_cehrbert_pretrain_runner.py +275 -0
  58. cehrbert/runners/hf_runner_argument_dataclass.py +288 -0
  59. cehrbert/runners/runner_util.py +339 -0
  60. cehrbert/spark_apps/__init__.py +0 -0
  61. cehrbert/spark_apps/cohorts/__init__.py +0 -0
  62. cehrbert/spark_apps/cohorts/atrial_fibrillation.py +44 -0
  63. cehrbert/spark_apps/cohorts/cabg.py +71 -0
  64. cehrbert/spark_apps/cohorts/coronary_artery_disease.py +88 -0
  65. cehrbert/spark_apps/cohorts/covid.py +42 -0
  66. cehrbert/spark_apps/cohorts/covid_inpatient.py +83 -0
  67. cehrbert/spark_apps/cohorts/death.py +45 -0
  68. cehrbert/spark_apps/cohorts/heart_failure.py +422 -0
  69. cehrbert/spark_apps/cohorts/ischemic_stroke.py +44 -0
  70. cehrbert/spark_apps/cohorts/last_visit_discharged_home.py +34 -0
  71. cehrbert/spark_apps/cohorts/query_builder.py +153 -0
  72. cehrbert/spark_apps/cohorts/spark_app_base.py +745 -0
  73. cehrbert/spark_apps/cohorts/type_two_diabietes.py +170 -0
  74. cehrbert/spark_apps/cohorts/ventilation.py +22 -0
  75. cehrbert/spark_apps/decorators/__init__.py +0 -0
  76. cehrbert/spark_apps/decorators/patient_event_decorator.py +759 -0
  77. cehrbert/spark_apps/generate_concept_similarity_table.py +423 -0
  78. cehrbert/spark_apps/generate_hierarchical_bert_training_data.py +238 -0
  79. cehrbert/spark_apps/generate_included_concept_list.py +116 -0
  80. cehrbert/spark_apps/generate_information_content.py +131 -0
  81. cehrbert/spark_apps/generate_required_labs.py +109 -0
  82. cehrbert/spark_apps/generate_training_data.py +343 -0
  83. cehrbert/spark_apps/legacy/__init__.py +0 -0
  84. cehrbert/spark_apps/legacy/mortality.py +183 -0
  85. cehrbert/spark_apps/prediction_cohorts/__init__.py +0 -0
  86. cehrbert/spark_apps/prediction_cohorts/afib_ischemic_stroke.py +13 -0
  87. cehrbert/spark_apps/prediction_cohorts/cad_cabg_cohort.py +18 -0
  88. cehrbert/spark_apps/prediction_cohorts/cad_hf_cohort.py +18 -0
  89. cehrbert/spark_apps/prediction_cohorts/copd_readmission.py +69 -0
  90. cehrbert/spark_apps/prediction_cohorts/covid_death.py +13 -0
  91. cehrbert/spark_apps/prediction_cohorts/covid_ventilation.py +13 -0
  92. cehrbert/spark_apps/prediction_cohorts/discharge_home_death.py +22 -0
  93. cehrbert/spark_apps/prediction_cohorts/hf_readmission.py +79 -0
  94. cehrbert/spark_apps/prediction_cohorts/hospitalization.py +98 -0
  95. cehrbert/spark_apps/prediction_cohorts/hospitalization_mortality.py +81 -0
  96. cehrbert/spark_apps/prediction_cohorts/t2dm_hf_cohort.py +18 -0
  97. cehrbert/spark_apps/spark_parse_args.py +350 -0
  98. cehrbert/spark_apps/sql_templates.py +42 -0
  99. cehrbert/tools/__init__.py +0 -0
  100. cehrbert/tools/download_omop_tables.py +131 -0
  101. cehrbert/trainers/__init__.py +0 -0
  102. cehrbert/trainers/model_trainer.py +308 -0
  103. cehrbert/trainers/train_cehr_bert.py +181 -0
  104. cehrbert/utils/__init__.py +0 -0
  105. cehrbert/utils/checkpoint_utils.py +198 -0
  106. cehrbert/utils/logging_utils.py +16 -0
  107. cehrbert/utils/model_utils.py +366 -0
  108. cehrbert/utils/spark_utils.py +1404 -0
  109. cehrbert-1.1.0.dist-info/LICENSE +21 -0
  110. cehrbert-1.1.0.dist-info/METADATA +217 -0
  111. cehrbert-1.1.0.dist-info/RECORD +114 -0
  112. cehrbert-1.1.0.dist-info/WHEEL +5 -0
  113. cehrbert-1.1.0.dist-info/entry_points.txt +3 -0
  114. cehrbert-1.1.0.dist-info/top_level.txt +1 -0
cehrbert/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ """This is the main module of the ACES package.
2
+
3
+ It contains the main functions and classes needed to extract cohorts.
4
+ """
5
+
6
+ from importlib.metadata import PackageNotFoundError, version
7
+
8
+ __package_name__ = "cehrbert"
9
+ try:
10
+ __version__ = version(__package_name__)
11
+ except PackageNotFoundError:
12
+ __version__ = "unknown"
File without changes
@@ -0,0 +1,13 @@
1
+ from typing import List, NamedTuple
2
+
3
+ LEARNING_RATE = "LEARNING_RATE"
4
+ LSTM_DIRECTION = "LSTM_DIRECTION"
5
+ LSTM_UNIT = "LSTM_UNIT"
6
+
7
+
8
+ class GridSearchConfig(NamedTuple):
9
+ """A data class for storing the row from the pandas data frame and the indexes for slicing the."""
10
+
11
+ learning_rates: List[float] = [1.0e-4]
12
+ lstm_directions: List[bool] = [True]
13
+ lstm_units: List[int] = [128]
@@ -0,0 +1,9 @@
1
+ PARQUET_DATA_PATH = "patient_sequence"
2
+ QUALIFIED_CONCEPT_LIST_PATH = "qualified_concept_list"
3
+ TIME_ATTENTION_MODEL_PATH = "time_aware_model.h5"
4
+ BERT_MODEL_VALIDATION_PATH = "bert_model.h5"
5
+ MORTALITY_DATA_PATH = "mortality"
6
+ HEART_FAILURE_DATA_PATH = "heart_failure"
7
+ HOSPITALIZATION_DATA_PATH = "hospitalization"
8
+ INFORMATION_CONTENT_DATA_PATH = "information_content"
9
+ CONCEPT_SIMILARITY_PATH = "concept_similarity"
File without changes
@@ -0,0 +1,28 @@
1
+ PERSON = "person"
2
+ VISIT_OCCURRENCE = "visit_occurrence"
3
+ CONDITION_OCCURRENCE = "condition_occurrence"
4
+ PROCEDURE_OCCURRENCE = "procedure_occurrence"
5
+ DRUG_EXPOSURE = "drug_exposure"
6
+ DEVICE_EXPOSURE = "device_exposure"
7
+ OBSERVATION = "observation"
8
+ MEASUREMENT = "measurement"
9
+ CATEGORICAL_MEASUREMENT = "categorical_measurement"
10
+ OBSERVATION_PERIOD = "observation_period"
11
+ DEATH = "death"
12
+ CDM_TABLES = [
13
+ PERSON,
14
+ VISIT_OCCURRENCE,
15
+ CONDITION_OCCURRENCE,
16
+ PROCEDURE_OCCURRENCE,
17
+ DRUG_EXPOSURE,
18
+ DEVICE_EXPOSURE,
19
+ OBSERVATION,
20
+ MEASUREMENT,
21
+ CATEGORICAL_MEASUREMENT,
22
+ OBSERVATION_PERIOD,
23
+ DEATH,
24
+ ]
25
+ REQUIRED_MEASUREMENT = "required_measurement"
26
+ UNKNOWN_CONCEPT = "[UNKNOWN]"
27
+ CONCEPT = "concept"
28
+ CONCEPT_ANCESTOR = "concept_ancestor"
File without changes
@@ -0,0 +1,33 @@
1
+ from enum import Enum
2
+ from typing import NamedTuple, Tuple
3
+
4
+
5
+ class RecordStatus(Enum):
6
+ """
7
+ COMPLETE indicates the record contains the entire history of a patient, therefore we should add [START] and [END].
8
+
9
+ tokens to the patient history. RIGHT_TRUNCATION indicates that we employ the right truncation of the patient
10
+ history for long sequences. This means that we should not add the [END] token to the end of the record because
11
+ this partial history is not supposed to end. TRUNCATION indicates that the record is a slice of the patient
12
+ history, we should not add [START] token and [END] token to such a sequence because this partial history got
13
+ truncated on both ends.
14
+ """
15
+
16
+ COMPLETE = 1
17
+ RIGHT_TRUNCATION = 2
18
+ TRUNCATION = 3
19
+
20
+
21
+ class RowSlicer(NamedTuple):
22
+ """A data class for storing the row from the pandas data frame and the indexes for slicing the."""
23
+
24
+ row: Tuple
25
+ start_index: int
26
+ end_index: int
27
+ target_index: int = 0
28
+ record_status: RecordStatus = RecordStatus.COMPLETE
29
+
30
+
31
+ class TokenizeFieldInfo(NamedTuple):
32
+ column_name: str
33
+ tokenized_column_name: str = None
@@ -0,0 +1,470 @@
1
+ import inspect
2
+ import logging
3
+ import random
4
+ from abc import ABC, abstractmethod
5
+ from collections import ChainMap
6
+ from itertools import chain, islice
7
+ from typing import List, Set
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ from .data_classes import RowSlicer
13
+ from .learning_objective import (
14
+ BertFineTuningLearningObjective,
15
+ DemographicsLearningObjective,
16
+ HierarchicalArtificialTokenPredictionLearningObjective,
17
+ HierarchicalMaskedLanguageModelLearningObjective,
18
+ HierarchicalProlongedLengthStayLearningObjective,
19
+ HierarchicalReadmissionLearningObjective,
20
+ HierarchicalVisitTypePredictionLearningObjective,
21
+ LearningObjective,
22
+ MaskedLanguageModelLearningObjective,
23
+ ProlongedLengthStayLearningObjective,
24
+ TimeAttentionLearningObjective,
25
+ VisitPredictionLearningObjective,
26
+ )
27
+ from .tokenizer import ConceptTokenizer
28
+
29
+
30
+ def create_indexes_by_time_window(dates, cursor, max_seq_len, time_window_size):
31
+ """
32
+ Extract the start_index and end_index used for slicing the sequences e.g. concept_ids and dates.
33
+
34
+ :param dates: a list of time stamps associated with the context
35
+ :param cursor: the current index used as the center for slicing the sequence
36
+ :param max_seq_len: the maximum sequence length
37
+ :param time_window_size: the maximum time window allowed
38
+ :return: start_index and end_index
39
+ """
40
+ seq_len = len(dates)
41
+ half_context_window_size = int(max_seq_len / 2)
42
+ start_index = max(0, cursor - half_context_window_size)
43
+ end_index = min(cursor + half_context_window_size, seq_len)
44
+
45
+ half_time_window_size = int(time_window_size / 2)
46
+ context_dates = dates[start_index:end_index]
47
+ time_deltas = context_dates - dates[cursor]
48
+ context_indexes = np.squeeze(
49
+ np.argwhere((time_deltas >= -half_time_window_size) & (time_deltas <= half_time_window_size)),
50
+ axis=-1,
51
+ )
52
+
53
+ return np.min(context_indexes).item(), np.max(context_indexes).item()
54
+
55
+
56
+ def get_required_params(clazz: LearningObjective):
57
+ """
58
+ Get required parameters for the learning objective class.
59
+
60
+ :param clazz:
61
+ :return:
62
+ """
63
+ params = inspect.signature(clazz).parameters
64
+ return [dict(name=name, required=param.default is inspect.Parameter.empty) for name, param in params.items()]
65
+
66
+
67
+ class AbstractDataGeneratorBase(ABC):
68
+ default_min_num_of_concepts = 2
69
+ default_required_column = "concept_ids"
70
+
71
+ def __init__(
72
+ self,
73
+ training_data: pd.DataFrame,
74
+ batch_size: int,
75
+ max_seq_len: int,
76
+ min_num_of_concepts: int,
77
+ is_random_cursor: bool = False,
78
+ is_pretraining: bool = True,
79
+ num_steps: int = None,
80
+ *args,
81
+ **kwargs,
82
+ ):
83
+
84
+ self._training_data = training_data
85
+ self._batch_size = batch_size
86
+ self._max_seq_len = max_seq_len
87
+ self._min_num_of_concepts = min_num_of_concepts
88
+ self._is_random_cursor = is_random_cursor
89
+ self._is_pretraining = is_pretraining
90
+ self._num_steps = num_steps
91
+
92
+ self.get_logger().info(
93
+ f"batch_size: {batch_size}\n"
94
+ f"max_seq_len: {max_seq_len}\n"
95
+ f"min_num_of_concepts: {min_num_of_concepts}\n"
96
+ f"is_random_cursor: {is_random_cursor}\n"
97
+ f"is_pretraining: {is_pretraining}\n"
98
+ f"num_of_steps: {num_steps}\n"
99
+ )
100
+
101
+ self._learning_objectives = self._initialize_learning_objectives(
102
+ max_seq_len=max_seq_len, is_pretraining=is_pretraining, **kwargs
103
+ )
104
+ # validate the required columns in the training data
105
+ self._validate_data_frame_columns()
106
+ self._clean_dataframe()
107
+
108
+ @abstractmethod
109
+ def _get_learning_objective_classes(self) -> List[LearningObjective]:
110
+ """
111
+ Initialize a list of LearningObjectives used for generating the input and and output.
112
+
113
+ :return:
114
+ """
115
+
116
+ def _initialize_learning_objectives(self, **kwargs) -> List[LearningObjective]:
117
+ """
118
+ Initialize a list of LearningObjectives used for generating the input and and output.
119
+
120
+ :return:
121
+ """
122
+
123
+ def _initialize(learning_objective) -> LearningObjective:
124
+ """
125
+ Initialize one LearningObjective using the provided keyword arguments.
126
+
127
+ from the parent method
128
+
129
+ :param learning_objective:
130
+ :return:
131
+ """
132
+ learning_object_input = dict()
133
+ params = get_required_params(learning_objective)
134
+ for required_param in [param["name"] for param in params if param["required"]]:
135
+ if required_param in kwargs:
136
+ learning_object_input[required_param] = kwargs[required_param]
137
+ return learning_objective(**learning_object_input)
138
+
139
+ return list(map(_initialize, self._get_learning_objective_classes()))
140
+
141
+ def _validate_data_frame_columns(self):
142
+ """
143
+ Validate if the training data has all required columns.
144
+
145
+ :return:
146
+ """
147
+ dataframe_columns = self._training_data.columns.tolist()
148
+ for required_column in self._get_required_columns():
149
+ if not required_column in dataframe_columns:
150
+ raise ValueError(f"The required column {required_column} does not exist in the training data")
151
+
152
+ @abstractmethod
153
+ def _clean_dataframe(self):
154
+ """
155
+ Clean the input data (_training_data) e.g. remove rows whose sequence length is less than.
156
+
157
+ _minimum_num_of_concepts.
158
+
159
+ Overload this method in the subclasses to overwrite the default behavior
160
+
161
+ :return:
162
+ """
163
+
164
+ def create_batch_generator(self):
165
+ """
166
+ Create the batch generator for tf.dataset.from_generator to use.
167
+
168
+ :return:
169
+ """
170
+ while True:
171
+ # Get a new iterator
172
+ iterator = self._create_iterator()
173
+ # Slice out a batch of data for every step
174
+ try:
175
+ for _ in range(self.get_steps_per_epoch()):
176
+ rows = list(islice(iterator, self._batch_size))
177
+ input_dicts = []
178
+ output_dicts = []
179
+ for learning_objective in self._learning_objectives:
180
+ input_dict, output_dict = learning_objective.process_batch(list(rows))
181
+ input_dicts.append(input_dict)
182
+ output_dicts.append(output_dict)
183
+ yield dict(ChainMap(*input_dicts)), dict(ChainMap(*output_dicts))
184
+ except (RuntimeError, ValueError) as e:
185
+ print(f"Error caught: {e}")
186
+
187
+ # Break out of the infinite loop in the non pretraining mode
188
+ if not self._is_pretraining:
189
+ break
190
+
191
+ def set_learning_objectives(self, learning_objectives: List[LearningObjective]):
192
+ """
193
+ Overwrite the default learning objectives.
194
+
195
+ :param learning_objectives:
196
+ :return:
197
+ """
198
+ self._learning_objectives = learning_objectives
199
+
200
+ @abstractmethod
201
+ def _create_iterator(self) -> RowSlicer:
202
+ pass
203
+
204
+ @abstractmethod
205
+ def get_data_size(self):
206
+ pass
207
+
208
+ def get_steps_per_epoch(self):
209
+ """
210
+ Calculate the number of steps required for one epoch to complete.
211
+
212
+ Floor division + 1 if there is any modulo value
213
+ :return:
214
+ """
215
+ num_of_steps = self.get_data_size() // self._batch_size + bool(self.get_data_size() % self._batch_size)
216
+
217
+ if self._num_steps:
218
+ return min(self._num_steps, num_of_steps)
219
+
220
+ return num_of_steps
221
+
222
+ def _get_required_columns(self) -> Set[str]:
223
+ """
224
+ Combine lists of required columns from multiple learning objectives into a unique set of.
225
+
226
+ required columns
227
+
228
+ :return:
229
+ """
230
+ learning_objective_required_columns = list(
231
+ chain(*[learning_objective.get_required_columns() for learning_objective in self._learning_objectives])
232
+ )
233
+ return set(learning_objective_required_columns + [self.default_required_column])
234
+
235
+ def get_tf_dataset_schema(self):
236
+ """
237
+ Combine the input and output tensorflow data schema from multiple learning objectives.
238
+
239
+ :return:
240
+ """
241
+ input_dict_schemas = []
242
+ output_dict_schemas = []
243
+ for learning_objective in self._learning_objectives:
244
+ input_dict_schema, output_dict_schema = learning_objective.get_tf_dataset_schema()
245
+ input_dict_schemas.append(input_dict_schema)
246
+ output_dict_schemas.append(output_dict_schema)
247
+ return dict(ChainMap(*input_dict_schemas)), dict(ChainMap(*output_dict_schemas))
248
+
249
+ @classmethod
250
+ def get_logger(cls):
251
+ return logging.getLogger(cls.__name__)
252
+
253
+
254
+ class BertDataGenerator(AbstractDataGeneratorBase):
255
+
256
+ def __init__(self, concept_tokenizer: ConceptTokenizer, *args, **kwargs):
257
+ super(BertDataGenerator, self).__init__(concept_tokenizer=concept_tokenizer, *args, **kwargs)
258
+ self._concept_tokenizer = concept_tokenizer
259
+
260
+ def _clean_dataframe(self):
261
+ self._training_data = self._training_data[
262
+ self._training_data[self.default_required_column].apply(len)
263
+ >= max(self.default_min_num_of_concepts, self._min_num_of_concepts)
264
+ ]
265
+
266
+ def _get_learning_objective_classes(self):
267
+ return [MaskedLanguageModelLearningObjective]
268
+
269
+ def _create_iterator(self):
270
+ """
271
+ Create an iterator that will iterate through all training data.
272
+
273
+ :return:
274
+ """
275
+ for row in self._training_data.sample(frac=1).itertuples():
276
+ seq_length = len(row.token_ids)
277
+ if self._is_pretraining:
278
+ cursor = (
279
+ random.randint(0, seq_length - 1)
280
+ if self._is_random_cursor & (seq_length > self._max_seq_len)
281
+ else seq_length // 2
282
+ )
283
+
284
+ half_window_size = int(self._max_seq_len / 2)
285
+ start_index = max(0, cursor - half_window_size)
286
+ end_index = min(cursor + half_window_size, seq_length)
287
+
288
+ if start_index < end_index:
289
+ yield RowSlicer(row, start_index, end_index)
290
+ else:
291
+ yield RowSlicer(row, 0, seq_length)
292
+
293
+ def get_data_size(self):
294
+ return len(self._training_data)
295
+
296
+
297
+ class BertVisitPredictionDataGenerator(BertDataGenerator):
298
+ def __init__(self, visit_tokenizer: ConceptTokenizer, *args, **kwargs):
299
+ super(BertDataGenerator, self).__init__(visit_tokenizer=visit_tokenizer, *args, **kwargs)
300
+ self._visit_tokenizer = visit_tokenizer
301
+
302
+ def _get_learning_objective_classes(self):
303
+ return [MaskedLanguageModelLearningObjective, VisitPredictionLearningObjective]
304
+
305
+
306
+ class HierarchicalBertDataGenerator(AbstractDataGeneratorBase):
307
+ def __init__(
308
+ self,
309
+ concept_tokenizer: ConceptTokenizer,
310
+ visit_tokenizer: ConceptTokenizer,
311
+ max_num_of_visits: int,
312
+ max_num_of_concepts: int,
313
+ include_att_prediction: bool,
314
+ include_visit_prediction: bool,
315
+ *args,
316
+ min_num_of_concepts: int = 5,
317
+ min_num_of_visits: int = 2,
318
+ **kwargs,
319
+ ):
320
+
321
+ # The num of visits
322
+ self._min_num_of_visits = min_num_of_visits
323
+ self._max_num_of_visits = max_num_of_visits
324
+ self._max_num_of_concepts = max_num_of_concepts
325
+
326
+ super().__init__(
327
+ concept_tokenizer=concept_tokenizer,
328
+ visit_tokenizer=visit_tokenizer,
329
+ max_num_of_visits=max_num_of_visits,
330
+ max_num_of_concepts=max_num_of_concepts,
331
+ max_seq_len=max_num_of_visits * max_num_of_concepts,
332
+ min_num_of_concepts=min_num_of_concepts,
333
+ include_att_prediction=include_att_prediction,
334
+ include_visit_prediction=include_visit_prediction,
335
+ *args,
336
+ **kwargs,
337
+ )
338
+
339
+ def _clean_dataframe(self):
340
+ """
341
+ Remove the patients that don't have enough concepts to qualify.
342
+
343
+ :return:
344
+ """
345
+ min_num_of_concepts = max(self.default_min_num_of_concepts, self._min_num_of_concepts)
346
+ criteria = (self._training_data["num_of_concepts"] >= min_num_of_concepts) & (
347
+ self._training_data["num_of_visits"] >= self._min_num_of_visits
348
+ )
349
+ self._training_data = self._training_data[criteria]
350
+
351
+ def _get_learning_objective_classes(self):
352
+ return [
353
+ HierarchicalMaskedLanguageModelLearningObjective,
354
+ HierarchicalArtificialTokenPredictionLearningObjective,
355
+ HierarchicalVisitTypePredictionLearningObjective,
356
+ ]
357
+
358
+ def _create_iterator(self):
359
+ """
360
+ Create an iterator that will iterate through all training example.
361
+
362
+ :return:
363
+ """
364
+ for row in self._training_data.itertuples():
365
+
366
+ if self._is_pretraining:
367
+ if self._max_num_of_visits >= row.num_of_visits:
368
+ start_index = 0
369
+ end_index = row.num_of_visits
370
+ else:
371
+ start_index = random.randint(0, row.num_of_visits - self._max_num_of_visits)
372
+ end_index = start_index + self._max_num_of_visits
373
+
374
+ assert start_index < end_index
375
+ yield RowSlicer(row, start_index, end_index)
376
+
377
+ else:
378
+ # Return the entire patient history
379
+ yield RowSlicer(row, 0, row.num_of_visits)
380
+
381
+ def get_data_size(self):
382
+ return len(self._training_data)
383
+
384
+
385
+ class HierarchicalBertMultiTaskDataGenerator(HierarchicalBertDataGenerator):
386
+ def __init__(
387
+ self,
388
+ include_readmission: bool,
389
+ include_prolonged_length_stay: bool,
390
+ *args,
391
+ **kwargs,
392
+ ):
393
+ self._include_readmission = include_readmission
394
+ self._include_prolonged_length_stay = include_prolonged_length_stay
395
+ super().__init__(*args, **kwargs)
396
+
397
+ def _get_learning_objective_classes(self):
398
+
399
+ learning_objectives = [
400
+ HierarchicalMaskedLanguageModelLearningObjective,
401
+ HierarchicalArtificialTokenPredictionLearningObjective,
402
+ HierarchicalVisitTypePredictionLearningObjective,
403
+ ]
404
+
405
+ if self._include_readmission:
406
+ learning_objectives.append(HierarchicalReadmissionLearningObjective)
407
+
408
+ if self._include_prolonged_length_stay:
409
+ learning_objectives.append(HierarchicalProlongedLengthStayLearningObjective)
410
+
411
+ return learning_objectives
412
+
413
+
414
+ class MedBertDataGenerator(BertDataGenerator):
415
+ def _get_learning_objective_classes(self):
416
+ return [
417
+ MaskedLanguageModelLearningObjective,
418
+ ProlongedLengthStayLearningObjective,
419
+ ]
420
+
421
+
422
+ class TimeAttentionDataGenerator(AbstractDataGeneratorBase):
423
+ def __init__(
424
+ self,
425
+ concept_tokenizer: ConceptTokenizer,
426
+ time_window_size: int,
427
+ *args,
428
+ **kwargs,
429
+ ):
430
+ super(TimeAttentionDataGenerator, self).__init__(
431
+ concept_tokenizer=concept_tokenizer,
432
+ time_window_size=time_window_size,
433
+ *args,
434
+ **kwargs,
435
+ )
436
+ self._concept_tokenizer = concept_tokenizer
437
+ self._time_window_size = time_window_size
438
+
439
+ def _get_learning_objective_classes(self):
440
+ return [TimeAttentionLearningObjective]
441
+
442
+ def _create_iterator(self):
443
+ """
444
+ Create an iterator that will iterate forever.
445
+
446
+ :return:
447
+ """
448
+ while True:
449
+ for row in self._training_data.itertuples():
450
+ concept_ids, dates = zip(*sorted(zip(row.token_ids, row.dates), key=lambda tup2: tup2[1]))
451
+ for i in range(len(concept_ids)):
452
+ # Only include the concepts whose time stamps are within -half_time_window and
453
+ # half_time_window from the target time stamp
454
+ start_index, end_index = create_indexes_by_time_window(
455
+ dates, i, self._max_seq_len, self._time_window_size
456
+ )
457
+ if start_index < end_index:
458
+ yield RowSlicer(row, start_index, end_index, i)
459
+
460
+ def get_data_size(self):
461
+ return len(self._training_data.token_ids.explode())
462
+
463
+
464
+ class FineTuningHierarchicalBertDataGenerator(HierarchicalBertDataGenerator):
465
+ def _get_learning_objective_classes(self):
466
+ return [
467
+ HierarchicalMaskedLanguageModelLearningObjective,
468
+ DemographicsLearningObjective,
469
+ BertFineTuningLearningObjective,
470
+ ]
@@ -0,0 +1,75 @@
1
+ import random
2
+ from abc import ABC
3
+ from enum import Enum
4
+
5
+ import networkx as nx
6
+ import pandas as pd
7
+
8
+
9
+ class SimilarityType(Enum):
10
+ SEMANTIC_SIMILARITY = "semantic_similarity"
11
+ MICA_INFORMATION_CONTENT = "mica_information_content"
12
+ LIN_MEASURE = "lin_measure"
13
+ JIANG_MEASURE = "jiang_measure"
14
+ INFORMATION_COEFFICIENT = "information_coefficient"
15
+ RELEVANCE_MEASURE = "relevance_measure"
16
+ GRAPH_IC_MEASURE = "graph_ic_measure"
17
+ NONE = "none"
18
+
19
+
20
+ class GraphSampler(ABC):
21
+ # TODO: Weighted similarity to increase the sampling the local neighbors using logit
22
+ def __init__(self, concept_similarity_path: str, concept_similarity_type: str):
23
+ self._concept_similarity_type = concept_similarity_type
24
+ self._concept_dict, self._similarity_dict = self._init_similarity(
25
+ concept_similarity_type=concept_similarity_type,
26
+ concept_similarity_path=concept_similarity_path,
27
+ )
28
+
29
+ def _is_sampling_enabled(self):
30
+ """
31
+ Check whether the graph sampling is enabled.
32
+
33
+ :return:
34
+ """
35
+ return self._concept_similarity_type != SimilarityType.NONE.value
36
+
37
+ def _init_similarity(self, concept_similarity_type: str, concept_similarity_path: str):
38
+ concept_dict = {}
39
+ similarity_dict = {}
40
+
41
+ # Check whether we want to use similarity type
42
+ if self._is_sampling_enabled():
43
+ similarity_table = pd.read_parquet(concept_similarity_path)
44
+ graph = nx.from_pandas_edgelist(
45
+ similarity_table,
46
+ source="concept_id_1",
47
+ target="concept_id_2",
48
+ edge_attr=concept_similarity_type,
49
+ )
50
+
51
+ for source in graph.nodes():
52
+ # Convert target and source to str types because tokenizer expects string type
53
+ concept_list, similarity_list = zip(
54
+ *[(str(target), val[concept_similarity_type]) for _, target, val in graph.edges(source, data=True)]
55
+ )
56
+ # Convert all concept_ids to string type
57
+ concept_dict[str(source)] = list(map(str, concept_list))
58
+ similarity_dict[str(source)] = similarity_list
59
+
60
+ return concept_dict, similarity_dict
61
+
62
+ def sample_graph(self, concept_id):
63
+ # sample the concept from the probability distribution in the graph and generate one
64
+ if self._is_sampling_enabled() and concept_id in self._concept_dict:
65
+ # This actually returns a list
66
+ random_choice = random.choices(
67
+ population=self._concept_dict[concept_id],
68
+ weights=self._similarity_dict[concept_id],
69
+ k=1,
70
+ )
71
+ # In case the choice is none, we return itself as the default value
72
+ return next(iter(random_choice), concept_id)
73
+
74
+ # If the concept is an orphan, simply return it
75
+ return concept_id
File without changes