-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataload.py
65 lines (53 loc) · 1.94 KB
/
dataload.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
""" 为模型准备输入的数据集类 """
import os
from torch.utils.data import Dataset, DataLoader
class DataSet(Dataset):
def __init__(self, file_name='NCBI-disease', train=True):
if file_name == 'NCBI-disease':
file_path = r'./NERdata/NCBI-disease'
elif file_name == 'BC4CHEMD':
file_path = r'./NERdata/BC4CHEMD'
else:
file_path = r'./NERdata/BC5CDR-chem'
if train == True:
with open(os.path.join(file_path, 'train_dev.tsv'), 'r') as f:
data = f.readlines()
else:
with open(os.path.join(file_path, 'test.tsv'), 'r') as f:
data = f.readlines()
self.content = []
words = []
tags = []
for line in data:
line_content = [i.strip().upper() for i in line.split()]
if line_content == []:
temp = list(zip(words, tags))
self.content.append(temp)
words = []
tags = []
else:
words.append(line_content[0])
tags.append(line_content[-1])
def __len__(self):
return len(self.content)
def __getitem__(self, item):
contents, target = zip(*self.content[item])
return list(contents), list(target)
def collate_fn(batch):
sentences, tags = zip(*batch)
return sentences, tags
def DataLoad(file_name ='NCBI-disease',train=True):
if train == True:
batch_size = 32
else:
batch_size = 64
dataset = DataSet(file_name,train)
dataloader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True, collate_fn=collate_fn, drop_last=True)
return dataloader
if __name__ == '__main__':
dataset = DataLoad('BC5CDR-chem',True) # 'NCBI-disease','BC4CHEMD','BC5CDR-chem'
for index, (sentences, tags) in enumerate(dataset):
print(index)
print(sentences)
print(tags)
break