First page Back Continue Last page Overview Graphics

Voting Function

We will write a vote function now. This functions uses the class 'Counter' from collections to count the quantity of the classes inside of an instance list. This instance list will be the neighbors of course. The function 'vote' returns the most common class:

from collections import Counter

def vote(neighbors):

class_counter = Counter()

for neighbor in neighbors:

class_counter[neighbor[2]] += 1

return class_counter.most_common(1)[0][0]

for i in range(n_training_samples):

neighbors = get_neighbors(learnset_data,

learnset_labels,

testset_data[i],

3,

distance=distance)

print("index: ", i,

", result of vote: ", vote(neighbors),

", label: ", testset_labels[i],

", data: ", testset_data[i])