2016-12-25 85 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. 
     ....