Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

manhattan distance and jaccard similarity added #8

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions grasp.py
Original file line number Diff line number Diff line change
Expand Up @@ -1799,6 +1799,11 @@ def distance(v1, v2):
"""
return sum(pow(v1.get(f, 0.0) - v2.get(f, 0.0), 2) for f in features((v1, v2))) ** 0.5

def manhattandistance(v1, v2):
""" Returns the manhattan distance of the given vectors.
"""
return sum(abs(v1.get(f, 0.0) - v2.get(f, 0.0)) for f in features((v1, v2)))

def dot(v1, v2):
""" Returns the dot product of the given vectors.
"""
Expand All @@ -1814,6 +1819,11 @@ def cos(v1, v2):
"""
return 1 - dot(v1, v2) / (norm(v1) * norm(v2) or 1) # cosine distance

def jaccard (v1, v2):
""" Returns the jaccard similarity coefficient of the given vectors (0.0-1.0).
"""
return len([f for f in features((v1,v2)) if v1.get(f, 0.0) == v2.get(f, 0.0)]) / float(len(v1))

def knn(v, vectors=[], k=3, distance=cos):
""" Returns the k nearest neighbors from the given list of vectors.
"""
Expand Down