Advertisement
am_dot_com

IA 2022-11-16

Nov 16th, 2022 (edited)
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. # distance_metrics_v3.py
  2. import math
  3.  
  4. import numpy as np
  5.  
  6. """
  7. Python implementation of some distance metrics
  8. Manhattan
  9. Euclidian
  10. Minkowski
  11.  
  12. These metrics are used by several higher level
  13. algorithms, namely KNN, for Machine Learning
  14. """
  15.  
  16. def dManhattan_v0 (pSample1, pSample2):
  17. bCaution = len(pSample1)==len(pSample2)
  18. if (bCaution):
  19. sum = 0
  20. for idx in range(len(pSample1)):
  21. e1 = pSample1[idx]
  22. e2 = pSample2[idx]
  23. diff = e2-e1
  24. if(diff<0):
  25. diff=-1*diff
  26. # if
  27. sum+=diff
  28. # for
  29. return sum
  30. # if caution
  31. return False
  32. # def dManhattan_v0
  33.  
  34. # using numpy
  35. def dManhattan_np(pS1, pS2):
  36. pS1 = np.array(pS1)
  37. pS2 = np.array(pS2)
  38. diff:np.ndarray = np.abs(pS2-pS1) # array with the differences, component-by-component
  39. return diff.sum()
  40. # def dManhattan_np
  41.  
  42. def dEuclidian_v0 (pS1, pS2):
  43. bCaution = len(pS1)==len(pS2)
  44. if(bCaution):
  45. sum = 0
  46. for address in range(len(pS1)):
  47. e1 = pS1[address]
  48. e2 = pS2[address]
  49. diff = (e2-e1)**2
  50. sum+=diff
  51. # for
  52. return math.sqrt(diff)
  53. # if
  54. return False
  55. # def dEuclidian_v0
  56.  
  57. # using numpy
  58. def dEuclidian_np(pS1, pS2):
  59. pS1=np.array(pS1)
  60. pS2=np.array(pS2)
  61. diff = (pS2-pS1)**2
  62. theSum = diff.sum()
  63. return math.sqrt(theSum)
  64. # def dEuclidian_np
  65.  
  66. def feedback(pS1, pS2, pMetric, pDescription):
  67. print("sample1: ", pS1)
  68. print("sample2: ", pS2)
  69. distance = pMetric(pS1, pS2)
  70. print(f"distance by {pDescription} = {distance}")
  71. # def feedback
  72.  
  73. def dMinkowski_np(pS1, pS2, pN=2):
  74. bCaution = len(pS1)==len(pS2)
  75. if(bCaution):
  76. pS1 = np.array(pS1)
  77. pS2 = np.array(pS2)
  78. diff = pS2-pS1
  79. diff = diff**pN
  80. theSum = diff.sum()
  81. return theSum**(1/pN)
  82. # if
  83. return False
  84. # def dMinkowski_np
  85.  
  86. s1 = [10, 11, 13, 15, 17]
  87. s2 = [10, 9, 11, 18, 14]
  88. feedback(s1, s1, dManhattan_v0, "dManhattan_v0")
  89. feedback(s1, s2, dManhattan_v0, "dManhattan_v0")
  90.  
  91. feedback(s1, s1, dManhattan_np, "dManhattan_np")
  92. feedback(s1, s2, dManhattan_np, "dManhattan_np")
  93.  
  94. feedback(s1, s1, dEuclidian_v0, "dEuclidian_v0")
  95. feedback(s1, s2, dEuclidian_v0, "dEuclidian_v0")
  96.  
  97. feedback(s1, s1, dEuclidian_np, "dEuclidian_np")
  98. feedback(s1, s2, dEuclidian_np, "dEuclidian_np")
  99.  
  100. feedback(s1, s1, dMinkowski_np, "dMinkowski_np")
  101. feedback(s1, s2, dMinkowski_np, "dMinkowski_np")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement