|
a |
|
b/task/NextXVisit.ipynb |
|
|
1 |
{ |
|
|
2 |
"cells": [ |
|
|
3 |
{ |
|
|
4 |
"cell_type": "code", |
|
|
5 |
"execution_count": null, |
|
|
6 |
"metadata": {}, |
|
|
7 |
"outputs": [], |
|
|
8 |
"source": [ |
|
|
9 |
"import sys \n", |
|
|
10 |
"sys.path.insert(0, '../')" |
|
|
11 |
] |
|
|
12 |
}, |
|
|
13 |
{ |
|
|
14 |
"cell_type": "code", |
|
|
15 |
"execution_count": null, |
|
|
16 |
"metadata": {}, |
|
|
17 |
"outputs": [], |
|
|
18 |
"source": [ |
|
|
19 |
"from torch.utils.data import DataLoader\n", |
|
|
20 |
"import pandas as pd\n", |
|
|
21 |
"from common.common import create_folder,H5Recorder\n", |
|
|
22 |
"import numpy as np\n", |
|
|
23 |
"from torch.utils.data.dataset import Dataset\n", |
|
|
24 |
"import os\n", |
|
|
25 |
"import torch\n", |
|
|
26 |
"import torch.nn as nn\n", |
|
|
27 |
"import pytorch_pretrained_bert as Bert\n", |
|
|
28 |
"\n", |
|
|
29 |
"from model import optimiser\n", |
|
|
30 |
"import sklearn.metrics as skm\n", |
|
|
31 |
"import math\n", |
|
|
32 |
"from torch.utils.data.dataset import Dataset\n", |
|
|
33 |
"import random\n", |
|
|
34 |
"import numpy as np\n", |
|
|
35 |
"import torch\n", |
|
|
36 |
"import time\n", |
|
|
37 |
"from sklearn.metrics import roc_auc_score\n", |
|
|
38 |
"from common.common import load_obj\n", |
|
|
39 |
"from model.utils import age_vocab\n", |
|
|
40 |
"from dataLoader.NextXVisit import NextVisit\n", |
|
|
41 |
"from model.NextXVisit import BertForMultiLabelPrediction\n", |
|
|
42 |
"import warnings\n", |
|
|
43 |
"warnings.filterwarnings(action='ignore')" |
|
|
44 |
] |
|
|
45 |
}, |
|
|
46 |
{ |
|
|
47 |
"cell_type": "code", |
|
|
48 |
"execution_count": null, |
|
|
49 |
"metadata": {}, |
|
|
50 |
"outputs": [], |
|
|
51 |
"source": [ |
|
|
52 |
"file_config = {\n", |
|
|
53 |
" 'vocab': '', # token2idx idx2token\n", |
|
|
54 |
" 'train': '',\n", |
|
|
55 |
" 'test': '',\n", |
|
|
56 |
"}\n", |
|
|
57 |
"\n", |
|
|
58 |
"optim_config = {\n", |
|
|
59 |
" 'lr': 3e-5,\n", |
|
|
60 |
" 'warmup_proportion': 0.1,\n", |
|
|
61 |
" 'weight_decay': 0.01\n", |
|
|
62 |
"}\n", |
|
|
63 |
"\n", |
|
|
64 |
"global_params = {\n", |
|
|
65 |
" 'batch_size': 256,\n", |
|
|
66 |
" 'gradient_accumulation_steps': 1,\n", |
|
|
67 |
" 'device': 'cuda:0',\n", |
|
|
68 |
" 'output_dir': '', # output folder\n", |
|
|
69 |
" 'best_name': '', # output model name\n", |
|
|
70 |
" 'max_len_seq': 100,\n", |
|
|
71 |
" 'max_age': 110,\n", |
|
|
72 |
" 'age_year': False,\n", |
|
|
73 |
" 'age_symbol': None,\n", |
|
|
74 |
" 'min_visit': 5\n", |
|
|
75 |
"}\n", |
|
|
76 |
"\n", |
|
|
77 |
"pretrain_model_path = '' # pretrained MLM path" |
|
|
78 |
] |
|
|
79 |
}, |
|
|
80 |
{ |
|
|
81 |
"cell_type": "code", |
|
|
82 |
"execution_count": null, |
|
|
83 |
"metadata": {}, |
|
|
84 |
"outputs": [], |
|
|
85 |
"source": [ |
|
|
86 |
"BertVocab = load_obj(file_config['vocab'])\n", |
|
|
87 |
"ageVocab, _ = age_vocab(max_age=global_params['max_age'], symbol=global_params['age_symbol'])" |
|
|
88 |
] |
|
|
89 |
}, |
|
|
90 |
{ |
|
|
91 |
"cell_type": "code", |
|
|
92 |
"execution_count": null, |
|
|
93 |
"metadata": {}, |
|
|
94 |
"outputs": [], |
|
|
95 |
"source": [ |
|
|
96 |
"# re-format label token\n", |
|
|
97 |
"def format_label_vocab(token2idx):\n", |
|
|
98 |
" token2idx = token2idx.copy()\n", |
|
|
99 |
" del token2idx['PAD']\n", |
|
|
100 |
" del token2idx['SEP']\n", |
|
|
101 |
" del token2idx['CLS']\n", |
|
|
102 |
" del token2idx['MASK']\n", |
|
|
103 |
" token = list(token2idx.keys())\n", |
|
|
104 |
" labelVocab = {}\n", |
|
|
105 |
" for i,x in enumerate(token):\n", |
|
|
106 |
" labelVocab[x] = i\n", |
|
|
107 |
" return labelVocab\n", |
|
|
108 |
"\n", |
|
|
109 |
"labelVocab = format_label_vocab(BertVocab['token2idx'])" |
|
|
110 |
] |
|
|
111 |
}, |
|
|
112 |
{ |
|
|
113 |
"cell_type": "code", |
|
|
114 |
"execution_count": null, |
|
|
115 |
"metadata": {}, |
|
|
116 |
"outputs": [], |
|
|
117 |
"source": [ |
|
|
118 |
"model_config = {\n", |
|
|
119 |
" 'vocab_size': len(BertVocab['token2idx'].keys()), # number of disease + symbols for word embedding\n", |
|
|
120 |
" 'hidden_size': 288, # word embedding and seg embedding hidden size\n", |
|
|
121 |
" 'seg_vocab_size': 2, # number of vocab for seg embedding\n", |
|
|
122 |
" 'age_vocab_size': len(ageVocab.keys()), # number of vocab for age embedding\n", |
|
|
123 |
" 'max_position_embedding': global_params['max_len_seq'], # maximum number of tokens\n", |
|
|
124 |
" 'hidden_dropout_prob': 0.1, # dropout rate\n", |
|
|
125 |
" 'num_hidden_layers': 6, # number of multi-head attention layers required\n", |
|
|
126 |
" 'num_attention_heads': 12, # number of attention heads\n", |
|
|
127 |
" 'attention_probs_dropout_prob': 0.1, # multi-head attention dropout rate\n", |
|
|
128 |
" 'intermediate_size': 512, # the size of the \"intermediate\" layer in the transformer encoder\n", |
|
|
129 |
" 'hidden_act': 'gelu', # The non-linear activation function in the encoder and the pooler \"gelu\", 'relu', 'swish' are supported\n", |
|
|
130 |
" 'initializer_range': 0.02, # parameter weight initializer range\n", |
|
|
131 |
"}\n", |
|
|
132 |
"\n", |
|
|
133 |
"feature_dict = {\n", |
|
|
134 |
" 'word':True,\n", |
|
|
135 |
" 'seg':True,\n", |
|
|
136 |
" 'age':True,\n", |
|
|
137 |
" 'position': True\n", |
|
|
138 |
"}" |
|
|
139 |
] |
|
|
140 |
}, |
|
|
141 |
{ |
|
|
142 |
"cell_type": "code", |
|
|
143 |
"execution_count": null, |
|
|
144 |
"metadata": {}, |
|
|
145 |
"outputs": [], |
|
|
146 |
"source": [ |
|
|
147 |
"class BertConfig(Bert.modeling.BertConfig):\n", |
|
|
148 |
" def __init__(self, config):\n", |
|
|
149 |
" super(BertConfig, self).__init__(\n", |
|
|
150 |
" vocab_size_or_config_json_file=config.get('vocab_size'),\n", |
|
|
151 |
" hidden_size=config['hidden_size'],\n", |
|
|
152 |
" num_hidden_layers=config.get('num_hidden_layers'),\n", |
|
|
153 |
" num_attention_heads=config.get('num_attention_heads'),\n", |
|
|
154 |
" intermediate_size=config.get('intermediate_size'),\n", |
|
|
155 |
" hidden_act=config.get('hidden_act'),\n", |
|
|
156 |
" hidden_dropout_prob=config.get('hidden_dropout_prob'),\n", |
|
|
157 |
" attention_probs_dropout_prob=config.get('attention_probs_dropout_prob'),\n", |
|
|
158 |
" max_position_embeddings = config.get('max_position_embedding'),\n", |
|
|
159 |
" initializer_range=config.get('initializer_range'),\n", |
|
|
160 |
" )\n", |
|
|
161 |
" self.seg_vocab_size = config.get('seg_vocab_size')\n", |
|
|
162 |
" self.age_vocab_size = config.get('age_vocab_size')" |
|
|
163 |
] |
|
|
164 |
}, |
|
|
165 |
{ |
|
|
166 |
"cell_type": "code", |
|
|
167 |
"execution_count": null, |
|
|
168 |
"metadata": {}, |
|
|
169 |
"outputs": [], |
|
|
170 |
"source": [ |
|
|
171 |
"train = pd.read_parquet(file_config['train'])\n", |
|
|
172 |
"Dset = NextVisit(token2idx=BertVocab['token2idx'], label2idx=labelVocab, age2idx=ageVocab, dataframe=train, max_len=global_params['max_len_seq'])\n", |
|
|
173 |
"trainload = DataLoader(dataset=Dset, batch_size=global_params['batch_size'], shuffle=True, num_workers=3)" |
|
|
174 |
] |
|
|
175 |
}, |
|
|
176 |
{ |
|
|
177 |
"cell_type": "code", |
|
|
178 |
"execution_count": null, |
|
|
179 |
"metadata": {}, |
|
|
180 |
"outputs": [], |
|
|
181 |
"source": [ |
|
|
182 |
"test = pd.read_parquet(file_config['test'])\n", |
|
|
183 |
"Dset = NextVisit(token2idx=BertVocab['token2idx'], label2idx=labelVocab, age2idx=ageVocab, dataframe=test, max_len=global_params['max_len_seq'])\n", |
|
|
184 |
"testload = DataLoader(dataset=Dset, batch_size=global_params['batch_size'], shuffle=False, num_workers=3)" |
|
|
185 |
] |
|
|
186 |
}, |
|
|
187 |
{ |
|
|
188 |
"cell_type": "code", |
|
|
189 |
"execution_count": null, |
|
|
190 |
"metadata": {}, |
|
|
191 |
"outputs": [], |
|
|
192 |
"source": [ |
|
|
193 |
"# del model\n", |
|
|
194 |
"conf = BertConfig(model_config)\n", |
|
|
195 |
"model = BertForMultiLabelPrediction(conf, num_labels=len(labelVocab.keys()), feature_dict=feature_dict)" |
|
|
196 |
] |
|
|
197 |
}, |
|
|
198 |
{ |
|
|
199 |
"cell_type": "code", |
|
|
200 |
"execution_count": null, |
|
|
201 |
"metadata": {}, |
|
|
202 |
"outputs": [], |
|
|
203 |
"source": [ |
|
|
204 |
"def load_model(path, model):\n", |
|
|
205 |
" # load pretrained model and update weights\n", |
|
|
206 |
" pretrained_dict = torch.load(path)\n", |
|
|
207 |
" model_dict = model.state_dict()\n", |
|
|
208 |
" # 1. filter out unnecessary keys\n", |
|
|
209 |
" pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}\n", |
|
|
210 |
" # 2. overwrite entries in the existing state dict\n", |
|
|
211 |
" model_dict.update(pretrained_dict)\n", |
|
|
212 |
" # 3. load the new state dict\n", |
|
|
213 |
" model.load_state_dict(model_dict)\n", |
|
|
214 |
" return model\n", |
|
|
215 |
"\n", |
|
|
216 |
"mode = load_model(pretrain_model_path, model)" |
|
|
217 |
] |
|
|
218 |
}, |
|
|
219 |
{ |
|
|
220 |
"cell_type": "code", |
|
|
221 |
"execution_count": null, |
|
|
222 |
"metadata": {}, |
|
|
223 |
"outputs": [], |
|
|
224 |
"source": [ |
|
|
225 |
"model = model.to(global_params['device'])\n", |
|
|
226 |
"optim = optimiser.adam(params=list(model.named_parameters()), config=optim_config)" |
|
|
227 |
] |
|
|
228 |
}, |
|
|
229 |
{ |
|
|
230 |
"cell_type": "code", |
|
|
231 |
"execution_count": null, |
|
|
232 |
"metadata": {}, |
|
|
233 |
"outputs": [], |
|
|
234 |
"source": [ |
|
|
235 |
"import sklearn\n", |
|
|
236 |
"def precision(logits, label):\n", |
|
|
237 |
" sig = nn.Sigmoid()\n", |
|
|
238 |
" output=sig(logits)\n", |
|
|
239 |
" label, output=label.cpu(), output.detach().cpu()\n", |
|
|
240 |
" tempprc= sklearn.metrics.average_precision_score(label.numpy(),output.numpy(), average='samples')\n", |
|
|
241 |
" return tempprc, output, label\n", |
|
|
242 |
"\n", |
|
|
243 |
"def precision_test(logits, label):\n", |
|
|
244 |
" sig = nn.Sigmoid()\n", |
|
|
245 |
" output=sig(logits)\n", |
|
|
246 |
" tempprc= sklearn.metrics.average_precision_score(label.numpy(),output.numpy(), average='samples')\n", |
|
|
247 |
" roc = sklearn.metrics.roc_auc_score(label.numpy(),output.numpy(), average='samples')\n", |
|
|
248 |
" return tempprc, roc, output, label," |
|
|
249 |
] |
|
|
250 |
}, |
|
|
251 |
{ |
|
|
252 |
"cell_type": "code", |
|
|
253 |
"execution_count": null, |
|
|
254 |
"metadata": {}, |
|
|
255 |
"outputs": [], |
|
|
256 |
"source": [ |
|
|
257 |
"from sklearn.preprocessing import MultiLabelBinarizer\n", |
|
|
258 |
"mlb = MultiLabelBinarizer(classes=list(labelVocab.values()))\n", |
|
|
259 |
"mlb.fit([[each] for each in list(labelVocab.values())])" |
|
|
260 |
] |
|
|
261 |
}, |
|
|
262 |
{ |
|
|
263 |
"cell_type": "code", |
|
|
264 |
"execution_count": null, |
|
|
265 |
"metadata": {}, |
|
|
266 |
"outputs": [], |
|
|
267 |
"source": [ |
|
|
268 |
"def train(e):\n", |
|
|
269 |
" model.train()\n", |
|
|
270 |
" tr_loss = 0\n", |
|
|
271 |
" temp_loss = 0\n", |
|
|
272 |
" nb_tr_examples, nb_tr_steps = 0, 0\n", |
|
|
273 |
" cnt = 0\n", |
|
|
274 |
" for step, batch in enumerate(trainload):\n", |
|
|
275 |
" cnt +=1\n", |
|
|
276 |
" age_ids, input_ids, posi_ids, segment_ids, attMask, targets, _ = batch\n", |
|
|
277 |
" \n", |
|
|
278 |
" targets = torch.tensor(mlb.transform(targets.numpy()), dtype=torch.float32)\n", |
|
|
279 |
"\n", |
|
|
280 |
" age_ids = age_ids.to(global_params['device'])\n", |
|
|
281 |
" input_ids = input_ids.to(global_params['device'])\n", |
|
|
282 |
" posi_ids = posi_ids.to(global_params['device'])\n", |
|
|
283 |
" segment_ids = segment_ids.to(global_params['device'])\n", |
|
|
284 |
" attMask = attMask.to(global_params['device'])\n", |
|
|
285 |
" targets = targets.to(global_params['device'])\n", |
|
|
286 |
" \n", |
|
|
287 |
" loss, logits = model(input_ids, age_ids, segment_ids, posi_ids,attention_mask=attMask, labels=targets)\n", |
|
|
288 |
" \n", |
|
|
289 |
" if global_params['gradient_accumulation_steps'] >1:\n", |
|
|
290 |
" loss = loss/global_params['gradient_accumulation_steps']\n", |
|
|
291 |
" loss.backward()\n", |
|
|
292 |
" \n", |
|
|
293 |
" temp_loss += loss.item()\n", |
|
|
294 |
" tr_loss += loss.item()\n", |
|
|
295 |
" nb_tr_examples += input_ids.size(0)\n", |
|
|
296 |
" nb_tr_steps += 1\n", |
|
|
297 |
" \n", |
|
|
298 |
" if step % 500==0:\n", |
|
|
299 |
" prec, a, b = precision(logits, targets)\n", |
|
|
300 |
" print(\"epoch: {}\\t| Cnt: {}\\t| Loss: {}\\t| precision: {}\".format(e, cnt,temp_loss/500, prec))\n", |
|
|
301 |
" temp_loss = 0\n", |
|
|
302 |
" \n", |
|
|
303 |
" if (step + 1) % global_params['gradient_accumulation_steps'] == 0:\n", |
|
|
304 |
" optim.step()\n", |
|
|
305 |
" optim.zero_grad()\n", |
|
|
306 |
"\n", |
|
|
307 |
"def evaluation():\n", |
|
|
308 |
" model.eval()\n", |
|
|
309 |
" y = []\n", |
|
|
310 |
" y_label = []\n", |
|
|
311 |
" tr_loss = 0\n", |
|
|
312 |
" for step, batch in enumerate(testload):\n", |
|
|
313 |
" model.eval()\n", |
|
|
314 |
" age_ids, input_ids, posi_ids, segment_ids, attMask, targets, _ = batch\n", |
|
|
315 |
" targets = torch.tensor(mlb.transform(targets.numpy()), dtype=torch.float32)\n", |
|
|
316 |
" \n", |
|
|
317 |
" age_ids = age_ids.to(global_params['device'])\n", |
|
|
318 |
" input_ids = input_ids.to(global_params['device'])\n", |
|
|
319 |
" posi_ids = posi_ids.to(global_params['device'])\n", |
|
|
320 |
" segment_ids = segment_ids.to(global_params['device'])\n", |
|
|
321 |
" attMask = attMask.to(global_params['device'])\n", |
|
|
322 |
" targets = targets.to(global_params['device'])\n", |
|
|
323 |
" \n", |
|
|
324 |
" with torch.no_grad():\n", |
|
|
325 |
" loss, logits = model(input_ids, age_ids, segment_ids, posi_ids,attention_mask=attMask, labels=targets)\n", |
|
|
326 |
" logits = logits.cpu()\n", |
|
|
327 |
" targets = targets.cpu()\n", |
|
|
328 |
" \n", |
|
|
329 |
" tr_loss += loss.item()\n", |
|
|
330 |
"\n", |
|
|
331 |
" y_label.append(targets)\n", |
|
|
332 |
" y.append(logits)\n", |
|
|
333 |
"\n", |
|
|
334 |
" y_label = torch.cat(y_label, dim=0)\n", |
|
|
335 |
" y = torch.cat(y, dim=0)\n", |
|
|
336 |
"\n", |
|
|
337 |
" aps, roc, output, label = precision_test(y, y_label)\n", |
|
|
338 |
" return aps, roc, tr_loss" |
|
|
339 |
] |
|
|
340 |
}, |
|
|
341 |
{ |
|
|
342 |
"cell_type": "code", |
|
|
343 |
"execution_count": null, |
|
|
344 |
"metadata": { |
|
|
345 |
"scrolled": false |
|
|
346 |
}, |
|
|
347 |
"outputs": [], |
|
|
348 |
"source": [ |
|
|
349 |
"best_pre = 0.0\n", |
|
|
350 |
"for e in range(50):\n", |
|
|
351 |
" train(e)\n", |
|
|
352 |
" aps, roc, test_loss = evaluation()\n", |
|
|
353 |
" if aps >best_pre:\n", |
|
|
354 |
" # Save a trained model\n", |
|
|
355 |
" print(\"** ** * Saving fine - tuned model ** ** * \")\n", |
|
|
356 |
" model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self\n", |
|
|
357 |
" output_model_file = os.path.join(global_params['output_dir'],global_params['best_name'])\n", |
|
|
358 |
" create_folder(global_params['output_dir'])\n", |
|
|
359 |
"\n", |
|
|
360 |
" torch.save(model_to_save.state_dict(), output_model_file)\n", |
|
|
361 |
" best_pre = aps\n", |
|
|
362 |
" print('aps : {}'.format(aps))" |
|
|
363 |
] |
|
|
364 |
} |
|
|
365 |
], |
|
|
366 |
"metadata": { |
|
|
367 |
"kernelspec": { |
|
|
368 |
"display_name": "Python 3", |
|
|
369 |
"language": "python", |
|
|
370 |
"name": "python3" |
|
|
371 |
}, |
|
|
372 |
"language_info": { |
|
|
373 |
"codemirror_mode": { |
|
|
374 |
"name": "ipython", |
|
|
375 |
"version": 3 |
|
|
376 |
}, |
|
|
377 |
"file_extension": ".py", |
|
|
378 |
"mimetype": "text/x-python", |
|
|
379 |
"name": "python", |
|
|
380 |
"nbconvert_exporter": "python", |
|
|
381 |
"pygments_lexer": "ipython3", |
|
|
382 |
"version": "3.7.4" |
|
|
383 |
} |
|
|
384 |
}, |
|
|
385 |
"nbformat": 4, |
|
|
386 |
"nbformat_minor": 2 |
|
|
387 |
} |