IndexError:列表索引超出python k最近邻居的范围

时间:2016-12-25 06:54:12

标签: python numpy matplotlib nearest-neighbor

k最近邻ML的程序

    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

多次尝试不同的方式和方法,但错误是持久的。

1 个答案:

答案 0 :(得分: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.
        ....