更新 function.py
Gitea Actions Challenge Test / Challenge-Actions (push) Successful in 11s

This commit is contained in:
2024-11-21 09:17:12 +08:00
parent c34c9d51aa
commit 4c7715a4b1
+13 -9
View File
@@ -41,13 +41,15 @@ name = "李燕如"
# 这里写自己的代码实现
def classify0(inX, dataSet, labels, k=5):
import numpy as np
def classify0(inX, dataSet, labels, k=3):
# 数据标准化
dataSet = (dataSet - np.mean(dataSet, axis=0)) / np.std(dataSet, axis=0)
inX = (inX - np.mean(dataSet, axis=0)) / np.std(dataSet, axis=0)
# 计算距离
distances = np.sqrt(np.sum((dataSet - inX) ** 2, axis=1))
distances = [distance.euclidean(inX, x) for x in dataSet]
# 获取k个最近邻的索引
k_indices = np.argsort(distances)[:k]
@@ -55,14 +57,16 @@ def classify0(inX, dataSet, labels, k=5):
# 获取这些样本对应的标签
k_nearest_labels = labels[k_indices]
# 权重分配(距离的倒数)
weights = 1 / distances[k_indices]
weights /= np.sum(weights) # 归一化权重
# 投票决定分类
result = {}
for label in k_nearest_labels:
if label in result:
result[label] += 1
else:
result[label] = 1
# 加权投票
prediction = np.argmax(np.bincount(k_nearest_labels, weights=weights))
return prediction
# 返回出现次数最多的类别
return max(result, key=result.get)
def load_data(file_path):
data = np.loadtxt(file_path, delimiter="\t")