Sanatbek_Matlatipov
commited on
Commit
·
56f55f1
1
Parent(s):
43e4e79
Evaluation part and test and gold annotated data is added to check the inter-annotator agreement
Browse files
data/absa_uz-manual-gold-cohen-kappa.xml
ADDED
The diff for this file is too large to render.
See raw diff
|
|
data/absa_uz-manual-gold.xml
ADDED
The diff for this file is too large to render.
See raw diff
|
|
data/absa_uz-manual-test-cohen-kapp.xml
ADDED
The diff for this file is too large to render.
See raw diff
|
|
data/absa_uz-manual-test.xml
ADDED
The diff for this file is too large to render.
See raw diff
|
|
evaluations/krippendorff-eval.py
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
import krippendorff
|
2 |
+
|
3 |
+
krippendorff.alpha(reliability_data=...)
|
evaluations/manual_evaluation.py
ADDED
@@ -0,0 +1,453 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
__author__ = "Matlatipov Sanatbek, Jaloliddin Rajabov"
|
2 |
+
__credits__ = ""
|
3 |
+
__license__ = ""
|
4 |
+
__version__ = ""
|
5 |
+
__maintainer__ = ""
|
6 |
+
__email__ = "{s.matlatipov, j.rajabov}@nuu.uz"
|
7 |
+
|
8 |
+
try:
|
9 |
+
import xml.etree.ElementTree as ET, getopt, logging, sys, random, re, copy
|
10 |
+
from xml.sax.saxutils import escape
|
11 |
+
import krippendorff as kp
|
12 |
+
from sklearn.metrics import confusion_matrix, cohen_kappa_score
|
13 |
+
import pandas as pd
|
14 |
+
import numpy as np
|
15 |
+
import re
|
16 |
+
import matplotlib.pyplot as plt
|
17 |
+
import seaborn as sns
|
18 |
+
except:
|
19 |
+
sys.exit('Some package is missing... Perhaps <re>?')
|
20 |
+
|
21 |
+
logging.basicConfig(level=logging.INFO)
|
22 |
+
logger = logging.getLogger(__name__)
|
23 |
+
|
24 |
+
|
25 |
+
def fd(counts):
|
26 |
+
"""Given a list of occurrences (e.g., [1,1,1,2]), return a dictionary of frequencies (e.g., {1:3, 2:1}.)"""
|
27 |
+
d = {}
|
28 |
+
for i in counts:
|
29 |
+
d[i] = d[i] + 1 if i in d else 1
|
30 |
+
return d
|
31 |
+
|
32 |
+
|
33 |
+
frequency_rank = lambda d: sorted(d, key=d.get, reverse=True)
|
34 |
+
'Given a map, return ranked the keys based on their values.'
|
35 |
+
|
36 |
+
|
37 |
+
class Category:
|
38 |
+
"""Category objects contain the term and polarity (i.e., pos, neg, neu, conflict) of the category (e.g., food,
|
39 |
+
price, etc.) of a sentence. """
|
40 |
+
|
41 |
+
def __init__(self, term='', polarity=''):
|
42 |
+
self.term = term
|
43 |
+
self.polarity = polarity
|
44 |
+
|
45 |
+
def create(self, element):
|
46 |
+
self.term = element.attrib['category']
|
47 |
+
self.polarity = element.attrib['polarity']
|
48 |
+
return self
|
49 |
+
|
50 |
+
def update(self, term='', polarity=''):
|
51 |
+
self.term = term
|
52 |
+
self.polarity = polarity
|
53 |
+
|
54 |
+
|
55 |
+
class Aspect:
|
56 |
+
"""Aspect objects contain the term (e.g., battery life) and polarity (i.e., positive, negative, neutral, conflict)
|
57 |
+
of an aspect. """
|
58 |
+
|
59 |
+
def __init__(self, term, polarity, offsets):
|
60 |
+
self.term = term
|
61 |
+
self.polarity = polarity
|
62 |
+
self.offsets = offsets
|
63 |
+
|
64 |
+
def create(self, element):
|
65 |
+
self.term = element.attrib['term']
|
66 |
+
self.polarity = element.attrib['polarity']
|
67 |
+
self.offsets = {'from': str(element.attrib['from']), 'to': str(element.attrib['to'])}
|
68 |
+
return self
|
69 |
+
|
70 |
+
def update(self, term='', polarity=''):
|
71 |
+
self.term = term
|
72 |
+
self.polarity = polarity
|
73 |
+
|
74 |
+
|
75 |
+
def validate(filename):
|
76 |
+
"""Validate an XML file"""
|
77 |
+
elements = ET.parse(filename).getroot().findall('sentence')
|
78 |
+
aspects = []
|
79 |
+
for e in elements:
|
80 |
+
for eterms in e.findall('aspectTerms'):
|
81 |
+
if eterms is not None:
|
82 |
+
for a in eterms.findall('aspectTerm'):
|
83 |
+
aspects.append(Aspect('', '', []).create(a).term)
|
84 |
+
return elements, aspects
|
85 |
+
|
86 |
+
|
87 |
+
fix = lambda text: escape(text.encode('utf8')).replace('\"', '"')
|
88 |
+
'Simple fix for writing out text.'
|
89 |
+
|
90 |
+
|
91 |
+
class Instance:
|
92 |
+
"""An instance is a sentence, modeled out of XML (pre-specified format, based on the 4th task of SemEval 2014).
|
93 |
+
It contains the text, the aspect terms, and any aspect categories."""
|
94 |
+
|
95 |
+
def __init__(self, element):
|
96 |
+
self.text = element.find('text').text
|
97 |
+
self.id = element.get('ID')
|
98 |
+
self.aspect_terms = [Aspect('', '', offsets={'from': '', 'to': ''}).create(e) for es in
|
99 |
+
element.findall('aspectTerms') for e in es if
|
100 |
+
es is not None]
|
101 |
+
self.aspect_categories = [Category(term='', polarity='').create(e) for es in element.findall('aspectCategories')
|
102 |
+
for e in es if
|
103 |
+
es is not None]
|
104 |
+
|
105 |
+
def get_aspect_terms(self):
|
106 |
+
return [a.term.lower() for a in self.aspect_terms]
|
107 |
+
|
108 |
+
def get_aspect_categories(self):
|
109 |
+
return [c.term.lower() for c in self.aspect_categories]
|
110 |
+
|
111 |
+
def add_aspect_term(self, term, polarity='', offsets=None):
|
112 |
+
if offsets is None:
|
113 |
+
offsets = {'from': '', 'to': ''}
|
114 |
+
a = Aspect(term, polarity, offsets)
|
115 |
+
self.aspect_terms.append(a)
|
116 |
+
|
117 |
+
def add_aspect_category(self, term, polarity=''):
|
118 |
+
c = Category(term, polarity)
|
119 |
+
self.aspect_categories.append(c)
|
120 |
+
|
121 |
+
|
122 |
+
class Corpus:
|
123 |
+
"""A corpus contains instances, and is useful for training algorithms or splitting to train/test files."""
|
124 |
+
|
125 |
+
def __init__(self, elements):
|
126 |
+
self.corpus = [Instance(e) for e in elements]
|
127 |
+
self.size = len(self.corpus)
|
128 |
+
self.aspect_terms_fd = fd([a for i in self.corpus for a in i.get_aspect_terms()])
|
129 |
+
self.top_aspect_terms = frequency_rank(self.aspect_terms_fd)
|
130 |
+
self.texts = [t.text for t in self.corpus]
|
131 |
+
|
132 |
+
def echo(self):
|
133 |
+
print('%d instances\n%d distinct aspect terms' % (len(self.corpus), len(self.top_aspect_terms)))
|
134 |
+
print('Top aspect terms: %s' % (', '.join(self.top_aspect_terms[:10])))
|
135 |
+
|
136 |
+
def clean_tags(self):
|
137 |
+
for i in range(len(self.corpus)):
|
138 |
+
self.corpus[i].aspect_terms = []
|
139 |
+
|
140 |
+
|
141 |
+
class Evaluate:
|
142 |
+
"""Manual evaluation of subtask"""
|
143 |
+
|
144 |
+
def __init__(self, correct, predicted):
|
145 |
+
self.value_domains_str = None
|
146 |
+
self.size = len(correct)
|
147 |
+
self.correct = correct
|
148 |
+
self.predicted = predicted
|
149 |
+
self.reliability_aspect_terms_data = self.get_reliability_aspect_terms_data()
|
150 |
+
self.reliability_aspect_terms_polarity = self.get_reliability_aspect_terms_polarity()
|
151 |
+
self.reliability_aspect_categories_data = self.get_reliability_aspect_category_data()
|
152 |
+
self.reliability_aspect_categoty_polarity = self.get_reliability_aspect_categories_polarities()
|
153 |
+
|
154 |
+
def krippendorff_alpha_aspect_terms(self, krippendorff_metric_type):
|
155 |
+
self.get_aspect_terms_value_domains_str()
|
156 |
+
alpha = kp.alpha(reliability_data=self.reliability_aspect_terms_data, value_domain=list(self.value_domains_str),
|
157 |
+
level_of_measurement=krippendorff_metric_type)
|
158 |
+
return alpha
|
159 |
+
|
160 |
+
def krippendorff_alpha_aspect_terms_polarity(self, krippendorff_metric_type):
|
161 |
+
self.get_aspect_terms_value_domains_str()
|
162 |
+
alpha = kp.alpha(reliability_data=self.reliability_aspect_terms_polarity,
|
163 |
+
level_of_measurement=krippendorff_metric_type)
|
164 |
+
return alpha
|
165 |
+
|
166 |
+
def krippendorff_alpha_aspect_categories(self, krippendorff_metric_type):
|
167 |
+
alpha = kp.alpha(reliability_data=self.reliability_aspect_categories_data,
|
168 |
+
value_domain=list(['ovqat', 'xizmat', 'muhit', 'narx', 'boshqalar']),
|
169 |
+
level_of_measurement=krippendorff_metric_type)
|
170 |
+
# value_counts = kp._reliability_data_to_value_counts(reliability_data, value_domain)
|
171 |
+
# alpha.
|
172 |
+
return alpha
|
173 |
+
|
174 |
+
def krippendorff_alpha_aspect_terms_polarity(self, krippendorff_metric_type):
|
175 |
+
self.get_aspect_terms_value_domains_str()
|
176 |
+
alpha = kp.alpha(reliability_data=self.reliability_aspect_terms_polarity,
|
177 |
+
level_of_measurement=krippendorff_metric_type)
|
178 |
+
return alpha
|
179 |
+
|
180 |
+
def get_aspect_terms_value_domains_str(self):
|
181 |
+
self.value_domains_str = set(self.reliability_aspect_terms_data[0])
|
182 |
+
self.value_domains_str.update(self.reliability_aspect_terms_data[1])
|
183 |
+
|
184 |
+
def get_reliability_aspect_terms_data(self):
|
185 |
+
new_gold = []
|
186 |
+
new_test = []
|
187 |
+
for i in range(self.size):
|
188 |
+
gold = self.correct[i].get_aspect_terms()
|
189 |
+
test = self.predicted[i].get_aspect_terms()
|
190 |
+
self.get_reliability_data(gold, new_gold, new_test, test)
|
191 |
+
return [new_gold, new_test]
|
192 |
+
|
193 |
+
def get_reliability_aspect_terms_polarity(self):
|
194 |
+
new_gold, new_test = [], []
|
195 |
+
for i in range(self.size):
|
196 |
+
cor_offsets, cor_polarities = [], []
|
197 |
+
pre_offsets, pre_polarities = [], []
|
198 |
+
for a in self.correct[i].aspect_terms:
|
199 |
+
cor_offsets = list(a.offsets)
|
200 |
+
cor_polarities = list(a.polarity)
|
201 |
+
for a in self.predicted[i].aspect_terms:
|
202 |
+
pre_offsets = list(a.offsets)
|
203 |
+
pre_polarities = list(a.polarity)
|
204 |
+
for cor_idx in range(len(cor_offsets)):
|
205 |
+
for pre_idx in range(len(pre_offsets)):
|
206 |
+
if cor_offsets[cor_idx] != pre_offsets[pre_idx]:
|
207 |
+
new_gold.append(cor_polarities[cor_idx])
|
208 |
+
new_test.append(np.nan)
|
209 |
+
new_gold.append(np.nan)
|
210 |
+
new_test.append(pre_polarities[pre_idx])
|
211 |
+
else:
|
212 |
+
new_gold.append(cor_polarities[cor_idx])
|
213 |
+
new_test.append(pre_polarities[pre_idx])
|
214 |
+
return [new_gold, new_test]
|
215 |
+
|
216 |
+
def get_reliability_aspect_category_data(self):
|
217 |
+
new_gold = []
|
218 |
+
new_test = []
|
219 |
+
for i in range(self.size):
|
220 |
+
gold = self.correct[i].get_aspect_categories()
|
221 |
+
test = self.predicted[i].get_aspect_categories()
|
222 |
+
gold = sorted(gold)
|
223 |
+
test = sorted(test)
|
224 |
+
new_gold = new_gold + gold
|
225 |
+
new_test = new_test + test
|
226 |
+
return [new_gold, new_test]
|
227 |
+
|
228 |
+
def get_reliability_aspect_categories_polarities(self):
|
229 |
+
new_gold, new_test = [], []
|
230 |
+
for i in range(self.size):
|
231 |
+
cor_polarities = self.correct[i].aspect_categories
|
232 |
+
pre_polarities = self.predicted[i].aspect_categories
|
233 |
+
new_gold = new_gold + cor_polarities
|
234 |
+
new_test = new_test + pre_polarities
|
235 |
+
return [new_gold, new_test]
|
236 |
+
|
237 |
+
@staticmethod
|
238 |
+
def get_reliability_data(gold, new_gold, new_test, test):
|
239 |
+
gold = sorted(gold)
|
240 |
+
test = sorted(test)
|
241 |
+
cnt = 0
|
242 |
+
for j in range(max(len(gold), len(test))):
|
243 |
+
try:
|
244 |
+
goldJ = re.sub(r'[^\w]', ' ', gold[j])
|
245 |
+
testJ = re.sub(r'[^\w]', ' ', test[j])
|
246 |
+
if goldJ != testJ:
|
247 |
+
cnt = cnt + 1
|
248 |
+
new_gold.append(goldJ)
|
249 |
+
new_test.append(np.nan)
|
250 |
+
new_gold.append(np.nan)
|
251 |
+
new_test.append(testJ)
|
252 |
+
else:
|
253 |
+
new_test.append(testJ)
|
254 |
+
new_gold.append(goldJ)
|
255 |
+
except IndexError:
|
256 |
+
if len(gold) < j:
|
257 |
+
new_gold.append(np.nan)
|
258 |
+
if len(test) < j:
|
259 |
+
new_test.append(np.nan)
|
260 |
+
|
261 |
+
def aspect_extraction(self, b=1):
|
262 |
+
manual_common, manual_gold, manual_test = 0., 0., 0.
|
263 |
+
for i in range(self.size):
|
264 |
+
cor = [a.offsets for a in self.correct[i].aspect_terms]
|
265 |
+
pre = [a.offsets for a in self.predicted[i].aspect_terms]
|
266 |
+
manual_common += len([a for a in pre if a in cor])
|
267 |
+
manual_test += len(pre)
|
268 |
+
manual_gold += len(cor)
|
269 |
+
p = manual_common / manual_test if manual_test > 0 else 0.
|
270 |
+
r = manual_common / manual_gold
|
271 |
+
f1 = (1 + (b ** 2)) * p * r / ((p * b ** 2) + r) if p > 0 and r > 0 else 0.
|
272 |
+
return p, r, f1, manual_common, manual_test, manual_gold
|
273 |
+
|
274 |
+
def aspect_extraction_cohen_kappa(self, b=1):
|
275 |
+
manual_gold, manual_test = [], []
|
276 |
+
for i in range(self.size):
|
277 |
+
temp_gold_list = []
|
278 |
+
temp_test_list = []
|
279 |
+
for a in self.correct[i].aspect_terms:
|
280 |
+
temp_gold_list.append(a.term)
|
281 |
+
for a in self.predicted[i].aspect_terms:
|
282 |
+
temp_test_list.append(a.term)
|
283 |
+
manual_gold = manual_gold + sorted(temp_gold_list)
|
284 |
+
manual_test = manual_test + sorted(temp_test_list)
|
285 |
+
|
286 |
+
return cohen_kappa_score(manual_gold, manual_test)
|
287 |
+
|
288 |
+
def get_confusion_matrix_heatmap(self, manual_gold, manual_test, labels, title):
|
289 |
+
confusion = confusion_matrix(manual_gold, manual_test, labels=labels)
|
290 |
+
ax = plt.subplot()
|
291 |
+
sns.heatmap(confusion, annot=True, fmt='g', ax=ax)
|
292 |
+
# labels, title and ticks
|
293 |
+
ax.set_xlabel('Test labels')
|
294 |
+
ax.set_ylabel('Gold labels')
|
295 |
+
ax.set_title(title);
|
296 |
+
ax.xaxis.set_ticklabels(list(labels))
|
297 |
+
ax.yaxis.set_ticklabels(list(labels))
|
298 |
+
plt.show()
|
299 |
+
# Aspect Category Detection
|
300 |
+
def category_detection(self, b=1):
|
301 |
+
manual_common, manual_gold, manual_test = 0., 0., 0.
|
302 |
+
for i in range(self.size):
|
303 |
+
cor = self.correct[i].get_aspect_categories()
|
304 |
+
# Use set to avoid duplicates (i.e., two times the same category)
|
305 |
+
pre = set(self.predicted[i].get_aspect_categories())
|
306 |
+
manual_common += len([c for c in pre if c in cor])
|
307 |
+
manual_test += len(pre)
|
308 |
+
manual_gold += len(cor)
|
309 |
+
p = manual_common / manual_test if manual_test > 0 else 0.
|
310 |
+
r = manual_common / manual_gold
|
311 |
+
f1 = (1 + b ** 2) * p * r / ((p * b ** 2) + r) if p > 0 and r > 0 else 0.
|
312 |
+
return p, r, f1, manual_common, manual_test, manual_gold
|
313 |
+
|
314 |
+
def aspect_category_detection_cohen_kappa(self, b=1):
|
315 |
+
manual_gold, manual_test = [], []
|
316 |
+
for i in range(self.size):
|
317 |
+
temp_gold_list = []
|
318 |
+
temp_test_list = []
|
319 |
+
for a in list(self.correct[i].aspect_categories):
|
320 |
+
temp_gold_list.append(a.term)
|
321 |
+
for a in list(self.predicted[i].aspect_categories):
|
322 |
+
temp_test_list.append(a.term)
|
323 |
+
manual_gold = manual_gold + sorted(temp_gold_list)
|
324 |
+
manual_test = manual_test + sorted(temp_test_list)
|
325 |
+
if len(self.correct[i].aspect_categories) != len(self.predicted[i].aspect_categories):
|
326 |
+
print("ID missed = ", self.correct[i].id)
|
327 |
+
labels = ['ovqat', 'xizmat', 'narx', 'muhit', 'boshqalar']
|
328 |
+
self.get_confusion_matrix_heatmap(manual_gold, manual_test, labels, 'Aspect Category term Confusion Matrix')
|
329 |
+
alpha = cohen_kappa_score(manual_gold, manual_test, labels=labels)
|
330 |
+
return alpha
|
331 |
+
|
332 |
+
def aspect_polarity_estimation(self, b=1):
|
333 |
+
common, relevant, retrieved = 0., 0., 0.
|
334 |
+
for i in range(self.size):
|
335 |
+
cor = [a.polarity for a in self.correct[i].aspect_terms]
|
336 |
+
pre = [a.polarity for a in self.predicted[i].aspect_terms]
|
337 |
+
common += sum([1 for j in range(len(pre)) if pre[j] == cor[j]])
|
338 |
+
retrieved += len(pre)
|
339 |
+
acc = common / retrieved
|
340 |
+
return acc, common, retrieved
|
341 |
+
|
342 |
+
def aspect_polarity_kappa_cohen_estimation(self, b=1):
|
343 |
+
manual_gold, manual_test = [], []
|
344 |
+
for i in range(self.size):
|
345 |
+
for a in self.correct[i].aspect_terms:
|
346 |
+
manual_gold.append(a.polarity)
|
347 |
+
for a in self.predicted[i].aspect_terms:
|
348 |
+
manual_test.append(a.polarity)
|
349 |
+
if len(self.correct[i].aspect_terms) != len(self.predicted[i].aspect_terms):
|
350 |
+
print("ID missed = ", self.correct[i].id)
|
351 |
+
labels = ['positive', 'negative', 'neutral', 'conflict']
|
352 |
+
self.get_confusion_matrix_heatmap(manual_gold, manual_test, labels, 'Aspect Terms Polarity Confusion Matrix')
|
353 |
+
return cohen_kappa_score(manual_gold, manual_test, labels=labels)
|
354 |
+
|
355 |
+
def aspect_category_polarity_estimation(self, b=1):
|
356 |
+
common, relevant, retrieved = 0., 0., 0.
|
357 |
+
for i in range(self.size):
|
358 |
+
cor = [a.polarity for a in self.correct[i].aspect_categories]
|
359 |
+
pre = [a.polarity for a in self.predicted[i].aspect_categories]
|
360 |
+
common += sum([1 for j in range(len(pre)) if pre[j] == cor[j]])
|
361 |
+
retrieved += len(pre)
|
362 |
+
acc = common / retrieved
|
363 |
+
return acc, common, retrieved
|
364 |
+
|
365 |
+
def aspect_category_polarity_kappa_cohen_estimation(self, b=1):
|
366 |
+
manual_gold, manual_test = [], []
|
367 |
+
for i in range(self.size):
|
368 |
+
temp_gold_list = []
|
369 |
+
temp_test_list = []
|
370 |
+
for a in self.correct[i].aspect_categories:
|
371 |
+
manual_gold.append(a.polarity)
|
372 |
+
for a in self.predicted[i].aspect_categories:
|
373 |
+
manual_test.append(a.polarity)
|
374 |
+
if len(self.correct[i].aspect_categories) != len(self.predicted[i].aspect_categories):
|
375 |
+
print("ID missed = ", self.correct[i].id)
|
376 |
+
labels = ['positive', 'negative', 'neutral', 'conflict']
|
377 |
+
self.get_confusion_matrix_heatmap(manual_gold, manual_test, labels, 'Aspect Category Terms Polarity Confusion Matrix')
|
378 |
+
|
379 |
+
return cohen_kappa_score(manual_gold, manual_test)
|
380 |
+
|
381 |
+
|
382 |
+
def main(argv=None):
|
383 |
+
# Parse the input
|
384 |
+
opts, args = getopt.getopt(argv, "hg:dt:om:k:", ["help", "grammar", "train=", "task=", "test="])
|
385 |
+
trainfile, testfile, task = None, None, 1
|
386 |
+
use_msg = 'Use as:\n">>> python baselines.py --train file.xml --task -1|1|2|3|4"\n\nThis will parse a train ' \
|
387 |
+
'set, examine whether is valid, test files, perform ABSA for task 1, 2, 3, or 4 , and write out a file ' \
|
388 |
+
'with the predictions. '
|
389 |
+
|
390 |
+
if len(opts) == 0:
|
391 |
+
sys.exit(use_msg)
|
392 |
+
for opt, arg in opts:
|
393 |
+
if opt in ("-h", "--help"):
|
394 |
+
sys.exit(use_msg)
|
395 |
+
elif opt in ('-t', "--train"):
|
396 |
+
trainfile = arg
|
397 |
+
elif opt in ('-m', "--task"):
|
398 |
+
task = int(arg)
|
399 |
+
|
400 |
+
# Examine if the file is in proper XML format for further use.
|
401 |
+
print('Validating the file...')
|
402 |
+
try:
|
403 |
+
elements, aspects = validate(trainfile)
|
404 |
+
print('PASSED! This corpus has: %d sentences, %d aspect term occurrences, and %d distinct aspect terms.' % (
|
405 |
+
len(elements), len(aspects), len(list(set(aspects)))))
|
406 |
+
except:
|
407 |
+
print("Unexpected error:", sys.exc_info()[0])
|
408 |
+
raise
|
409 |
+
|
410 |
+
# Get the corpus and split into train/test.
|
411 |
+
manual_corpus_gold = Corpus(ET.parse(trainfile).getroot().findall('sentence'))
|
412 |
+
manual_corpus_test = Corpus(ET.parse('rest-manual-test-cohen-kapp.xml').getroot().findall('sentence'))
|
413 |
+
|
414 |
+
if task == 1:
|
415 |
+
print('\n------- Aspect terms --------')
|
416 |
+
print('P = %f -- R = %f -- F1 = %f (#correct: %d, #retrieved-test: '
|
417 |
+
'%d, #relevant-gold: %d)' % Evaluate(manual_corpus_gold.corpus,
|
418 |
+
manual_corpus_test.corpus).aspect_extraction())
|
419 |
+
print('Cohen\'s kappa = ', Evaluate(manual_corpus_gold.corpus, manual_corpus_test.corpus)
|
420 |
+
.aspect_extraction_cohen_kappa())
|
421 |
+
print('Krippendorff nominal metric = ', Evaluate(manual_corpus_gold.corpus, manual_corpus_test.corpus)
|
422 |
+
.krippendorff_alpha_aspect_terms("nominal"))
|
423 |
+
|
424 |
+
if task == 2:
|
425 |
+
print('\nAspect term polarity...')
|
426 |
+
print('Accuracy = %f, #Correct/#All: %d/%d' % Evaluate(manual_corpus_gold.corpus, manual_corpus_test.corpus)
|
427 |
+
.aspect_polarity_estimation())
|
428 |
+
print('Cohen Kappa Accuracy = %f,' % Evaluate(manual_corpus_gold.corpus, manual_corpus_test.corpus)
|
429 |
+
.aspect_polarity_kappa_cohen_estimation())
|
430 |
+
print('Krippendorff nominal metric = ', Evaluate(manual_corpus_gold.corpus, manual_corpus_test.corpus)
|
431 |
+
.krippendorff_alpha_aspect_terms_polarity("nominal"))
|
432 |
+
|
433 |
+
if task == 3:
|
434 |
+
print('\n------- Aspect Categories --------')
|
435 |
+
print('P = %f -- R = %f -- F1 = %f (#correct: %d, #retrieved: '
|
436 |
+
'%d, #relevant: %d)' % Evaluate(manual_corpus_gold.corpus,
|
437 |
+
manual_corpus_test.corpus).category_detection())
|
438 |
+
print('Cohen\'s kappa = ', Evaluate(manual_corpus_gold.corpus, manual_corpus_test.corpus)
|
439 |
+
.aspect_category_detection_cohen_kappa())
|
440 |
+
print('Krippendorff nominal metric = ', Evaluate(manual_corpus_gold.corpus, manual_corpus_test.corpus)
|
441 |
+
.krippendorff_alpha_aspect_categories("nominal"))
|
442 |
+
|
443 |
+
if task == 4:
|
444 |
+
print('\nEstimating aspect category polarity...')
|
445 |
+
print('Accuracy = %f, #Correct/#All: %d/%d' % Evaluate(manual_corpus_gold.corpus, manual_corpus_test.corpus)
|
446 |
+
.aspect_category_polarity_estimation())
|
447 |
+
print('Cohen Kappa Accuracy = %f,' % Evaluate(manual_corpus_gold.corpus, manual_corpus_test.corpus)
|
448 |
+
.aspect_category_polarity_kappa_cohen_estimation())
|
449 |
+
print('Krippendorff nominal metric = ', Evaluate(manual_corpus_gold.corpus, manual_corpus_test.corpus)
|
450 |
+
.krippendorff_alpha_aspect_terms_polarity("nominal"))
|
451 |
+
|
452 |
+
|
453 |
+
if __name__ == "__main__": main(sys.argv[1:])
|