-
Notifications
You must be signed in to change notification settings - Fork 0
/
seq_utils.py
411 lines (368 loc) · 14.4 KB
/
seq_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
import numpy as np
SMALL_POSITIVE_CONST = 1e-4
def ot2bio_ate(ate_tag_sequence):
"""
ot2bio function for ate task
"""
n_tags = len(ate_tag_sequence)
new_ate_sequence = []
prev_ate_tag = '$$$'
for i in range(n_tags):
cur_ate_tag = ate_tag_sequence[i]
if cur_ate_tag == 'O' or cur_ate_tag == 'EQ':
# note that, EQ tag can be incorrectly predicted in the testing phase
# when meet EQ, regard it as O
new_ate_sequence.append('O')
prev_ate_tag = 'O'
else:
# current ate tag is T
if cur_ate_tag == prev_ate_tag:
new_ate_sequence.append('I')
else:
new_ate_sequence.append('B')
prev_ate_tag = cur_ate_tag
assert len(new_ate_sequence) == len(ate_tag_sequence)
return new_ate_sequence
def ot2bieos_ate(ate_tag_sequence):
"""
ot2bieos function for ate task
"""
n_tags = len(ate_tag_sequence)
new_ate_sequence = []
prev_ate_tag = '$$$'
for i in range(n_tags):
cur_ate_tag = ate_tag_sequence[i]
if cur_ate_tag == 'O' or cur_ate_tag == 'EQ':
# note that, EQ tag can be incorrectly predicted in the testing phase
# when meet EQ, regard it as O
new_ate_sequence.append('O')
prev_ate_tag = 'O'
else:
# current ate tag is T
if cur_ate_tag != prev_ate_tag:
if i == n_tags - 1:
new_ate_sequence.append('S')
else:
next_ate_tag = ate_tag_sequence[i + 1]
if next_ate_tag == 'O':
new_ate_sequence.append('S')
else:
new_ate_sequence.append('B')
else:
# previous ate tag is also T
if i == n_tags - 1:
new_ate_sequence.append('E')
else:
next_ate_tag = ate_tag_sequence[i + 1]
if next_ate_tag == 'O':
new_ate_sequence.append('E')
else:
new_ate_sequence.append('I')
prev_ate_tag = 'T'
return new_ate_sequence
def ot2bio_absa(absa_tag_sequence):
"""
ot2bio function for ts tag sequence
"""
#new_ts_sequence = []
new_absa_sequence = []
n_tag = len(absa_tag_sequence)
prev_pos = '$$$'
for i in range(n_tag):
cur_absa_tag = absa_tag_sequence[i]
if cur_absa_tag == 'O':
new_absa_sequence.append('O')
cur_pos = 'O'
else:
# current tag is subjective tag, i.e., cur_pos is T
# print(cur_ts_tag)
cur_pos, cur_sentiment = cur_absa_tag.split('-')
if cur_pos == prev_pos:
# prev_pos is T
new_absa_sequence.append('I-%s' % cur_sentiment)
else:
# prev_pos is O
new_absa_sequence.append('B-%s' % cur_sentiment)
prev_pos = cur_pos
return new_absa_sequence
def ot2bieos_absa(absa_tag_sequence):
"""
ot2bieos function for end-to-end aspect-based sentiment analysis task
"""
n_tags = len(absa_tag_sequence)
#new_ts_sequence = []
new_absa_sequence = []
prev_pos = '$$$'
for i in range(n_tags):
cur_absa_tag = absa_tag_sequence[i]
if cur_absa_tag == 'O' or cur_absa_tag == 'EQ':
# when meet the EQ tag, regard it as O
new_absa_sequence.append('O')
cur_pos = 'O'
else:
cur_pos, cur_sentiment = cur_absa_tag.split('-')
# cur_pos is T
if cur_pos != prev_pos:
# prev_pos is O and new_cur_pos can only be B or S
if i == n_tags - 1:
new_absa_sequence.append('S-%s' % cur_sentiment)
else:
next_absa_tag = absa_tag_sequence[i + 1]
if next_absa_tag == 'O':
new_absa_sequence.append('S-%s' % cur_sentiment)
else:
new_absa_sequence.append('B-%s' % cur_sentiment)
else:
# prev_pos is T and new_cur_pos can only be I or E
if i == n_tags - 1:
new_absa_sequence.append('E-%s' % cur_sentiment)
else:
next_absa_tag = absa_tag_sequence[i + 1]
if next_absa_tag == 'O':
new_absa_sequence.append('E-%s' % cur_sentiment)
else:
new_absa_sequence.append('I-%s' % cur_sentiment)
prev_pos = cur_pos
return new_absa_sequence
def ot2bio(tags, task):
if task == 'ate':
return ot2bio_ate(tags)
elif task == 'absa':
return ot2bio_absa(tags)
else:
raise Exception("Unsupported task!")
def ot2bieos(tags, task):
if task == 'ate':
return ot2bieos_ate(tags)
elif task == 'absa':
return ot2bieos_absa(tags)
else:
raise Exception("Unsupported task!")
def bio2ot_ate(ate_tag_sequence):
"""
bio2ot function for ate task
"""
n_tags = len(ate_tag_sequence)
new_ate_sequence = []
for i in range(n_tags):
ate_tag = ate_tag_sequence[i]
if ate_tag == 'O' or ate_tag == 'EQ':
# note that, EQ tag can be incorrectly predicted in the testing phase
# when meet EQ, regard it as O
new_ate_sequence.append('O')
else:
new_ate_sequence.append('T')
assert len(new_ate_sequence) == len(ate_tag_sequence)
return new_ate_sequence
def bio2ot_absa(absa_tag_sequence):
"""
bio2ot function for absa task
"""
new_absa_sequence = []
n_tags = len(absa_tag_sequence)
for i in range(n_tags):
absa_tag = absa_tag_sequence[i]
#assert absa_tag != 'EQ'
if absa_tag == 'O' or absa_tag == 'EQ':
new_absa_sequence.append('O')
else:
pos, sentiment = absa_tag.split('-')
new_absa_sequence.append('T-%s' % sentiment)
return new_absa_sequence
def tag2ate(tag_sequence):
"""
:param tag_sequence:
"""
n_tags = len(tag_sequence)
ate_sequence = []
beg, end = -1, -1
for i in range(n_tags):
ate_tag = tag_sequence[i]
if ate_tag == 'S':
ate_sequence.append((i, i))
elif ate_tag == 'B':
beg = i
elif ate_tag == 'E':
end = i
if end > beg > -1:
ate_sequence.append((beg, end))
beg, end = -1, -1
return ate_sequence
def tag2absa(tag_sequence):
"""
transform absa tag sequence to a list of absa triplet (b, e, sentiment)
"""
n_tags = len(tag_sequence)
absa_sequence, sentiments = [], []
beg, end = -1, -1
for i in range(n_tags):
absa_tag = tag_sequence[i]
# current position and sentiment
# tag O and tag EQ will not be counted
eles = absa_tag.split('-')
if len(eles) == 2:
pos, sentiment = eles
else:
pos, sentiment = 'O', 'O'
if sentiment != 'O':
# current word is a subjective word
sentiments.append(sentiment)
if pos == 'S':
# singleton
# assert len(sentiments) == 1
absa_sequence.append((i, i, sentiments[-1]))
sentiments = []
elif pos == 'B':
beg = i
if len(sentiments) > 1:
# remove the effect of the noisy I-{POS,NEG,NEU}
sentiments = [sentiments[-1]]
elif pos == 'E':
end = i
# schema1: only the consistent sentiment tags are accepted
# that is, all of the sentiment tags are the same
if end > beg > -1 and len(set(sentiments)) == 1:
absa_sequence.append((beg, end, sentiment))
sentiments = []
beg, end = -1, -1
return absa_sequence
def match_ate(gold_ate_sequence, pred_ate_sequence):
"""
calculate the proportions of correctly predicted aspect terms
"""
hit_count, gold_count, pred_count = 0, 0, 0
gold_count = len(gold_ate_sequence)
pred_count = len(pred_ate_sequence)
for t in pred_ate_sequence:
if t in gold_ate_sequence:
hit_count += 1
return hit_count, gold_count, pred_count
def match_absa(gold_absa_sequence, pred_absa_sequence):
"""
calculate the number of correctly predicted aspect sentiment
:param gold_absa_sequence: gold standard targeted sentiment sequence
:param pred_absa_sequence: predicted targeted sentiment sequence
"""
# positive, negative and neutral
tag2tagid = {'POS': 0, 'NEG': 1, 'NEU': 2}
hit_count, gold_count, pred_count = np.zeros(3), np.zeros(3), np.zeros(3)
for t in gold_absa_sequence:
#print(t)
ts_tag = t[2]
tid = tag2tagid[ts_tag]
gold_count[tid] += 1
for t in pred_absa_sequence:
ts_tag = t[2]
tid = tag2tagid[ts_tag]
if t in gold_absa_sequence:
hit_count[tid] += 1
pred_count[tid] += 1
return hit_count, gold_count, pred_count
def compute_metrics_absa(pred, gold, label_vocab, tagging_schema):
"""
compute metric scores for absa task
"""
assert len(pred) == len(gold)
num_samples = len(pred)
# number of true positive, gold standard, predicted aspect sentiment triplet
n_tp_absa, n_gold_absa, n_pred_absa = np.zeros(3), np.zeros(3), np.zeros(3)
class_count = np.zeros(3)
class_precision, class_recall, class_f1 = np.zeros(3), np.zeros(3), np.zeros(3)
absa_ground_truth, absa_predictions = [], []
for i in range(num_samples):
eval_positions = np.where(gold[i] != -100)[0]
#print("eval_positions:", eval_positions)
pred_labels = pred[i][eval_positions]
gold_labels = gold[i][eval_positions]
pred_tags = [label_vocab[label] for label in pred_labels]
gold_tags = [label_vocab[label] for label in gold_labels]
if tagging_schema == 'OT':
gold_tags = ot2bieos_absa(gold_tags)
pred_tags = ot2bieos_absa(pred_tags)
elif tagging_schema == 'BIO':
gold_tags = ot2bieos_absa(bio2ot_absa(gold_tags))
pred_tags = ot2bieos_absa(bio2ot_absa(pred_tags))
else:
pass # current tagging schema is BIEOS, do nothing
pred_absa_seq, gold_absa_seq = tag2absa(tag_sequence=pred_tags), tag2absa(tag_sequence=gold_tags)
hit_count, gold_count, pred_count = match_absa(gold_absa_sequence=gold_absa_seq, pred_absa_sequence=pred_absa_seq)
absa_ground_truth.append(gold_absa_seq)
absa_predictions.append(pred_absa_seq)
# true-positive count
n_tp_absa += hit_count
n_gold_absa += gold_count
n_pred_absa += pred_count
for (b, e, s) in gold_absa_seq:
if s == 'POS':
class_count[0] += 1
elif s == 'NEG':
class_count[1] += 1
else:
class_count[2] += 1
print("#POS: {}, #NEG: {}, #NEU: {}".format(class_count[0], class_count[1], class_count[2]))
for i in range(3):
num_hit = n_tp_absa[i]
num_gold = n_gold_absa[i]
num_pred = n_pred_absa[i]
class_precision[i] = float(num_hit) / float(num_pred + SMALL_POSITIVE_CONST)
class_recall[i] = float(num_hit) / float(num_gold + SMALL_POSITIVE_CONST)
class_f1[i] = 2 * class_precision[i] * class_recall[i] / (class_precision[i] + class_recall[i] + SMALL_POSITIVE_CONST)
#print("class count:", class_count)
macro_f1 = class_f1.mean()
num_hit_total = sum(n_tp_absa)
num_pred_total = sum(n_pred_absa)
num_gold_total = sum(n_gold_absa)
micro_precision = float(num_hit_total) / (num_pred_total + SMALL_POSITIVE_CONST)
micro_recall = float(num_hit_total) / (num_gold_total + SMALL_POSITIVE_CONST)
micro_f1 = 2 * micro_precision * micro_recall / (micro_precision + micro_recall + SMALL_POSITIVE_CONST)
scores = {'macro_f1': macro_f1, 'precision': micro_precision,
"recall": micro_recall, "micro_f1": micro_f1}
return scores, absa_ground_truth, absa_predictions
def compute_metrics_ate(pred, gold, label_vocab, tagging_schema):
"""
compute metric scores for ate task
"""
assert len(pred) == len(gold)
num_samples = len(pred)
# number of true postive, gold standard, predicted aspect terms
n_tp_ate, n_gold_ate, n_pred_ate = 0, 0, 0
ate_ground_truth, ate_predictions = [], []
for i in range(num_samples):
# eval_positions = np.where(eval_mask[i] == 1)[0]
eval_positions = np.where(gold[i] != -100)[0]
pred_labels = pred[i][eval_positions]
gold_labels = gold[i][eval_positions]
pred_tags = [label_vocab[label] for label in pred_labels]
gold_tags = [label_vocab[label] for label in gold_labels]
if tagging_schema == 'OT':
gold_tags = ot2bieos_ate(gold_tags)
pred_tags = ot2bieos_ate(pred_tags)
elif tagging_schema == 'BIO':
gold_tags = ot2bieos_ate(bio2ot_ate(gold_tags))
pred_tags = ot2bieos_ate(bio2ot_ate(pred_tags))
else:
pass # current tagging schema is BIEOS, do nothing
# golden & predicted aspect terms
gold_ate_seq, pred_ate_seq = tag2ate(tag_sequence=gold_tags), tag2ate(tag_sequence=pred_tags)
hit_count, gold_count, pred_count = match_ate(gold_ate_sequence=gold_ate_seq, pred_ate_sequence=pred_ate_seq)
ate_ground_truth.append(gold_ate_seq)
ate_predictions.append(pred_ate_seq)
n_tp_ate += hit_count
n_gold_ate += gold_count
n_pred_ate += pred_count
print("number of gold aspect terms: {}".format(n_gold_ate))
precision = float(n_tp_ate) / (float(n_pred_ate) + SMALL_POSITIVE_CONST)
recall = float(n_tp_ate) / (float(n_gold_ate) + SMALL_POSITIVE_CONST)
f1 = 2 * precision * recall / (precision + recall + SMALL_POSITIVE_CONST)
scores = {'precision': precision, 'recall': recall, 'f1': f1}
return scores, ate_ground_truth, ate_predictions
def write_sents_labels(word_seqs, label_seqs, file_name):
lines = []
for i in range(len(word_seqs)):
for j in range(len(word_seqs[i])):
if word_seqs[i][j] != '\u200b':
lines.append(f"{word_seqs[i][j]}\t{label_seqs[i][j]}\tNONE-CATE\n")
lines.append('\n')
with open(file_name, 'w+', encoding='UTF-8') as fp:
fp.writelines(lines)
print(f"Write file to {file_name}")