Diff of /dataLoader/MLM.py [000000] .. [bad60c]

Switch to unified view

a b/dataLoader/MLM.py
1
from torch.utils.data.dataset import Dataset
2
import numpy as np
3
from dataLoader.utils import seq_padding,position_idx,index_seg,random_mask
4
import torch
5
6
7
class MLMLoader(Dataset):
8
    def __init__(self, dataframe, token2idx, age2idx, max_len, code='code', age='age'):
9
        self.vocab = token2idx
10
        self.max_len = max_len
11
        self.code = dataframe[code]
12
        self.age = dataframe[age]
13
        self.age2idx = age2idx
14
15
    def __getitem__(self, index):
16
        """
17
        return: age, code, position, segmentation, mask, label
18
        """
19
20
        # extract data
21
        age = self.age[index][(-self.max_len+1):]
22
        code = self.code[index][(-self.max_len+1):]
23
24
        # avoid data cut with first element to be 'SEP'
25
        if code[0] != 'SEP':
26
            code = np.append(np.array(['CLS']), code)
27
            age = np.append(np.array(age[0]), age)
28
        else:
29
            code[0] = 'CLS'
30
31
        # mask 0:len(code) to 1, padding to be 0
32
        mask = np.ones(self.max_len)
33
        mask[len(code):] = 0
34
35
        # pad age sequence and code sequence
36
        age = seq_padding(age, self.max_len, token2idx=self.age2idx)
37
38
        tokens, code, label = random_mask(code, self.vocab)
39
40
        # get position code and segment code
41
        tokens = seq_padding(tokens, self.max_len)
42
        position = position_idx(tokens)
43
        segment = index_seg(tokens)
44
45
        # pad code and label
46
        code = seq_padding(code, self.max_len, symbol=self.vocab['PAD'])
47
        label = seq_padding(label, self.max_len, symbol=-1)
48
49
        return torch.LongTensor(age), torch.LongTensor(code), torch.LongTensor(position), torch.LongTensor(segment), \
50
               torch.LongTensor(mask), torch.LongTensor(label)
51
52
    def __len__(self):
53
        return len(self.code)