-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdataset.py
236 lines (192 loc) · 7.54 KB
/
dataset.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
""" PyTorch dataset class"""
import pickle
import random
import torch
import numpy as np
from torch import LongTensor
# from nltk.corpus import wordnet
class Dataset:
""" Dataset Class : callable """
def __init__(self):
super().__init__()
def __iter__(self):
raise NotImplementedError
class ClassificationDataset(Dataset):
""" Classification Dataset wrapper """
def __init__(self, file_name: str, batch_size: int, vocab: dict, datatype: str = 'train', gpu: bool = True, max_pad_size: int = 5):
super().__init__()
self.batch_size = batch_size
self.file_name = file_name
self.vocab = vocab
self.ivocab = dict(zip(vocab.values(), vocab.keys()))
self.datatype = datatype
self.gpu = gpu
self.max_pad_size = 0
self.data = pickle.load(open(file_name, 'rb'))
def __len__(self):
return len(self.data[0])
def __iter__(self):
batch = []
for d in zip(*self.data):
if self.gpu:
d = [t.cuda() for t in d]
batch.append(d)
if len(batch) == self.batch_size:
batch = [torch.stack(d) for d in zip(*batch)]
yield batch
batch.clear()
if batch:
batch = [torch.stack(d) for d in zip(*batch)]
yield batch
class ClassificationDataset_old(Dataset):
""" Classification Dataset wrapper """
def __init__(self, file_name: str, batch_size: int, vocab: dict, datatype: str = 'train', max_pad_size: int = 5):
super().__init__()
self.batch_size = batch_size
self.file_name = file_name
self.vocab = vocab
self.ivocab = dict(zip(vocab.values(), vocab.keys()))
self.datatype = datatype
self.max_pad_size = 0
self.data = []
with open(self.file_name, mode='r', encoding='utf-8') as f:
for line in f:
self.data.append(line)
self.real_label = {}
# self.new_map = pickle.load(open('diff.pkl', 'rb'))
self.replace = False
def set_replacement(self, val):
self.replace = val
def get_real_label(self, idx):
return self.real_label[int(idx)]
def __len__(self):
return len(self.data)
def __iter__(self):
# with open(self.file_name, mode='r', encoding='utf-8') as f:
x, y, xlen = [], [], []
c = []
ids = []
max_seq = 0
for line in self.data:
line = line.replace('\n', '')
line = list(map(int, line.split(',')))
if self.datatype == 'train':
idx, label, label_sample, text = line[0], line[1], line[2], line[3:]
is_corrupted = (label_sample != label)
c.append(is_corrupted)
ids.append(idx)
x.append(text)
y.append(label_sample)
xlen.append(len(text))
max_seq = max(max_seq, len(text))
if idx not in self.real_label:
self.real_label[idx] = label
elif self.datatype == 'test':
idx, label, text = line[0], line[1], line[2:]
ids.append(idx)
x.append(text)
y.append(label)
xlen.append(len(text))
max_seq = max(max_seq, len(text))
if len(x) == self.batch_size:
for i, d in enumerate(x):
npad = (max_seq - len(d) + self.max_pad_size)
d.extend([self.vocab['<pad>']] * npad)
x[i] = d
yield LongTensor(x), LongTensor(y), LongTensor(xlen), LongTensor(ids), LongTensor(c)
x.clear()
y.clear()
xlen.clear()
c.clear()
ids.clear()
max_seq = 0
if len(x) == 0:
np.random.shuffle(self.data)
return
else:
for i, d in enumerate(x):
npad = (max_seq - len(d) + self.max_pad_size)
d.extend([self.vocab['<pad>']] * npad)
# d = list(reversed(d))
# d.extend([self.vocab['<pad>']] * self.max_pad_size)
# d = list(reversed(d))
x[i] = d
np.random.shuffle(self.data)
return LongTensor(x), LongTensor(y), LongTensor(xlen), LongTensor(ids), LongTensor(c)
class SequenceDataset(Dataset):
""" Sequence Dataset wrapper """
def __init__(self, file_name: str, batch_size: int, vocab: dict, datatype: str = 'train', max_pad_size: int = 5):
super().__init__()
self.batch_size = batch_size
self.file_name = file_name
self.vocab = vocab
self.ivocab = dict(zip(vocab.values(), vocab.keys()))
self.datatype = datatype
self.max_pad_size = 0
self.data = []
with open(self.file_name, mode='r', encoding='utf-8') as f:
for line in f:
self.data.append(line)
self.real_label = {}
# self.new_map = pickle.load(open('diff.pkl', 'rb'))
self.replace = False
def get_real_label(self, idx):
idx = int(idx)
return self.real_label[int(idx)]
def __len__(self):
return len(self.data)
def __iter__(self):
# with open(self.file_name, mode='r', encoding='utf-8') as f:
x, y, xlen = [], [], []
c = []
ids = []
max_seq = 0
for line in self.data:
line = line.replace('\n', '')
line = line.split('#')
if self.datatype == 'train':
idx, label, label_sample, text = line[0], line[1], line[2], line[3]
idx = int(idx)
text = list(map(int, text.split(',')))
label_sample = list(map(int, label_sample.split(',')))
label = list(map(int, label.split(',')))
for l, lc in zip(label, label_sample):
c.append(l == lc)
ids.append(idx)
x.append(text)
y.append(label_sample)
xlen.append(len(text))
max_seq = max(max_seq, len(text))
if idx not in self.real_label:
self.real_label[idx] = label
elif self.datatype == 'test':
idx, label, text = line[0], line[1], line[2]
idx = int(idx)
text = list(map(int, text.split(',')))
label = list(map(int, label.split(',')))
ids.append(idx)
x.append(text)
y.append(label)
xlen.append(len(text))
max_seq = max(max_seq, len(text))
if len(x) == self.batch_size:
for i, d in enumerate(x):
npad = (max_seq - len(d))
x[i].extend([self.vocab['<pad>']] * npad)
y[i].extend([self.vocab['<unk>']] * npad)
yield LongTensor(x), LongTensor(y), LongTensor(xlen), LongTensor(ids), LongTensor(c)
x.clear()
y.clear()
xlen.clear()
c.clear()
ids.clear()
max_seq = 0
if len(x) == 0:
np.random.shuffle(self.data)
return
for i, d in enumerate(x):
npad = (max_seq - len(d) + self.max_pad_size)
x[i].extend([self.vocab['<pad>']] * npad)
y[i].extend([self.vocab['<unk>']] * npad)
np.random.shuffle(self.data)
yield LongTensor(x), LongTensor(y), LongTensor(xlen), LongTensor(ids), LongTensor(c)