|
a |
|
b/dataLoader/NextXVisit.py |
|
|
1 |
import numpy as np |
|
|
2 |
from torch.utils.data.dataset import Dataset |
|
|
3 |
from dataLoader.utils import seq_padding,code2index, position_idx, index_seg |
|
|
4 |
import torch |
|
|
5 |
|
|
|
6 |
|
|
|
7 |
class NextVisit(Dataset): |
|
|
8 |
def __init__(self, token2idx, label2idx, age2idx, dataframe, max_len, code='code', age='age', label='label'): |
|
|
9 |
# dataframe preproecssing |
|
|
10 |
# filter out the patient with number of visits less than min_visit |
|
|
11 |
self.vocab = token2idx |
|
|
12 |
self.label_vocab = label2idx |
|
|
13 |
self.max_len = max_len |
|
|
14 |
self.code = dataframe[code] |
|
|
15 |
self.age = dataframe[age] |
|
|
16 |
self.label = dataframe[label] |
|
|
17 |
self.patid = dataframe.patid |
|
|
18 |
|
|
|
19 |
self.age2idx = age2idx |
|
|
20 |
|
|
|
21 |
def __getitem__(self, index): |
|
|
22 |
""" |
|
|
23 |
return: age, code, position, segmentation, mask, label |
|
|
24 |
""" |
|
|
25 |
# cut data |
|
|
26 |
age = self.age[index] |
|
|
27 |
code = self.code[index] |
|
|
28 |
label = self.label[index] |
|
|
29 |
patid = self.patid[index] |
|
|
30 |
|
|
|
31 |
# extract data |
|
|
32 |
age = age[(-self.max_len+1):] |
|
|
33 |
code = code[(-self.max_len+1):] |
|
|
34 |
|
|
|
35 |
# avoid data cut with first element to be 'SEP' |
|
|
36 |
if code[0] != 'SEP': |
|
|
37 |
code = np.append(np.array(['CLS']), code) |
|
|
38 |
age = np.append(np.array(age[0]), age) |
|
|
39 |
else: |
|
|
40 |
code[0] = 'CLS' |
|
|
41 |
|
|
|
42 |
# mask 0:len(code) to 1, padding to be 0 |
|
|
43 |
mask = np.ones(self.max_len) |
|
|
44 |
mask[len(code):] = 0 |
|
|
45 |
|
|
|
46 |
# pad age sequence and code sequence |
|
|
47 |
age = seq_padding(age, self.max_len, token2idx=self.age2idx) |
|
|
48 |
|
|
|
49 |
tokens, code = code2index(code, self.vocab) |
|
|
50 |
_, label = code2index(label, self.label_vocab) |
|
|
51 |
|
|
|
52 |
# get position code and segment code |
|
|
53 |
tokens = seq_padding(tokens, self.max_len) |
|
|
54 |
position = position_idx(tokens) |
|
|
55 |
segment = index_seg(tokens) |
|
|
56 |
|
|
|
57 |
# pad code and label |
|
|
58 |
code = seq_padding(code, self.max_len, symbol=self.vocab['PAD']) |
|
|
59 |
label = seq_padding(label, self.max_len, symbol=-1) |
|
|
60 |
|
|
|
61 |
return torch.LongTensor(age), torch.LongTensor(code), torch.LongTensor(position), torch.LongTensor(segment), \ |
|
|
62 |
torch.LongTensor(mask), torch.LongTensor(label), torch.LongTensor([int(patid)]) |
|
|
63 |
|
|
|
64 |
def __len__(self): |
|
|
65 |
return len(self.code) |