当我调用random.sample(arr,length)时,错误返回random_sample()最多需要1个位置参数(给定2个)。我尝试使用不同的名称导入numpy,这不是解决问题。任何想法?感谢
import numpy.random
import random
import numpy as np
from numpy import *
points = [[1,1],[1.5,2],[3,4],[5,7],[3.5,5],[4.5,5], [3.5,4]]
def cluster(X,center):
clusters = {}
for x in X:
z= min([(i[0], np.linalg.norm(x-center[i[0]])) for i in enumerate(center)], key=lambda t:t[1])
try:
clusters[z].append(x)
except KeyError:
clusters[z]=[x]
return clusters
def update(oldcenter,clusters):
d=[]
r=[]
newcenter=[]
for k in clusters:
if k[0]==0:
d.append(clusters[(k[0],k[1])])
else:
r.append(clusters[(k[0],k[1])])
c=np.mean(d, axis=0)
u=np.mean(r,axis=0)
newcenter.append(c)
newcenter.append(u)
return newcenter
def shouldStop(oldcenter,center, iterations):
MAX_ITERATIONS=0
if iterations > MAX_ITERATIONS: return True
u=np.array_equal(center,oldcenter)
return u
def init_board(N):
X = np.array([(random.uniform(1,4), random.uniform(1, 4)) for i in range(4)])
return X
def kmeans(X,k):
clusters={}
iterations = 0
oldcenter=([[],[]])
center = random.sample(X,k)
while not shouldStop(oldcenter, center, iterations):
# Save old centroids for convergence test. Book keeping.
oldcenter=center
iterations += 1
clusters=cluster(X,center)
center=update(oldcenter,clusters)
return (center,clusters)
X=init_board(4)
(center,clusters)=kmeans(X,2)
print "center:",center
#print "clusters:", clusters
答案 0 :(得分:4)
使用from numpy import *
时,将numpy
命名空间中的所有项目导入脚本命名空间。执行此操作时,任何具有相同名称的函数/变量/ etc都将被numpy
命名空间中的项覆盖。
numpy
有一个名为numpy.random
的子包,然后覆盖了random
导入,如下面的代码所示:
import random
# Here random is the Python stdlib random package.
from numpy import *
# As numpy has a random package, numpy.random,
# random is now the numpy.random package as it has been overwritten.
在这种情况下,您应该使用import numpy as np
,这样您就可以访问:
import random
# random now contains the stdlib random package
import numpy as np
# np.random now contains the numpy.random package
答案 1 :(得分:-2)
您的积分是List
类型,因此您应该将其转换为数组
points = np.asarray(point)
此外,您应该使用import random