Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # distance_metrics_v3.py
- import math
- import numpy as np
- """
- Python implementation of some distance metrics
- Manhattan
- Euclidian
- Minkowski
- These metrics are used by several higher level
- algorithms, namely KNN, for Machine Learning
- """
- def dManhattan_v0 (pSample1, pSample2):
- bCaution = len(pSample1)==len(pSample2)
- if (bCaution):
- sum = 0
- for idx in range(len(pSample1)):
- e1 = pSample1[idx]
- e2 = pSample2[idx]
- diff = e2-e1
- if(diff<0):
- diff=-1*diff
- # if
- sum+=diff
- # for
- return sum
- # if caution
- return False
- # def dManhattan_v0
- # using numpy
- def dManhattan_np(pS1, pS2):
- pS1 = np.array(pS1)
- pS2 = np.array(pS2)
- diff:np.ndarray = np.abs(pS2-pS1) # array with the differences, component-by-component
- return diff.sum()
- # def dManhattan_np
- def dEuclidian_v0 (pS1, pS2):
- bCaution = len(pS1)==len(pS2)
- if(bCaution):
- sum = 0
- for address in range(len(pS1)):
- e1 = pS1[address]
- e2 = pS2[address]
- diff = (e2-e1)**2
- sum+=diff
- # for
- return math.sqrt(diff)
- # if
- return False
- # def dEuclidian_v0
- # using numpy
- def dEuclidian_np(pS1, pS2):
- pS1=np.array(pS1)
- pS2=np.array(pS2)
- diff = (pS2-pS1)**2
- theSum = diff.sum()
- return math.sqrt(theSum)
- # def dEuclidian_np
- def feedback(pS1, pS2, pMetric, pDescription):
- print("sample1: ", pS1)
- print("sample2: ", pS2)
- distance = pMetric(pS1, pS2)
- print(f"distance by {pDescription} = {distance}")
- # def feedback
- def dMinkowski_np(pS1, pS2, pN=2):
- bCaution = len(pS1)==len(pS2)
- if(bCaution):
- pS1 = np.array(pS1)
- pS2 = np.array(pS2)
- diff = pS2-pS1
- diff = diff**pN
- theSum = diff.sum()
- return theSum**(1/pN)
- # if
- return False
- # def dMinkowski_np
- s1 = [10, 11, 13, 15, 17]
- s2 = [10, 9, 11, 18, 14]
- feedback(s1, s1, dManhattan_v0, "dManhattan_v0")
- feedback(s1, s2, dManhattan_v0, "dManhattan_v0")
- feedback(s1, s1, dManhattan_np, "dManhattan_np")
- feedback(s1, s2, dManhattan_np, "dManhattan_np")
- feedback(s1, s1, dEuclidian_v0, "dEuclidian_v0")
- feedback(s1, s2, dEuclidian_v0, "dEuclidian_v0")
- feedback(s1, s1, dEuclidian_np, "dEuclidian_np")
- feedback(s1, s2, dEuclidian_np, "dEuclidian_np")
- feedback(s1, s1, dMinkowski_np, "dMinkowski_np")
- feedback(s1, s2, dMinkowski_np, "dMinkowski_np")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement