agreement.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. # Natural Language Toolkit: Agreement Metrics
  2. #
  3. # Copyright (C) 2001-2019 NLTK Project
  4. # Author: Tom Lippincott <tom@cs.columbia.edu>
  5. # URL: <http://nltk.org/>
  6. # For license information, see LICENSE.TXT
  7. #
  8. """
  9. Implementations of inter-annotator agreement coefficients surveyed by Artstein
  10. and Poesio (2007), Inter-Coder Agreement for Computational Linguistics.
  11. An agreement coefficient calculates the amount that annotators agreed on label
  12. assignments beyond what is expected by chance.
  13. In defining the AnnotationTask class, we use naming conventions similar to the
  14. paper's terminology. There are three types of objects in an annotation task:
  15. the coders (variables "c" and "C")
  16. the items to be annotated (variables "i" and "I")
  17. the potential categories to be assigned (variables "k" and "K")
  18. Additionally, it is often the case that we don't want to treat two different
  19. labels as complete disagreement, and so the AnnotationTask constructor can also
  20. take a distance metric as a final argument. Distance metrics are simply
  21. functions that take two arguments, and return a value between 0.0 and 1.0
  22. indicating the distance between them. If not supplied, the default is binary
  23. comparison between the arguments.
  24. The simplest way to initialize an AnnotationTask is with a list of triples,
  25. each containing a coder's assignment for one object in the task:
  26. task = AnnotationTask(data=[('c1', '1', 'v1'),('c2', '1', 'v1'),...])
  27. Note that the data list needs to contain the same number of triples for each
  28. individual coder, containing category values for the same set of items.
  29. Alpha (Krippendorff 1980)
  30. Kappa (Cohen 1960)
  31. S (Bennet, Albert and Goldstein 1954)
  32. Pi (Scott 1955)
  33. TODO: Describe handling of multiple coders and missing data
  34. Expected results from the Artstein and Poesio survey paper:
  35. >>> from nltk.metrics.agreement import AnnotationTask
  36. >>> import os.path
  37. >>> t = AnnotationTask(data=[x.split() for x in open(os.path.join(os.path.dirname(__file__), "artstein_poesio_example.txt"))])
  38. >>> t.avg_Ao()
  39. 0.88
  40. >>> t.pi()
  41. 0.7995322418977615...
  42. >>> t.S()
  43. 0.8199999999999998...
  44. This would have returned a wrong value (0.0) in @785fb79 as coders are in
  45. the wrong order. Subsequently, all values for pi(), S(), and kappa() would
  46. have been wrong as they are computed with avg_Ao().
  47. >>> t2 = AnnotationTask(data=[('b','1','stat'),('a','1','stat')])
  48. >>> t2.avg_Ao()
  49. 1.0
  50. The following, of course, also works.
  51. >>> t3 = AnnotationTask(data=[('a','1','othr'),('b','1','othr')])
  52. >>> t3.avg_Ao()
  53. 1.0
  54. """
  55. from __future__ import print_function, unicode_literals, division
  56. import logging
  57. from itertools import groupby
  58. from operator import itemgetter
  59. from six import iteritems
  60. from nltk.probability import FreqDist, ConditionalFreqDist
  61. from nltk.internals import deprecated
  62. from nltk.compat import python_2_unicode_compatible
  63. from nltk.metrics.distance import binary_distance
  64. log = logging.getLogger(__name__)
  65. @python_2_unicode_compatible
  66. class AnnotationTask(object):
  67. """Represents an annotation task, i.e. people assign labels to items.
  68. Notation tries to match notation in Artstein and Poesio (2007).
  69. In general, coders and items can be represented as any hashable object.
  70. Integers, for example, are fine, though strings are more readable.
  71. Labels must support the distance functions applied to them, so e.g.
  72. a string-edit-distance makes no sense if your labels are integers,
  73. whereas interval distance needs numeric values. A notable case of this
  74. is the MASI metric, which requires Python sets.
  75. """
  76. def __init__(self, data=None, distance=binary_distance):
  77. """Initialize an annotation task.
  78. The data argument can be None (to create an empty annotation task) or a sequence of 3-tuples,
  79. each representing a coder's labeling of an item:
  80. (coder,item,label)
  81. The distance argument is a function taking two arguments (labels) and producing a numerical distance.
  82. The distance from a label to itself should be zero:
  83. distance(l,l) = 0
  84. """
  85. self.distance = distance
  86. self.I = set()
  87. self.K = set()
  88. self.C = set()
  89. self.data = []
  90. if data is not None:
  91. self.load_array(data)
  92. def __str__(self):
  93. return "\r\n".join(
  94. map(
  95. lambda x: "%s\t%s\t%s"
  96. % (x['coder'], x['item'].replace('_', "\t"), ",".join(x['labels'])),
  97. self.data,
  98. )
  99. )
  100. def load_array(self, array):
  101. """Load an sequence of annotation results, appending to any data already loaded.
  102. The argument is a sequence of 3-tuples, each representing a coder's labeling of an item:
  103. (coder,item,label)
  104. """
  105. for coder, item, labels in array:
  106. self.C.add(coder)
  107. self.K.add(labels)
  108. self.I.add(item)
  109. self.data.append({'coder': coder, 'labels': labels, 'item': item})
  110. def agr(self, cA, cB, i, data=None):
  111. """Agreement between two coders on a given item
  112. """
  113. data = data or self.data
  114. # cfedermann: we don't know what combination of coder/item will come
  115. # first in x; to avoid StopIteration problems due to assuming an order
  116. # cA,cB, we allow either for k1 and then look up the missing as k2.
  117. k1 = next((x for x in data if x['coder'] in (cA, cB) and x['item'] == i))
  118. if k1['coder'] == cA:
  119. k2 = next((x for x in data if x['coder'] == cB and x['item'] == i))
  120. else:
  121. k2 = next((x for x in data if x['coder'] == cA and x['item'] == i))
  122. ret = 1.0 - float(self.distance(k1['labels'], k2['labels']))
  123. log.debug("Observed agreement between %s and %s on %s: %f", cA, cB, i, ret)
  124. log.debug(
  125. "Distance between \"%r\" and \"%r\": %f",
  126. k1['labels'],
  127. k2['labels'],
  128. 1.0 - ret,
  129. )
  130. return ret
  131. def Nk(self, k):
  132. return float(sum(1 for x in self.data if x['labels'] == k))
  133. def Nik(self, i, k):
  134. return float(sum(1 for x in self.data if x['item'] == i and x['labels'] == k))
  135. def Nck(self, c, k):
  136. return float(sum(1 for x in self.data if x['coder'] == c and x['labels'] == k))
  137. @deprecated('Use Nk, Nik or Nck instead')
  138. def N(self, k=None, i=None, c=None):
  139. """Implements the "n-notation" used in Artstein and Poesio (2007)
  140. """
  141. if k is not None and i is None and c is None:
  142. ret = self.Nk(k)
  143. elif k is not None and i is not None and c is None:
  144. ret = self.Nik(i, k)
  145. elif k is not None and c is not None and i is None:
  146. ret = self.Nck(c, k)
  147. else:
  148. raise ValueError(
  149. "You must pass either i or c, not both! (k=%r,i=%r,c=%r)" % (k, i, c)
  150. )
  151. log.debug("Count on N[%s,%s,%s]: %d", k, i, c, ret)
  152. return ret
  153. def _grouped_data(self, field, data=None):
  154. data = data or self.data
  155. return groupby(sorted(data, key=itemgetter(field)), itemgetter(field))
  156. def Ao(self, cA, cB):
  157. """Observed agreement between two coders on all items.
  158. """
  159. data = self._grouped_data(
  160. 'item', (x for x in self.data if x['coder'] in (cA, cB))
  161. )
  162. ret = sum(self.agr(cA, cB, item, item_data) for item, item_data in data) / len(
  163. self.I
  164. )
  165. log.debug("Observed agreement between %s and %s: %f", cA, cB, ret)
  166. return ret
  167. def _pairwise_average(self, function):
  168. """
  169. Calculates the average of function results for each coder pair
  170. """
  171. total = 0
  172. n = 0
  173. s = self.C.copy()
  174. for cA in self.C:
  175. s.remove(cA)
  176. for cB in s:
  177. total += function(cA, cB)
  178. n += 1
  179. ret = total / n
  180. return ret
  181. def avg_Ao(self):
  182. """Average observed agreement across all coders and items.
  183. """
  184. ret = self._pairwise_average(self.Ao)
  185. log.debug("Average observed agreement: %f", ret)
  186. return ret
  187. def Do_Kw_pairwise(self, cA, cB, max_distance=1.0):
  188. """The observed disagreement for the weighted kappa coefficient.
  189. """
  190. total = 0.0
  191. data = (x for x in self.data if x['coder'] in (cA, cB))
  192. for i, itemdata in self._grouped_data('item', data):
  193. # we should have two items; distance doesn't care which comes first
  194. total += self.distance(next(itemdata)['labels'], next(itemdata)['labels'])
  195. ret = total / (len(self.I) * max_distance)
  196. log.debug("Observed disagreement between %s and %s: %f", cA, cB, ret)
  197. return ret
  198. def Do_Kw(self, max_distance=1.0):
  199. """Averaged over all labelers
  200. """
  201. ret = self._pairwise_average(
  202. lambda cA, cB: self.Do_Kw_pairwise(cA, cB, max_distance)
  203. )
  204. log.debug("Observed disagreement: %f", ret)
  205. return ret
  206. # Agreement Coefficients
  207. def S(self):
  208. """Bennett, Albert and Goldstein 1954
  209. """
  210. Ae = 1.0 / len(self.K)
  211. ret = (self.avg_Ao() - Ae) / (1.0 - Ae)
  212. return ret
  213. def pi(self):
  214. """Scott 1955; here, multi-pi.
  215. Equivalent to K from Siegel and Castellan (1988).
  216. """
  217. total = 0.0
  218. label_freqs = FreqDist(x['labels'] for x in self.data)
  219. for k, f in iteritems(label_freqs):
  220. total += f ** 2
  221. Ae = total / ((len(self.I) * len(self.C)) ** 2)
  222. return (self.avg_Ao() - Ae) / (1 - Ae)
  223. def Ae_kappa(self, cA, cB):
  224. Ae = 0.0
  225. nitems = float(len(self.I))
  226. label_freqs = ConditionalFreqDist((x['labels'], x['coder']) for x in self.data)
  227. for k in label_freqs.conditions():
  228. Ae += (label_freqs[k][cA] / nitems) * (label_freqs[k][cB] / nitems)
  229. return Ae
  230. def kappa_pairwise(self, cA, cB):
  231. """
  232. """
  233. Ae = self.Ae_kappa(cA, cB)
  234. ret = (self.Ao(cA, cB) - Ae) / (1.0 - Ae)
  235. log.debug("Expected agreement between %s and %s: %f", cA, cB, Ae)
  236. return ret
  237. def kappa(self):
  238. """Cohen 1960
  239. Averages naively over kappas for each coder pair.
  240. """
  241. return self._pairwise_average(self.kappa_pairwise)
  242. def multi_kappa(self):
  243. """Davies and Fleiss 1982
  244. Averages over observed and expected agreements for each coder pair.
  245. """
  246. Ae = self._pairwise_average(self.Ae_kappa)
  247. return (self.avg_Ao() - Ae) / (1.0 - Ae)
  248. def Disagreement(self, label_freqs):
  249. total_labels = sum(label_freqs.values())
  250. pairs = 0.0
  251. for j, nj in iteritems(label_freqs):
  252. for l, nl in iteritems(label_freqs):
  253. pairs += float(nj * nl) * self.distance(l, j)
  254. return 1.0 * pairs / (total_labels * (total_labels - 1))
  255. def alpha(self):
  256. """Krippendorff 1980
  257. """
  258. # check for degenerate cases
  259. if len(self.K) == 0:
  260. raise ValueError("Cannot calculate alpha, no data present!")
  261. if len(self.K) == 1:
  262. log.debug("Only one annotation value, allpha returning 1.")
  263. return 1
  264. if len(self.C) == 1 and len(self.I) == 1:
  265. raise ValueError("Cannot calculate alpha, only one coder and item present!")
  266. total_disagreement = 0.0
  267. total_ratings = 0
  268. all_valid_labels_freq = FreqDist([])
  269. total_do = 0.0 # Total observed disagreement for all items.
  270. for i, itemdata in self._grouped_data('item'):
  271. label_freqs = FreqDist(x['labels'] for x in itemdata)
  272. labels_count = sum(label_freqs.values())
  273. if labels_count < 2:
  274. # Ignore the item.
  275. continue
  276. all_valid_labels_freq += label_freqs
  277. total_do += self.Disagreement(label_freqs) * labels_count
  278. do = total_do / sum(all_valid_labels_freq.values())
  279. de = self.Disagreement(all_valid_labels_freq) # Expected disagreement.
  280. k_alpha = 1.0 - do / de
  281. return k_alpha
  282. def weighted_kappa_pairwise(self, cA, cB, max_distance=1.0):
  283. """Cohen 1968
  284. """
  285. total = 0.0
  286. label_freqs = ConditionalFreqDist(
  287. (x['coder'], x['labels']) for x in self.data if x['coder'] in (cA, cB)
  288. )
  289. for j in self.K:
  290. for l in self.K:
  291. total += label_freqs[cA][j] * label_freqs[cB][l] * self.distance(j, l)
  292. De = total / (max_distance * pow(len(self.I), 2))
  293. log.debug("Expected disagreement between %s and %s: %f", cA, cB, De)
  294. Do = self.Do_Kw_pairwise(cA, cB)
  295. ret = 1.0 - (Do / De)
  296. return ret
  297. def weighted_kappa(self, max_distance=1.0):
  298. """Cohen 1968
  299. """
  300. return self._pairwise_average(
  301. lambda cA, cB: self.weighted_kappa_pairwise(cA, cB, max_distance)
  302. )
  303. if __name__ == '__main__':
  304. import re
  305. import optparse
  306. from nltk.metrics import distance
  307. # process command-line arguments
  308. parser = optparse.OptionParser()
  309. parser.add_option(
  310. "-d",
  311. "--distance",
  312. dest="distance",
  313. default="binary_distance",
  314. help="distance metric to use",
  315. )
  316. parser.add_option(
  317. "-a",
  318. "--agreement",
  319. dest="agreement",
  320. default="kappa",
  321. help="agreement coefficient to calculate",
  322. )
  323. parser.add_option(
  324. "-e",
  325. "--exclude",
  326. dest="exclude",
  327. action="append",
  328. default=[],
  329. help="coder names to exclude (may be specified multiple times)",
  330. )
  331. parser.add_option(
  332. "-i",
  333. "--include",
  334. dest="include",
  335. action="append",
  336. default=[],
  337. help="coder names to include, same format as exclude",
  338. )
  339. parser.add_option(
  340. "-f",
  341. "--file",
  342. dest="file",
  343. help="file to read labelings from, each line with three columns: 'labeler item labels'",
  344. )
  345. parser.add_option(
  346. "-v",
  347. "--verbose",
  348. dest="verbose",
  349. default='0',
  350. help="how much debugging to print on stderr (0-4)",
  351. )
  352. parser.add_option(
  353. "-c",
  354. "--columnsep",
  355. dest="columnsep",
  356. default="\t",
  357. help="char/string that separates the three columns in the file, defaults to tab",
  358. )
  359. parser.add_option(
  360. "-l",
  361. "--labelsep",
  362. dest="labelsep",
  363. default=",",
  364. help="char/string that separates labels (if labelers can assign more than one), defaults to comma",
  365. )
  366. parser.add_option(
  367. "-p",
  368. "--presence",
  369. dest="presence",
  370. default=None,
  371. help="convert each labeling into 1 or 0, based on presence of LABEL",
  372. )
  373. parser.add_option(
  374. "-T",
  375. "--thorough",
  376. dest="thorough",
  377. default=False,
  378. action="store_true",
  379. help="calculate agreement for every subset of the annotators",
  380. )
  381. (options, remainder) = parser.parse_args()
  382. if not options.file:
  383. parser.print_help()
  384. exit()
  385. logging.basicConfig(level=50 - 10 * int(options.verbose))
  386. # read in data from the specified file
  387. data = []
  388. with open(options.file, 'r') as infile:
  389. for l in infile:
  390. toks = l.split(options.columnsep)
  391. coder, object_, labels = (
  392. toks[0],
  393. str(toks[1:-1]),
  394. frozenset(toks[-1].strip().split(options.labelsep)),
  395. )
  396. if (
  397. (options.include == options.exclude)
  398. or (len(options.include) > 0 and coder in options.include)
  399. or (len(options.exclude) > 0 and coder not in options.exclude)
  400. ):
  401. data.append((coder, object_, labels))
  402. if options.presence:
  403. task = AnnotationTask(
  404. data, getattr(distance, options.distance)(options.presence)
  405. )
  406. else:
  407. task = AnnotationTask(data, getattr(distance, options.distance))
  408. if options.thorough:
  409. pass
  410. else:
  411. print(getattr(task, options.agreement)())
  412. logging.shutdown()