2016-12-25 10 views
1

プログラム内の範囲外のリストインデックスMLはIndexError:K最近傍のPythonの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

それは '票'は空のiterableだと思われる! – Kasramvd

+0

ループが実際に実行されるように、 'warning.warn'行の後ろに' else'を忘れていた可能性はありますか? – tihom

答えて

0

インデントがオフです:ループを警告または実行する必要があります。ここにあなたがそれを修正する方法を1つのバージョン:

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. 
     .... 
関連する問題