简体   繁体   中英

Keyerror : 1 python

I am trying to write ak 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?

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.

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM