简体   繁体   English

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

[英]IndexError: list index out of range in python k nearest neighbour

program of k nearest neighbour ML 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)

Program throwing an error 程序抛出错误

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

IndexError: list index out of range

Tried different ways and methods many times but the error is persistent. 多次尝试不同的方法和方法,但错误是持久的。

your indentation is off: you should either warn or run the loop. 你的缩进是关闭的:你应该警告或运行循环。 here is one version how you could fix that: 这是一个版本如何解决这个问题:

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.
        ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM