0

I am trying to write a k means algorithm and at very basic stage right now.
The code is as follows to randomly select the centres for clustering:

import numpy as np

import random

X = [2,3,5,8,12,15,18]

C = 2

def rand_center(ip,C):

    centers = {}
    for i in range (C):
        if i>0:
            while centers[i] != centers[i-1]:   
                centers[i] = random.choice(X)
                else:
            centers[i] = random.choice(X)   
    return centers
    print (centers)

rand_center(X,C)

When I run this, it gives me KeyError:1
Can anyone guide me resolve this error?

1
  • 1
    By the way, you can't print (or do anything) following that return statment Commented Nov 23, 2016 at 5:10

4 Answers 4

1

while centers[i] != centers[i-1]... What happens on the second iteration of the for i in range (C): loop?

centers[1] != centers[0]... There is no centers[1] at that point.

Sign up to request clarification or add additional context in comments.

Comments

0

I guess that this issue is because of incorrect index to an array. So if you re-check the indexes passed in array may help you to solve this issue. And it will be more helpful for me to debug your code if you post the line number in which you are getting this error.

Comments

0

your code is wrong you should re write it as follows

import numpy as np
import random

X = [2,3,5,8,12,15,18]

C = 2

def rand_center(ip,C):
    if C<1:
       return []
    centers = [random.choice(ip)]
    for i in range(1,min(C,len(ip))):
        centers.append(random.choice(ip)) 
        while centers[i] in centers[:i]:   
            centers[i] = random.choice(ip)        
    return centers

print (rand_center(X,C))

1 Comment

Thank you everyone!
0

I hope you are looking to output: ie. Dictionary with Key and value that doesn't having same value in Current, Previous and Next key.

import numpy as np
import random

X = [2,3,5,8,12,15,18]
C = 2

def rand_center(ip,C):
    centers = {}
    for i in range (C):
        rand_num = random.choice(X) 
        if i>0:
            #Add Key and Value in Dictionary. 
            centers[i] = rand_num
            #Check condition if it Doesn't follow the rule, then change value and retry.
            while rand_num != centers[i-1]: 
                centers[i] = rand_num
                #Change the current value 
                rand_num = random.choice(X) 
        else:
            #First Key 0 not having previous element. Set it as default  
            centers[i] = rand_num   
    return centers

print"Output: ",rand_center(X,C)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.