distance.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. # -*- coding: utf-8 -*-
  2. # Natural Language Toolkit: Distance Metrics
  3. #
  4. # Copyright (C) 2001-2020 NLTK Project
  5. # Author: Edward Loper <edloper@gmail.com>
  6. # Steven Bird <stevenbird1@gmail.com>
  7. # Tom Lippincott <tom@cs.columbia.edu>
  8. # URL: <http://nltk.org/>
  9. # For license information, see LICENSE.TXT
  10. #
  11. """
  12. Distance Metrics.
  13. Compute the distance between two items (usually strings).
  14. As metrics, they must satisfy the following three requirements:
  15. 1. d(a, a) = 0
  16. 2. d(a, b) >= 0
  17. 3. d(a, c) <= d(a, b) + d(b, c)
  18. """
  19. import warnings
  20. import operator
  21. def _edit_dist_init(len1, len2):
  22. lev = []
  23. for i in range(len1):
  24. lev.append([0] * len2) # initialize 2D array to zero
  25. for i in range(len1):
  26. lev[i][0] = i # column 0: 0,1,2,3,4,...
  27. for j in range(len2):
  28. lev[0][j] = j # row 0: 0,1,2,3,4,...
  29. return lev
  30. def _edit_dist_step(lev, i, j, s1, s2, substitution_cost=1, transpositions=False):
  31. c1 = s1[i - 1]
  32. c2 = s2[j - 1]
  33. # skipping a character in s1
  34. a = lev[i - 1][j] + 1
  35. # skipping a character in s2
  36. b = lev[i][j - 1] + 1
  37. # substitution
  38. c = lev[i - 1][j - 1] + (substitution_cost if c1 != c2 else 0)
  39. # transposition
  40. d = c + 1 # never picked by default
  41. if transpositions and i > 1 and j > 1:
  42. if s1[i - 2] == c2 and s2[j - 2] == c1:
  43. d = lev[i - 2][j - 2] + 1
  44. # pick the cheapest
  45. lev[i][j] = min(a, b, c, d)
  46. def edit_distance(s1, s2, substitution_cost=1, transpositions=False):
  47. """
  48. Calculate the Levenshtein edit-distance between two strings.
  49. The edit distance is the number of characters that need to be
  50. substituted, inserted, or deleted, to transform s1 into s2. For
  51. example, transforming "rain" to "shine" requires three steps,
  52. consisting of two substitutions and one insertion:
  53. "rain" -> "sain" -> "shin" -> "shine". These operations could have
  54. been done in other orders, but at least three steps are needed.
  55. Allows specifying the cost of substitution edits (e.g., "a" -> "b"),
  56. because sometimes it makes sense to assign greater penalties to
  57. substitutions.
  58. This also optionally allows transposition edits (e.g., "ab" -> "ba"),
  59. though this is disabled by default.
  60. :param s1, s2: The strings to be analysed
  61. :param transpositions: Whether to allow transposition edits
  62. :type s1: str
  63. :type s2: str
  64. :type substitution_cost: int
  65. :type transpositions: bool
  66. :rtype int
  67. """
  68. # set up a 2-D array
  69. len1 = len(s1)
  70. len2 = len(s2)
  71. lev = _edit_dist_init(len1 + 1, len2 + 1)
  72. # iterate over the array
  73. for i in range(len1):
  74. for j in range(len2):
  75. _edit_dist_step(
  76. lev,
  77. i + 1,
  78. j + 1,
  79. s1,
  80. s2,
  81. substitution_cost=substitution_cost,
  82. transpositions=transpositions,
  83. )
  84. return lev[len1][len2]
  85. def _edit_dist_backtrace(lev):
  86. i, j = len(lev) - 1, len(lev[0]) - 1
  87. alignment = [(i, j)]
  88. while (i, j) != (0, 0):
  89. directions = [
  90. (i - 1, j), # skip s1
  91. (i, j - 1), # skip s2
  92. (i - 1, j - 1), # substitution
  93. ]
  94. direction_costs = (
  95. (lev[i][j] if (i >= 0 and j >= 0) else float("inf"), (i, j))
  96. for i, j in directions
  97. )
  98. _, (i, j) = min(direction_costs, key=operator.itemgetter(0))
  99. alignment.append((i, j))
  100. return list(reversed(alignment))
  101. def edit_distance_align(s1, s2, substitution_cost=1):
  102. """
  103. Calculate the minimum Levenshtein edit-distance based alignment
  104. mapping between two strings. The alignment finds the mapping
  105. from string s1 to s2 that minimizes the edit distance cost.
  106. For example, mapping "rain" to "shine" would involve 2
  107. substitutions, 2 matches and an insertion resulting in
  108. the following mapping:
  109. [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (4, 5)]
  110. NB: (0, 0) is the start state without any letters associated
  111. See more: https://web.stanford.edu/class/cs124/lec/med.pdf
  112. In case of multiple valid minimum-distance alignments, the
  113. backtrace has the following operation precedence:
  114. 1. Skip s1 character
  115. 2. Skip s2 character
  116. 3. Substitute s1 and s2 characters
  117. The backtrace is carried out in reverse string order.
  118. This function does not support transposition.
  119. :param s1, s2: The strings to be aligned
  120. :type s1: str
  121. :type s2: str
  122. :type substitution_cost: int
  123. :rtype List[Tuple(int, int)]
  124. """
  125. # set up a 2-D array
  126. len1 = len(s1)
  127. len2 = len(s2)
  128. lev = _edit_dist_init(len1 + 1, len2 + 1)
  129. # iterate over the array
  130. for i in range(len1):
  131. for j in range(len2):
  132. _edit_dist_step(
  133. lev,
  134. i + 1,
  135. j + 1,
  136. s1,
  137. s2,
  138. substitution_cost=substitution_cost,
  139. transpositions=False,
  140. )
  141. # backtrace to find alignment
  142. alignment = _edit_dist_backtrace(lev)
  143. return alignment
  144. def binary_distance(label1, label2):
  145. """Simple equality test.
  146. 0.0 if the labels are identical, 1.0 if they are different.
  147. >>> from nltk.metrics import binary_distance
  148. >>> binary_distance(1,1)
  149. 0.0
  150. >>> binary_distance(1,3)
  151. 1.0
  152. """
  153. return 0.0 if label1 == label2 else 1.0
  154. def jaccard_distance(label1, label2):
  155. """Distance metric comparing set-similarity.
  156. """
  157. return (len(label1.union(label2)) - len(label1.intersection(label2))) / len(
  158. label1.union(label2)
  159. )
  160. def masi_distance(label1, label2):
  161. """Distance metric that takes into account partial agreement when multiple
  162. labels are assigned.
  163. >>> from nltk.metrics import masi_distance
  164. >>> masi_distance(set([1, 2]), set([1, 2, 3, 4]))
  165. 0.665
  166. Passonneau 2006, Measuring Agreement on Set-Valued Items (MASI)
  167. for Semantic and Pragmatic Annotation.
  168. """
  169. len_intersection = len(label1.intersection(label2))
  170. len_union = len(label1.union(label2))
  171. len_label1 = len(label1)
  172. len_label2 = len(label2)
  173. if len_label1 == len_label2 and len_label1 == len_intersection:
  174. m = 1
  175. elif len_intersection == min(len_label1, len_label2):
  176. m = 0.67
  177. elif len_intersection > 0:
  178. m = 0.33
  179. else:
  180. m = 0
  181. return 1 - len_intersection / len_union * m
  182. def interval_distance(label1, label2):
  183. """Krippendorff's interval distance metric
  184. >>> from nltk.metrics import interval_distance
  185. >>> interval_distance(1,10)
  186. 81
  187. Krippendorff 1980, Content Analysis: An Introduction to its Methodology
  188. """
  189. try:
  190. return pow(label1 - label2, 2)
  191. # return pow(list(label1)[0]-list(label2)[0],2)
  192. except:
  193. print("non-numeric labels not supported with interval distance")
  194. def presence(label):
  195. """Higher-order function to test presence of a given label
  196. """
  197. return lambda x, y: 1.0 * ((label in x) == (label in y))
  198. def fractional_presence(label):
  199. return (
  200. lambda x, y: abs(((1.0 / len(x)) - (1.0 / len(y))))
  201. * (label in x and label in y)
  202. or 0.0 * (label not in x and label not in y)
  203. or abs((1.0 / len(x))) * (label in x and label not in y)
  204. or ((1.0 / len(y))) * (label not in x and label in y)
  205. )
  206. def custom_distance(file):
  207. data = {}
  208. with open(file, "r") as infile:
  209. for l in infile:
  210. labelA, labelB, dist = l.strip().split("\t")
  211. labelA = frozenset([labelA])
  212. labelB = frozenset([labelB])
  213. data[frozenset([labelA, labelB])] = float(dist)
  214. return lambda x, y: data[frozenset([x, y])]
  215. def jaro_similarity(s1, s2):
  216. """
  217. Computes the Jaro similarity between 2 sequences from:
  218. Matthew A. Jaro (1989). Advances in record linkage methodology
  219. as applied to the 1985 census of Tampa Florida. Journal of the
  220. American Statistical Association. 84 (406): 414-20.
  221. The Jaro distance between is the min no. of single-character transpositions
  222. required to change one word into another. The Jaro similarity formula from
  223. https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance :
  224. jaro_sim = 0 if m = 0 else 1/3 * (m/|s_1| + m/s_2 + (m-t)/m)
  225. where:
  226. - |s_i| is the length of string s_i
  227. - m is the no. of matching characters
  228. - t is the half no. of possible transpositions.
  229. """
  230. # First, store the length of the strings
  231. # because they will be re-used several times.
  232. len_s1, len_s2 = len(s1), len(s2)
  233. # The upper bound of the distance for being a matched character.
  234. match_bound = max(len_s1, len_s2) // 2 - 1
  235. # Initialize the counts for matches and transpositions.
  236. matches = 0 # no.of matched characters in s1 and s2
  237. transpositions = 0 # no. of transpositions between s1 and s2
  238. flagged_1 = [] # positions in s1 which are matches to some character in s2
  239. flagged_2 = [] # positions in s2 which are matches to some character in s1
  240. # Iterate through sequences, check for matches and compute transpositions.
  241. for i in range(len_s1): # Iterate through each character.
  242. upperbound = min(i + match_bound, len_s2 - 1)
  243. lowerbound = max(0, i - match_bound)
  244. for j in range(lowerbound, upperbound + 1):
  245. if s1[i] == s2[j] and j not in flagged_2:
  246. matches += 1
  247. flagged_1.append(i)
  248. flagged_2.append(j)
  249. break
  250. flagged_2.sort()
  251. for i, j in zip(flagged_1, flagged_2):
  252. if s1[i] != s2[j]:
  253. transpositions += 1
  254. if matches == 0:
  255. return 0
  256. else:
  257. return (
  258. 1
  259. / 3
  260. * (
  261. matches / len_s1
  262. + matches / len_s2
  263. + (matches - transpositions // 2) / matches
  264. )
  265. )
  266. def jaro_winkler_similarity(s1, s2, p=0.1, max_l=4):
  267. """
  268. The Jaro Winkler distance is an extension of the Jaro similarity in:
  269. William E. Winkler. 1990. String Comparator Metrics and Enhanced
  270. Decision Rules in the Fellegi-Sunter Model of Record Linkage.
  271. Proceedings of the Section on Survey Research Methods.
  272. American Statistical Association: 354-359.
  273. such that:
  274. jaro_winkler_sim = jaro_sim + ( l * p * (1 - jaro_sim) )
  275. where,
  276. - jaro_sim is the output from the Jaro Similarity,
  277. see jaro_similarity()
  278. - l is the length of common prefix at the start of the string
  279. - this implementation provides an upperbound for the l value
  280. to keep the prefixes.A common value of this upperbound is 4.
  281. - p is the constant scaling factor to overweigh common prefixes.
  282. The Jaro-Winkler similarity will fall within the [0, 1] bound,
  283. given that max(p)<=0.25 , default is p=0.1 in Winkler (1990)
  284. Test using outputs from https://www.census.gov/srd/papers/pdf/rr93-8.pdf
  285. from "Table 5 Comparison of String Comparators Rescaled between 0 and 1"
  286. >>> winkler_examples = [("billy", "billy"), ("billy", "bill"), ("billy", "blily"),
  287. ... ("massie", "massey"), ("yvette", "yevett"), ("billy", "bolly"), ("dwayne", "duane"),
  288. ... ("dixon", "dickson"), ("billy", "susan")]
  289. >>> winkler_scores = [1.000, 0.967, 0.947, 0.944, 0.911, 0.893, 0.858, 0.853, 0.000]
  290. >>> jaro_scores = [1.000, 0.933, 0.933, 0.889, 0.889, 0.867, 0.822, 0.790, 0.000]
  291. # One way to match the values on the Winkler's paper is to provide a different
  292. # p scaling factor for different pairs of strings, e.g.
  293. >>> p_factors = [0.1, 0.125, 0.20, 0.125, 0.20, 0.20, 0.20, 0.15, 0.1]
  294. >>> for (s1, s2), jscore, wscore, p in zip(winkler_examples, jaro_scores, winkler_scores, p_factors):
  295. ... assert round(jaro_similarity(s1, s2), 3) == jscore
  296. ... assert round(jaro_winkler_similarity(s1, s2, p=p), 3) == wscore
  297. Test using outputs from https://www.census.gov/srd/papers/pdf/rr94-5.pdf from
  298. "Table 2.1. Comparison of String Comparators Using Last Names, First Names, and Street Names"
  299. >>> winkler_examples = [('SHACKLEFORD', 'SHACKELFORD'), ('DUNNINGHAM', 'CUNNIGHAM'),
  300. ... ('NICHLESON', 'NICHULSON'), ('JONES', 'JOHNSON'), ('MASSEY', 'MASSIE'),
  301. ... ('ABROMS', 'ABRAMS'), ('HARDIN', 'MARTINEZ'), ('ITMAN', 'SMITH'),
  302. ... ('JERALDINE', 'GERALDINE'), ('MARHTA', 'MARTHA'), ('MICHELLE', 'MICHAEL'),
  303. ... ('JULIES', 'JULIUS'), ('TANYA', 'TONYA'), ('DWAYNE', 'DUANE'), ('SEAN', 'SUSAN'),
  304. ... ('JON', 'JOHN'), ('JON', 'JAN'), ('BROOKHAVEN', 'BRROKHAVEN'),
  305. ... ('BROOK HALLOW', 'BROOK HLLW'), ('DECATUR', 'DECATIR'), ('FITZRUREITER', 'FITZENREITER'),
  306. ... ('HIGBEE', 'HIGHEE'), ('HIGBEE', 'HIGVEE'), ('LACURA', 'LOCURA'), ('IOWA', 'IONA'), ('1ST', 'IST')]
  307. >>> jaro_scores = [0.970, 0.896, 0.926, 0.790, 0.889, 0.889, 0.722, 0.467, 0.926,
  308. ... 0.944, 0.869, 0.889, 0.867, 0.822, 0.783, 0.917, 0.000, 0.933, 0.944, 0.905,
  309. ... 0.856, 0.889, 0.889, 0.889, 0.833, 0.000]
  310. >>> winkler_scores = [0.982, 0.896, 0.956, 0.832, 0.944, 0.922, 0.722, 0.467, 0.926,
  311. ... 0.961, 0.921, 0.933, 0.880, 0.858, 0.805, 0.933, 0.000, 0.947, 0.967, 0.943,
  312. ... 0.913, 0.922, 0.922, 0.900, 0.867, 0.000]
  313. # One way to match the values on the Winkler's paper is to provide a different
  314. # p scaling factor for different pairs of strings, e.g.
  315. >>> p_factors = [0.1, 0.1, 0.1, 0.1, 0.125, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.20,
  316. ... 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
  317. >>> for (s1, s2), jscore, wscore, p in zip(winkler_examples, jaro_scores, winkler_scores, p_factors):
  318. ... if (s1, s2) in [('JON', 'JAN'), ('1ST', 'IST')]:
  319. ... continue # Skip bad examples from the paper.
  320. ... assert round(jaro_similarity(s1, s2), 3) == jscore
  321. ... assert round(jaro_winkler_similarity(s1, s2, p=p), 3) == wscore
  322. This test-case proves that the output of Jaro-Winkler similarity depends on
  323. the product l * p and not on the product max_l * p. Here the product max_l * p > 1
  324. however the product l * p <= 1
  325. >>> round(jaro_winkler_similarity('TANYA', 'TONYA', p=0.1, max_l=100), 3)
  326. 0.88
  327. """
  328. # To ensure that the output of the Jaro-Winkler's similarity
  329. # falls between [0,1], the product of l * p needs to be
  330. # also fall between [0,1].
  331. if not 0 <= max_l * p <= 1:
  332. warnings.warn(
  333. str(
  334. "The product `max_l * p` might not fall between [0,1]."
  335. "Jaro-Winkler similarity might not be between 0 and 1."
  336. )
  337. )
  338. # Compute the Jaro similarity
  339. jaro_sim = jaro_similarity(s1, s2)
  340. # Initialize the upper bound for the no. of prefixes.
  341. # if user did not pre-define the upperbound,
  342. # use shorter length between s1 and s2
  343. # Compute the prefix matches.
  344. l = 0
  345. # zip() will automatically loop until the end of shorter string.
  346. for s1_i, s2_i in zip(s1, s2):
  347. if s1_i == s2_i:
  348. l += 1
  349. else:
  350. break
  351. if l == max_l:
  352. break
  353. # Return the similarity value as described in docstring.
  354. return jaro_sim + (l * p * (1 - jaro_sim))
  355. def demo():
  356. string_distance_examples = [
  357. ("rain", "shine"),
  358. ("abcdef", "acbdef"),
  359. ("language", "lnaguaeg"),
  360. ("language", "lnaugage"),
  361. ("language", "lngauage"),
  362. ]
  363. for s1, s2 in string_distance_examples:
  364. print("Edit distance btwn '%s' and '%s':" % (s1, s2), edit_distance(s1, s2))
  365. print(
  366. "Edit dist with transpositions btwn '%s' and '%s':" % (s1, s2),
  367. edit_distance(s1, s2, transpositions=True),
  368. )
  369. print("Jaro similarity btwn '%s' and '%s':" % (s1, s2), jaro_similarity(s1, s2))
  370. print(
  371. "Jaro-Winkler similarity btwn '%s' and '%s':" % (s1, s2),
  372. jaro_winkler_similarity(s1, s2),
  373. )
  374. print(
  375. "Jaro-Winkler distance btwn '%s' and '%s':" % (s1, s2),
  376. 1 - jaro_winkler_similarity(s1, s2),
  377. )
  378. s1 = set([1, 2, 3, 4])
  379. s2 = set([3, 4, 5])
  380. print("s1:", s1)
  381. print("s2:", s2)
  382. print("Binary distance:", binary_distance(s1, s2))
  383. print("Jaccard distance:", jaccard_distance(s1, s2))
  384. print("MASI distance:", masi_distance(s1, s2))
  385. if __name__ == "__main__":
  386. demo()