python - "ValueError: The truth value of an array with more than one element is ambiguous" -


i trying execute following code :( simple code kmeans algorithm has been written in python.the two-step procedure continues until assignments of clusters , centroids no longer change. convergence guaranteed solution might local minimum. in practice, algorithm run multiple times , averaged.

import numpy np import random numpy import *  points = [[1,1],[1.5,2],[3,4],[5,7],[3.5,5],[4.5,5], [3.5,4]]   def cluster(points,center):   clusters = {}    x in points:      z= min([(i[0], np.linalg.norm(x-center[i[0]]))  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=[]   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=4     if iterations > max_iterations: return true     return (oldcenter == center)  def kmeans():      points = np.array([[1,1],[1.5,2],[3,4],[5,7],[3.5,5],[4.5,5], [3.5,4]])   clusters={}   iterations = 0   oldcenter=([[],[]])      center= ([[1,1],[5,7]])                            while not shouldstop(oldcenter, center, iterations):         # save old centroids convergence test. book keeping.         oldcenter=center         iterations += 1         clusters=cluster(points,center)           center=update(oldcenter,clusters)    return (center,clusters)  kmeans() 

but stuck. can me this, please?

traceback (most recent call last):   file "has_converged.py", line 64, in <module>     (center,clusters)=kmeans()   file "has_converged.py", line 55, in kmeans     while not shouldstop(oldcenter, center, iterations):   file "has_converged.py", line 46, in shouldstop     return (oldcenter == center) valueerror: truth value of array more 1 element ambiguous.  use a.any() or a.all() 

as error indicates, cannot compare 2 arrays == in numpy:

>>> = np.random.randn(5) >>> b = np.random.randn(5) >>> array([-0.28636246,  0.75874234,  1.29656196,  1.19471939,  1.25924266]) >>> b array([-0.13541816,  1.31538069,  1.29514837, -1.2661043 ,  0.07174764]) >>> == b array([false, false, false, false, false], dtype=bool) 

the result of == element-wise boolean array. can tell whether array true all method:

>>> (a == b).all() false 

that said, checking whether centroids changed in way unreliable because of rounding. might want use np.allclose instead.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -