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

768 views Asked by At

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

1

There are 1 answers

0
hiro protagonist On

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