KMeansClustering no longer works with custom objects. #15
Copy link
Copy link
Open
Labels
Milestone
Description
The following code gives an error:
from cluster import KMeansClustering
from os import urandom
from pprint import pprint
from random import randint
class ObjectWithMetadata(object):
def __init__(self, value):
self.value = value
self.uid = urandom(10).encode('base64').strip()
def __repr__(self):
return 'ObjectWithMetadata({!r}, {!r}'.format(self.value, self.uid)
data = [ObjectWithMetadata(randint(0, 1000))
for _ in range(200)]
cl = KMeansClustering(data, lambda x, y: float(abs(x.value-y.value)))
clustered = cl.getclusters(10)
pprint(clustered)
print(len(clustered))
The error:
Traceback (most recent call last):
File "metadata.py", line 21, in <module>
clustered = cl.getclusters(10)
File "/home/exhuma/work/github/python-cluster/cluster/method/kmeans.py", line 109, in getclusters
res = self.assign_item(item, cluster)
File "/home/exhuma/work/github/python-cluster/cluster/method/kmeans.py", line 124, in assign_item
if self.distance(item, centroid(cluster)) < self.distance(
File "/home/exhuma/work/github/python-cluster/cluster/util.py", line 175, in centroid
for i in range(len(data[0])):
TypeError: object of type 'ObjectWithMetadata' has no len()
Reactions are currently unavailable
Activity
exhuma commentedon Aug 24, 2014
With the current implementation of
KMeansClustering, solving this would get quite messy. Running the K-Means method requires 3 functions which strongly depend on the nature of items:It would make more sense to enforce non-tuple data elements to be a subclass of an ABC which has the above methods as abstract. Where
distancecould be implemented as__sub__andequalitycould be implemented as__eq__.I will follow semantic versioning, and as this would change the external API, I will postpone this for
2.0centroid implementation with zip.
anupamme commentedon May 10, 2017
I believe HierarchicalClustering also does not work with custom objects e.g. I have following code:
where,
salary_head_probables_listis a list of custom object_find_squared_distancereturns of type floatI am getting this error trace:
exhuma commentedon May 10, 2017
Thanks for raising this. I have to admit that this package has fallen a bit off my radar since I moved jobs a couple of years ago. I'll try to find some time to work on this. The package certainly could do with some love again... :)
anupamme commentedon May 10, 2017
Sure, is there a quick hacky fix for this issue? which I can do and get unblocked.
exhuma commentedon May 11, 2017
Sorry for the late reply... I wrote the answer above right before hitting the sack. I'll see if I can find something.
exhuma commentedon May 11, 2017
@anupamme I've looked at your problem, and it's not related to this issue (#15). I've opened a new one (see #23) for your issue.