Returns the distance between two vectors.
(v1, v2, method=COSINE)
| 721 | "cosine", "euclidean", "manhattan", "hamming" |
| 722 | |
| 723 | def 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 |
no test coverage detected
searching dependent graphs…