From f8d59a257a96b8c4ee31f5e4e6671e27b53491f7 Mon Sep 17 00:00:00 2001 From: wujunjie <297081150@qq.com> Date: Thu, 26 Sep 2024 10:51:16 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20function.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/function.py b/function.py index ce7aea6..1f082f5 100644 --- a/function.py +++ b/function.py @@ -38,6 +38,28 @@ name = "吴俊煯" # 这里写自己的代码实现 +def euclidean_distance(instance1, instance2, length): + """ + 计算两个实例之间的欧几里得距离 + """ + distance = 0 + for x in range(length): + distance += (instance1[x] - instance2[x]) ** 2 + return np.sqrt(distance) + +def get_neighbors(train, test_row, k=4): + """ + 获取测试实例的 k 个最近邻 + """ + distances = [] + length = len(test_row) - 1 # 假设最后一列是标签 + for index in range(len(train)): + dist = euclidean_distance(test_row, train[index], length) + distances.append((train[index], dist)) + distances.sort(key=lambda tup: tup[1]) + neighbors = distances[:k] + return neighbors + def classify0(inX, dataSet, labels,k=4): """ KNN 分类算法。