2016-12-25 89 views
1

程序列表索引超出範圍MLIndexError:在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

似乎'票'是一個空的迭代! – 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. 
     ....