执行kmedoids python模块

时间:2018-05-13 13:11:01

标签: python python-3.x k-means

我尝试运行此github page上提供的kmedoids群集实施。

提供的minimal working example非常简单,但我无法使用kMedoids()函数执行第一行而不会引发错误:

from sklearn.metrics.pairwise import pairwise_distances
import numpy as np    
import kmedoids

# 3 points in dataset
data = np.array([[1,1], 
                [2,2], 
                [10,10]])

# distance matrix
D = pairwise_distances(data, metric='euclidean')

# split into 2 clusters
M, C = kmedoids.kMedoids(D, 2)  # <-- THIS RAISES AN ERROR

print('medoids:')
for point_idx in M:
    print( data[point_idx] )

print('')
print('clustering result:')
for label in C:
    for point_idx in C[label]:
        print('label {0}: {1}'.format(label, data[point_idx]))

错误是:

Traceback (most recent call last):
File "/usr/lib/python3.5/code.py", line 91, in runcode
exec(code, self.locals)
File "", line 1, in 
File "", line 9, in kMedoids
File "mtrand.pyx", line 4832, in mtrand.RandomState.shuffle
File "mtrand.pyx", line 4835, in mtrand.RandomState.shuffle
TypeError: 'range' object does not support item assignment

我在Eclipse PyDev中设置了如下例子,用于Python 3.5:

  • 使用pip3 install安装所有模块(numpy,scipy和scikit-learn)
  • kmedoids.py文件添加到与example.py
  • 相同的目录中

最近有没有人尝试过使用此功能?我的Python版本(3.5)会导致此错误吗?

1 个答案:

答案 0 :(得分:0)

发现问题,确实肯定与最初不适用于Python 3的kMedoids() code有关。

要使其适用于Python 3.5,请编辑以下与range()函数相关的行,如下所示(参见此相关answer):

index_shuf = range(len(rs)) -->  index_shuf = list(range(len(rs)))

for t in xrange(tmax): --> for t in range(tmax):