| 1421 | return c |
| 1422 | |
| 1423 | class DistanceMap(object): |
| 1424 | |
| 1425 | def __init__(self, method=COSINE): |
| 1426 | """ A lazy map of cached distances between Vector objects. |
| 1427 | """ |
| 1428 | self.method = method |
| 1429 | self._cache = {} |
| 1430 | |
| 1431 | def __call__(self, v1, v2): |
| 1432 | return self.distance(v1, v2) |
| 1433 | |
| 1434 | def distance(self, v1, v2): |
| 1435 | """ Returns the cached distance between two vectors. |
| 1436 | """ |
| 1437 | try: |
| 1438 | # Two Vector objects for which the distance was already calculated. |
| 1439 | d = self._cache[(v1.id, v2.id)] |
| 1440 | except KeyError: |
| 1441 | # Two Vector objects for which the distance has not been calculated. |
| 1442 | d = self._cache[(v1.id, v2.id)] = distance(v1, v2, method=self.method) |
| 1443 | except AttributeError: |
| 1444 | # No "id" property, so not a Vector but a plain dict. |
| 1445 | d = distance(v1, v2, method=self.method) |
| 1446 | return d |
| 1447 | |
| 1448 | def cluster(method=KMEANS, vectors=[], **kwargs): |
| 1449 | """ Clusters the given list of vectors using the k-means or hierarchical algorithm. |