MCPcopy Index your code
hub / github.com/clips/pattern / distance

Function distance

pattern/vector/__init__.py:723–738  ·  view source on GitHub ↗

Returns the distance between two vectors.

(v1, v2, method=COSINE)

Source from the content-addressed store, hash-verified

721 "cosine", "euclidean", "manhattan", "hamming"
722
723def distance(v1, v2, method=COSINE):
724 """ Returns the distance between two vectors.
725 """
726 if method == COSINE:
727 return 1 - cosine_similarity(v1, v2)
728 if method == EUCLIDEAN: # Squared Euclidean distance is used (1.5x faster).
729 return sum((v1.get(w, 0) - v2.get(w, 0)) ** 2 for w in set(chain(v1, v2)))
730 if method == MANHATTAN:
731 return sum(abs(v1.get(w, 0) - v2.get(w, 0)) for w in set(chain(v1, v2)))
732 if method == HAMMING:
733 d = sum(not (w in v1 and w in v2 and v1[w] == v2[w]) for w in set(chain(v1, v2)))
734 d = d / float(max(len(v1), len(v2)) or 1)
735 return d
736 if isinstance(method, type(distance)):
737 # Given method is a function of the form: distance(v1, v2) => float.
738 return method(v1, v2)
739
740_distance = distance
741

Callers 5

distanceMethod · 0.85
distanceMethod · 0.85
k_meansFunction · 0.85
kmppFunction · 0.85
classifyMethod · 0.85

Calls 5

cosine_similarityFunction · 0.85
sumFunction · 0.85
lenFunction · 0.85
absFunction · 0.50
getMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…