forked from adinastoll/NLPDL_Project_MemNN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataproc_utils.py
511 lines (363 loc) · 13.1 KB
/
dataproc_utils.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import nltk
import re
import string
import itertools
from imblearn.over_sampling import RandomOverSampler
from imblearn.under_sampling import RandomUnderSampler
from sklearn.metrics import confusion_matrix
def split_paraphs(df):
paragraphs = []
for col, row in df.iterrows():
bid = row['Body ID']
body = row['articleBody']
paras = body.split('\n\n')
for p in paras:
paragraphs.append((bid, p))
return paragraphs
def stance_toint(df):
df.loc[df['Stance'] == 'unrelated', 'Stance'] = 0
df.loc[df['Stance'] == 'discuss', 'Stance'] = 1
df.loc[df['Stance'] == 'agree', 'Stance'] = 2
df.loc[df['Stance'] == 'disagree', 'Stance'] = 3
return df
def get_claims_labels(df):
claims = []
labels = []
for col, row in df.iterrows():
bid = row['Body ID']
line = row['Headline']
claims.append((bid, line))
stance = row['Stance']
labels.append(stance)
return claims, labels
def remove_nonascii(lines):
ascii_chars = set(string.printable)
processed = [[bid, ''.join(filter(lambda x: x in ascii_chars, s))] for bid, s in lines]
return processed
def replace_pattern(old_pat, new_pat, lines):
compiled_old = re.compile(old_pat)
processed = [[bid, re.sub(compiled_old, new_pat, s)] for bid, s in lines]
return processed
def tokenize_lines(lines):
tokenized = [[bid, nltk.word_tokenize(s.lower())] for bid, s in lines]
return tokenized
def replace_pattern_tokenized(old_pat, new_pat, tokens):
compiled_old = re.compile(old_pat)
processed = [[bid, [re.sub(compiled_old, new_pat, tok) for tok in line]] for bid, line in tokens]
return processed
def trim_bodies(body_pars, keep_count=9, keep_length=None):
paragraph_dict = {}
count_dict = {}
for bid, par in body_pars:
if keep_length:
par = par[1][:keep_length]
if bid not in count_dict:
count_dict[bid] = 0
paragraph_dict[bid] = []
if count_dict[bid] < keep_count:
paragraph_dict[bid].append((bid, par))
count_dict[bid] = count_dict[bid] + 1
trimmed_pars = []
for k, v in paragraph_dict.items():
trimmed_pars += v
return trimmed_pars
def trim_claims(claims, keep_length=12):
trimmed_claims = []
for c in claims:
new_claim = c[1][:keep_length]
trimmed_claims.append([c[0], new_claim])
return trimmed_claims
def save_proc_bodies(filename, bodies):
all_pars = [str(bid) + ' ' + ' '.join(p) for bid, p in bodies if len(p) > 0]
txt_file = '\n'.join(all_pars)
with open(filename, 'w') as f:
f.write(txt_file)
def save_proc_claims(filename, claims, labels):
all_claims = []
for i in range(len(labels)):
bid = claims[i][0]
claim = claims[i][1]
label = labels[i]
all_claims.append(str(bid) + ' ' + ' '.join(claim) + ' ' + str(label))
txt_file = '\n'.join(all_claims)
with open(filename, 'w') as f:
f.write(txt_file)
def parse_proc_bodies(all_bodies):
bodies = []
for line in all_bodies:
line = line.strip().split()
bid = int(line[0])
par = line[1:]
bodies.append((bid, par))
return bodies
def parse_proc_bodies_dict(all_bodies, split_pars=True, tokenize=True):
bid2pars = {}
for line in all_bodies:
line = line.strip().split()
bid = int(line[0])
par = line[1:]
if tokenize is False:
par = ' '.join(par)
if bid in bid2pars:
if split_pars:
bid2pars[bid].append(par)
else:
bid2pars[bid].extend(par)
else:
if split_pars:
bid2pars[bid] = [par]
else:
bid2pars[bid] = par
return bid2pars
def parse_proc_claims(all_claims):
claims = []
labels = []
for line in all_claims:
line = line.strip().split()
bid = int(line[0])
claim = line[1:-1]
label = int(line[-1])
claims.append((bid, claim))
labels.append(label)
return claims, labels
def load_file(filename):
with open(filename) as f:
lines = f.readlines()
return lines
def read_proc_data(all_bodies, all_claims, split_pars=True):
b2p = parse_proc_bodies_dict(all_bodies, split_pars=split_pars)
data = []
for line in all_claims:
line = line.strip().split()
bid = int(line[0])
claim = line[1:-1]
label = int(line[-1])
if bid in b2p:
data.append((b2p[bid], claim, label))
return data
def load_proc_data(bodies_filename, claims_filename, split_pars=True):
all_bodies = load_file(bodies_filename)
all_claims = load_file(claims_filename)
b2p = parse_proc_bodies_dict(all_bodies, split_pars=split_pars)
data = []
for line in all_claims:
line = line.strip().split()
bid = int(line[0])
claim = line[1:-1]
label = int(line[-1])
if bid in b2p:
data.append((b2p[bid], claim, label))
return data
def make_word_freq_V(data, fmin=None):
V = {'<unknown>': 0}
for b, c, _ in data:
for par in b:
for word in par:
V[word] = V.get(word, 0) + 1
for word in c:
V[word] = V.get(word, 0) + 1
if fmin is not None:
most_freq_V = {'<unknown>': 0}
for word, count in V.items():
if count < fmin:
most_freq_V['<unknown>'] += 1
else:
most_freq_V[word] = count
V = most_freq_V
return V
def word2idx(vocab, pretrained=None):
if pretrained is None:
word_idx = {w: i+1 for i, w in enumerate(vocab)}
else:
word_idx = {w: i+1 for i, w in enumerate(vocab.keys() & pretrained.keys())}
return word_idx
def make_V(body_pars, claims):
V = {}
for par in body_pars:
for word in par[1]:
V[word] = V.get(word, 0) + 1
for line in claims:
for word in line[1]:
V[word] = V.get(word, 0) + 1
return V
def remove_rare(V_dict, fmin=2):
most_freq_V = {'<unknown>': 0}
for k, v in V_dict.items():
if v < fmin:
most_freq_V['<unknown>'] += 1
else:
most_freq_V[k] = v
return most_freq_V
def remove_placeholder_keys(V_dict, old_keys, new_keys):
for i in range(len(new_keys)):
old_k = old_keys[i]
if old_k in V_dict:
V_dict[new_keys[i]] = V_dict[old_k]
del V_dict[old_k]
return V_dict
def extract_wordvecs(filename, V_dict):
vec_dict = {}
with open(filename, encoding='utf-8') as f:
for line in f:
line = line.strip().split()
word = line[0]
if word in V_dict:
vec_dict[word] = line[1:]
return vec_dict
def write_wordvecs_tofile(filename, vec_dict):
txt_file = '\n'.join([k + ' ' + ' '.join(v) for k, v in vec_dict.items()])
with open(filename, 'w') as f:
f.write(txt_file)
def load_wordvecs(filename):
w2v = {}
with open(filename) as f:
for line in f:
line = line.strip().split()
w2v[line[0]] = [float(x) for x in line[1:]]
return w2v
def make_id_dicts(k2v_dict):
k2i, i2k, i2v, i = {}, {}, {}, 0
for k, v in k2v_dict.items():
k2i[k] = i
i2k[i] = k
i2v[i] = v
i += 1
return k2i, i2k, i2v
def vocab_vectorizer(data, w2i, max_par_num=9, max_par_len=30, max_claim_len=30):
nclaims = len(data)
d = np.zeros((nclaims, max_par_num, max_par_len), dtype=np.int32)
s = np.zeros((nclaims, max_claim_len), dtype=np.int32)
for i in range(nclaims):
max_npars = max_par_num
max_claim_length = max_claim_len
body, claim, _ = data[i]
npars = len(body)
if npars < max_npars:
npars, max_npars = max_npars, npars
for j in range(max_npars):
max_par_length = max_par_len
par = body[j]
par_len = len(par)
if par_len < max_par_length:
par_len, max_par_length = max_par_length, par_len
for k in range(max_par_length):
pword = par[k]
if pword in w2i:
d[i, j, k] = w2i[pword]
else:
d[i, j, k] = w2i['<unknown>']
claim_len = len(claim)
if claim_len < max_claim_length:
claim_len, max_claim_length = max_claim_length, claim_len
for m in range(max_claim_length):
cword = claim[m]
if cword in w2i:
s[i, m] = w2i[cword]
else:
s[i, m] = w2i['<unknown>']
return d, s
def word_vectorizer(data, w2i, max_body_len=30, max_claim_len=12):
nclaims = len(data)
d = np.zeros((nclaims, max_body_len), dtype=np.int32)
s = np.zeros((nclaims, max_claim_len), dtype=np.int32)
for i in range(nclaims):
body_len = max_body_len
claim_len = max_claim_len
body, claim, _ = data[i]
nwords_body = len(body)
if nwords_body < body_len:
nwords_body, body_len = body_len, nwords_body
for j in range(body_len):
pword = body[j]
if pword in w2i:
d[i, j] = w2i[pword]
else:
d[i, j] = w2i['<unknown>']
nwords_claim = len(claim)
if nwords_claim < claim_len:
nwords_claim, claim_len = claim_len, nwords_claim
for k in range(claim_len):
cword = claim[k]
if cword in w2i:
s[i, k] = w2i[cword]
else:
s[i, k] = w2i['<unknown>']
return d, s
def label2onehot(labels):
n = len(labels)
onehot_labels = np.zeros((n, 4), dtype=np.int32)
for i in range(n):
label = labels[i]
onehot_labels[i, label] = 1
return onehot_labels
def random_sampler(X_body, X_claim, X_p_tfidf, y, type='under', random_state=42):
if type == 'under':
rs = RandomUnderSampler(sampling_strategy='majority', random_state=random_state)
elif type == 'over':
rs = RandomOverSampler(random_state=random_state)
else:
raise ValueError('Incorrect sampler type.')
body_shape = X_body.shape
if len(body_shape) > 2:
n, m, s = body_shape
X_body = X_body.reshape((n, -1))
X = np.hstack((X_body, X_claim, X_p_tfidf))
X_resampled, y_resampled = rs.fit_resample(X, y)
X_body_resampled = X_resampled[:, :(m * s)].reshape((-1, m, s))
X_claim_resampled = X_resampled[:, (m * s): -m]
X_p_tfidf_resampled = X_resampled[:, -m:]
else:
n, m = body_shape
X = np.hstack((X_body, X_claim, X_p_tfidf))
X_resampled, y_resampled = rs.fit_resample(X, y)
X_body_resampled = X_resampled[:, :m]
X_claim_resampled = X_resampled[:, m:-m]
X_p_tfidf_resampled = X_resampled[:, -m:]
return X_body_resampled, X_claim_resampled, X_p_tfidf_resampled, y_resampled
def plot_confusion_matrix(cm, classes,
normalize=True,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
# print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.tight_layout()
return plt.gcf()
def get_score(true_label, predicted_label):
# 0 - unrelated, #1 - discuss, #2 - agree, #3 - disagree
unrelated_class = [0]
related_class = [1, 2, 3]
if true_label in unrelated_class and predicted_label in unrelated_class:
return 0.25
elif true_label in related_class and predicted_label in related_class:
return 0.25 + (0.75 if predicted_label == true_label else 0)
return 0
def compute_weighted_accuracy(true_labels, predicted_labels):
scores = [get_score(true, pred) for true, pred in list(zip(true_labels, predicted_labels))]
best_result = [get_score(true, pred) for true, pred in list(zip(true_labels, true_labels))]
weighted_accuracy = np.sum(scores) / np.sum(best_result)
return weighted_accuracy