相同功能的不同输出

Different output for same function

我在 python 中实现了 KNN 算法。

import math

            #height,width,deepth,thickness,Label
data_set = [(2,9,8,4, "Good"),
            (3,7,7,9, "Bad"),
            (10,3,10,3, "Good"),
            (2,9,6,10, "Good"),
            (3,3,2,5, "Bad"),
            (2,8,5,6, "Bad"),
            (7,2,3,10, "Good"),
            (1,10,8,10, "Bad"),
            (2,8,1,10, "Good")
            ]


A = (3,2,1,5)
B = (8,3,1,2)
C = (6,10,8,3)
D = (9,6,4,1)


distances = []
labels = []

def calc_distance(datas,test):
    for data in datas:
        distances.append(
            ( round(math.sqrt(((data[0] - test[0])**2 + (data[1] - test[1])**2 + (data[2] - test[2])**2 + (data[3] - test[3])**2)), 3), data[4] )) 
    return distances

def most_frequent(list1): 
    return max(set(list1), key = list1.count) 

def get_neibours(k):
    distances.sort()
    print(distances[:k])
    for distance in distances[:k]:
        labels.append(distance[1])
    print("It can be classified as: ", end="")
    print(most_frequent(labels))



calc_distance(data_set,D)
get_neibours(7)

calc_distance(data_set,D)
get_neibours(7)

我大部分时间工作得很好,我得到了正确的标签。例如对于 D,我确实得到了标签 "Good"。但是我发现了一个错误,例如当我调用它两次时:

 calc_distance(data_set,D)
get_neibours(7)

calc_distance(data_set,D)
get_neibours(7)

我运行它几次,我得到不同的输出-"Good"和"Bad"当我运行程序几次..

一定是哪里出了问题我没找到。

问题是您使用相同的距离和标签,排序并获取前 k 个元素。在函数中创建列表并 return 它。检查下面的修改。

import math

data_set = [
    (2,9,8,4, "Good"),
    (3,7,7,9, "Bad"),
    (10,3,10,3, "Good"),
    (2,9,6,10, "Good"),
    (3,3,2,5, "Bad"),
    (2,8,5,6, "Bad"),
    (7,2,3,10, "Good"),
    (1,10,8,10, "Bad"),
    (2,8,1,10, "Good"),
]

A = (3,2,1,5)
B = (8,3,1,2)
C = (6,10,8,3)
D = (9,6,4,1)

def calc_distance(datas, test):
    distances = []
    for data in datas:
        distances.append(
            ( round(math.sqrt(((data[0] - test[0])**2 + (data[1] - test[1])**2 + (data[2] - test[2])**2 + (data[3] - test[3])**2)), 3), data[4] ))
    return distances

def most_frequent(list1):
    return max(set(list1), key = list1.count)

def get_neibours(distances, k):
    labels = []
    distances.sort()
    print(distances[:k])
    for distance in distances[:k]:
        labels.append(distance[1])
    print("It can be classified as: ", end="")
    print(most_frequent(labels))

distances = calc_distance(data_set,D)
get_neibours(distances, 7)

distances = calc_distance(data_set,D)
get_neibours(distances, 7) 

[(7.071, 'Good'), (8.062, 'Bad'), (8.888, 'Bad'), (9.11, 'Good'), (10.1, 'Good'), (10.488, 'Bad'), (11.958, 'Good')] 它可以分类为:好

[(7.071, 'Good'), (8.062, 'Bad'), (8.888, 'Bad'), (9.11, 'Good'), (10.1, 'Good'), (10.488, 'Bad'), (11.958, 'Good')] 它可以分类为:好