For this function:
def kmeans(examples, k, verbose = False):
#Get k randomly chosen initial centroids, create cluster for each
initialCentroids = random.sample(examples, k)
clusters = []
for e in initialCentroids:
clusters.append(Cluster([e]))
#Iterate until centroids do not change
converged = False
numIterations = 0
while not converged:
numIterations += 1
#Create a list containing k distinct empty lists
newClusters = []
for i in range(k):
newClusters.append([])
#Associate each example with closest centroid
for e in examples:
#Find the centroid closest to e
smallestDistance = e.distance(clusters[0].getCentroid())
index = 0
for i in range(1, k):
distance = e.distance(clusters[i].getCentroid())
if distance < smallestDistance:
smallestDistance = distance
index = i
#Add e to the list of examples for appropriate cluster
newClusters[index].append(e)
for c in newClusters: #Avoid having empty clusters
if len(c) == 0:
raise ValueError('Empty Cluster')
#Update each cluster; check if a centroid has changed
converged = True
for i in range(k):
if clusters[i].update(newClusters[i]) > 0.0:
converged = False
if verbose:
print('Iteration #' + str(numIterations))
for c in clusters:
print(c)
print('') #add blank line
return clusters
I am having a hard time figuring out how to access the values to plot. It creates a list of objects, but I know the points are correct becase when I call the function I get the output:
When I use the print function i get the output
[<__main__.Cluster object at 0x7fb580f95f70>, <__main__.Cluster object at 0x7fb580f95910>, <__main__.Cluster object at 0x7fb580f95730>]
In the pic I attached, I would like to grab each list in the iteration(there are two) and plot it as it will have its own marker and color. This is a clustering problem I am working on and have been given these pre filled functions to use. Only using numpys, pandas, and matplotlib.
Any help or guidance as to what to google will be greatly appreciated.
I have googled 'object is not itterable', how to iterate through objects', 'How to plot objects using matplotlib'.
I have also tried to run some of the code within the function and got cross-eyed.
Tried looping through the variable i assigned to the called function, and it only prints the first iteration but keeps it as an object still so I cannot move the values to a list.
<__main__.Cluster ...>by a different string?