2016-12-25 4 views
1

프로그램의 범위를 벗어난리스트 인덱스는 ML은IndexError : K 가장 가까운 이웃의 파이썬 K 가장 가까운 이웃

import numpy as np 
    import math 
    import matplotlib.pyplot as plt 
    from matplotlib import style 
    from collections import Counter 

    dataset={'k':[[1,2],[2,3],[3,1]], 'r':[[6,5],[7,7],[8,6]]} 
    new_features=[5,7] 

    def k_nearest_neigh(data,predict,k=3): 
     distances = [] 
     if len(data)>=k: 
      warnings.warn('jerk') 
      for group in data: 
       for features in data[group]: 
        eu_dist=np.linalg.norm(np.array(features)-np.array(predict)) 
        distances.append([eu_dist,group]) 
        print(distances) 
     votes=[i[1] for i in sorted(distances)[:k]] 
     print(Counter(votes).most_common(1)) 
     vote_result=Counter(votes).most_common(1)[0][0] 
     return vote_result    

    result=k_nearest_neigh(dataset,new_features,k=3) 
    print(result) 

프로그램은

line 32, in k_nearest_neigh 
    vote_result=Counter(votes).most_common(1)[0][0] 

IndexError: list index out of range 

시도 여러 가지 방법과 방법을 여러 번 오류를 던지고 있지만 오류입니다 지속성 있는.

+0

'votes'는 빈 반복 가능으로 보입니다! – Kasramvd

+0

아마 루프가 실제로 실행되도록'warning.warn' 줄 다음에'else'를 잊어 버리셨습니까? – tihom

답변

0

들여 쓰기가 해제되었습니다. 루프를 경고하거나 실행해야합니다. 다음은 그 문제를 해결할 수있는 방법입니다 :

def k_nearest_neigh(data,predict,k=3): 
    if len(data)>=k: 
     warnings.warn('jerk') 
     return 
    distances = [] 
    for group in data: # do this whenever you issue no warning. 
     ....