-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_processor.py
372 lines (263 loc) · 11.2 KB
/
data_processor.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import torch
import codecs
import json
import pandas as pd
from torch.utils.data import Dataset
from transformers import AutoTokenizer, pipeline
from sklearn.preprocessing import OneHotEncoder
from transformers import pipeline
from tqdm import tqdm
class dataset(Dataset):
def __init__(self, examples):
super(dataset, self).__init__()
self.examples = examples
def __getitem__(self, idx):
return self.examples[idx]
def __len__(self):
return len(self.examples)
def collate_fn(examples):
ids_sent1, segs_sent1, att_mask_sent1, position_sep, labels = map(list, zip(*examples))
ids_sent1 = torch.tensor(ids_sent1, dtype=torch.long)
segs_sent1 = torch.tensor(segs_sent1, dtype=torch.long)
att_mask_sent1 = torch.tensor(att_mask_sent1, dtype=torch.long)
position_sep = torch.tensor(position_sep, dtype=torch.long)
labels = torch.tensor(labels, dtype=torch.long)
return ids_sent1, segs_sent1, att_mask_sent1, position_sep, labels
def collate_fn_adv(examples):
ids_sent1, segs_sent1, att_mask_sent1, position_sep, labels = map(list, zip(*examples))
ids_sent1 = torch.tensor(ids_sent1, dtype=torch.long)
segs_sent1 = torch.tensor(segs_sent1, dtype=torch.long)
att_mask_sent1 = torch.tensor(att_mask_sent1, dtype=torch.long)
position_sep = torch.tensor(position_sep, dtype=torch.long)
return ids_sent1, segs_sent1, att_mask_sent1, position_sep, labels
class DataProcessor:
def __init__(self,config):
self.config = config
self.tokenizer = AutoTokenizer.from_pretrained(self.config["model_name"])
self.max_sent_len = config["max_sent_len"]
def __str__(self,):
pattern = """General data processor: \n\n Tokenizer: {}\n\nMax sentence length: {}""".format(self.config["model_name"], self.max_sent_len)
return pattern
def _get_examples(self, dataset, dataset_type="train"):
examples = []
for row in tqdm(dataset, desc="tokenizing..."):
id, sentence1, sentence2, label = row
"""
for the first sentence
"""
sentence1_length = len(self.tokenizer.encode(sentence1))
sentence2_length = len(self.tokenizer.encode(sentence2))
ids_sent1 = self.tokenizer.encode(sentence1, sentence2)
segs_sent1 = [0] * sentence1_length + [1] * (sentence2_length)
position_sep = [1] * len(ids_sent1)
position_sep[sentence1_length] = 1
position_sep[0] = 0
position_sep[1] = 1
assert len(ids_sent1) == len(position_sep)
assert len(ids_sent1) == len(segs_sent1)
pad_id = self.tokenizer.encode(self.tokenizer.pad_token, add_special_tokens=False)[0]
if len(ids_sent1) < self.max_sent_len:
res = self.max_sent_len - len(ids_sent1)
att_mask_sent1 = [1] * len(ids_sent1) + [0] * res
ids_sent1 += [pad_id] * res
segs_sent1 += [0] * res
position_sep += [0] * res
else:
ids_sent1 = ids_sent1[:self.max_sent_len]
segs_sent1 = segs_sent1[:self.max_sent_len]
att_mask_sent1 = [1] * self.max_sent_len
position_sep = position_sep[:self.max_sent_len]
example = [ids_sent1, segs_sent1, att_mask_sent1, position_sep, label]
examples.append(example)
print(f"finished preprocessing examples in {dataset_type}")
return examples
class DiscourseMarkerProcessor(DataProcessor):
def __init__(self, config):
super(DiscourseMarkerProcessor, self).__init__(config)
self.mapping = self.load_json('json/word_to_target.json')
self.id_to_word = self.load_json('json/id_to_word.json')
def load_json(self, path):
try:
with open(path, 'r') as file:
mapping = json.load(file)
except:
raise FileNotFoundError(f"File {path} not found")
return mapping
def process_dataset(self, dataset, name="train"):
result = []
new_dataset = []
for sample in dataset:
if self.id_to_word[str(sample["label"])] not in self.mapping.keys():
continue
new_dataset.append([sample["sentence1"], sample["sentence2"], self.mapping[self.id_to_word[str(sample["label"])]]])
one_hot_encoder = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
labels = []
for i, sample in tqdm(enumerate(new_dataset), desc="processing labels..."):
labels.append([sample[-1]])
print("one hot encoding...")
labels = one_hot_encoder.fit_transform(labels)
for i, (sample, label) in tqdm(enumerate(zip(new_dataset, labels)), desc="creating results..."):
result.append([f"{name}_{i}", sample[0], sample[1], label])
examples = self._get_examples(result, name)
return examples
class StudentEssayProcessor(DataProcessor):
def __init__(self, config):
super(StudentEssayProcessor,self).__init__(config)
def read_input_files(self, file_path, name="train", pipe=None):
"""
Reads input files in tab-separated format.
Will split file_paths on comma, reading from multiple files.
"""
sentences = []
label_distribution=[]
target = []
target_sentences = []
id=[]
with codecs.open(file_path, encoding="ISO-8859-1", mode="r") as f:
for line in f:
line = line.replace("\n","")
line = line.split("\t")
if line == ['\r']:
continue
sample_id = line[0]
sent = line[1].strip()
target = line[3].strip()
if pipe is not None:
ds_marker = pipe(f"{sent}</s></s>{target}")[0]["label"]
ds_marker = ds_marker.replace("_", " ")
ds_marker = ds_marker[0].upper() + ds_marker[1:]
target = target[0].lower() + target[1:]
target = ds_marker + " " + target
label = line[-1].strip()
sentences.append(sent)
target_sentences.append(target)
id.append(sample_id)
l=[0,0]
if label == 'supports':
l=[1,0]
elif label == 'attacks':
l=[0,1]
label_distribution.append(l)
result = []
for i in range(len(label_distribution)):
result.append([id[i],sentences[i],target_sentences[i], label_distribution[i]])
examples = self._get_examples(result, name)
return examples
class DebateProcessor(DataProcessor):
def __init__(self, config):
super(DebateProcessor,self).__init__(config)
def read_input_files(self, file_path, name="train", pipe=None):
"""
Reads input files in tab-separated format.
Will split file_paths on comma, reading from multiple files.
"""
sentences = []
label_distribution=[]
target_sentences = []
id=[]
with codecs.open(file_path, encoding="ISO-8859-1", mode="r") as f:
for line in f:
line = line.replace("\n","")
line = line.split("\t")
if line == ['\r']:
continue
sample_id = line[0]
sent = line[1].strip()
target = line[3].strip()
label = line[-1].strip()
if pipe is not None:
ds_marker = self.pipe(f"{sent}</s></s>{target}")[0]["label"]
ds_marker = ds_marker.replace("_", " ")
ds_marker = ds_marker[0].upper() + ds_marker[1:]
target = target[0].lower() + target[1:]
target = ds_marker + " " + target
sentences.append(sent)
target_sentences.append(target)
id.append(sample_id)
l=[0,0]
if label == 'support':
l=[1,0]
elif label == 'attack':
l=[0,1]
label_distribution.append(l)
result = []
for i in range(len(label_distribution)):
result.append([id[i],sentences[i],target_sentences[i], label_distribution[i]])
examples = self._get_examples(result, name)
return examples
class MARGProcessor(DataProcessor):
def __init__(self, config):
super(MARGProcessor, self).__init__(config)
self.pipe = pipeline("text-classification", model="sileod/roberta-base-discourse-marker-prediction")
def read_input_files(self, file_path, name="train", pipe=None):
"""
Reads input files in tab-separated format.
Will split file_paths on comma, reading from multiple files.
"""
sentences = []
label_distribution=[]
target_sentences = []
id=[]
df = pd.read_csv(file_path)
for i,row in df.iterrows():
if row[-1] != name:
continue
sample_id = row[0]
sent = row[1].strip()
target = row[2].strip()
if pipe is not None:
ds_marker = self.pipe(f"{sent}</s></s>{target}")[0]["label"]
ds_marker = ds_marker.replace("_", " ")
ds_marker = ds_marker[0].upper() + ds_marker[1:]
target = target[0].lower() + target[1:]
target = ds_marker + " " + target
label = row[3].strip()
sentences.append(sent)
target_sentences.append(target)
id.append(sample_id)
l=[0,0,0]
if label == 'support':
l = [1,0,0]
elif label == 'attack':
l = [0,1,0]
elif label == 'neither':
l = [0,0,1]
label_distribution.append(l)
result = []
for i in range(len(label_distribution)):
result.append([id[i],sentences[i],target_sentences[i], label_distribution[i]])
examples = self._get_examples(result, name)
return examples
class StudentEssayWithDiscourseInjectionProcessor(StudentEssayProcessor):
def __init__(self, config):
super(StudentEssayWithDiscourseInjectionProcessor, self).__init__(config)
self.pipe = pipeline("text-classification", model="sileod/roberta-base-discourse-marker-prediction")
def read_input_files(self, file_path, name="train"):
"""
Reads input files in tab-separated format.
Will split file_paths on comma, reading from multiple files.
"""
examples = super().read_input_files(file_path, name, pipe=self.pipe)
return examples
class DebateWithDiscourseInjectionProcessor(DebateProcessor):
def __init__(self, config):
super(DebateWithDiscourseInjectionProcessor,self).__init__(config)
self.pipe = pipeline("text-classification", model="sileod/roberta-base-discourse-marker-prediction")
def read_input_files(self, file_path, name="train"):
"""
Reads input files in tab-separated format.
Will split file_paths on comma, reading from multiple files.
"""
examples = super().read_input_files(file_path, name, pipe=self.pipe)
return examples
class MARGWithDiscourseInjectionProcessor(DataProcessor):
def __init__(self, config):
super(MARGWithDiscourseInjectionProcessor,self).__init__(config)
self.pipe = pipeline("text-classification", model="sileod/roberta-base-discourse-marker-prediction")
def read_input_files(self, file_path, name="train"):
"""
Reads input files in tab-separated format.
Will split file_paths on comma, reading from multiple files.
"""
examples = super().read_input_files(file_path, name, pipe=self.pipe)
return examples