leo
leo

Reputation: 1

Keyerror : 1 python

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?

Upvotes: 0

Views: 8467

Answers (4)

Prafull kadam
Prafull kadam

Reputation: 208

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)

Upvotes: 0

Mr. A
Mr. A

Reputation: 1231

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))

Upvotes: 0

sansingh
sansingh

Reputation: 195

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.

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191710

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.

Upvotes: 1

Related Questions