更新 function.py
Gitea Actions Challenge Test / Challenge-Actions (push) Failing after 12s

This commit is contained in:
zhe
2024-10-16 20:44:26 +08:00
parent 96a380f99f
commit 80744d7ada
+27 -5
View File
@@ -1,6 +1,7 @@
# function.py
import numpy as np
from collections import Counter
from sklearn.preprocessing import StandardScaler # 用于数据标准化
"""
挑战说明:
- 自行编写实现 KNN 分类算法。
@@ -25,8 +26,8 @@ import numpy as np
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423xxx"
name = "test_name"
id = "202210423111"
name = "李劲"
"""
@@ -54,7 +55,28 @@ def classify0(inX, dataSet, labels, k=0):
Returns:
- int: 预测的分类标签。
"""
# 确保输入样本inX是numpy数组
inX = np.array(inX)
# 标准化数据(使用训练数据的均值和标准差来转换输入数据和训练数据)
scaler = StandardScaler().fit(dataSet)
dataSet_scaled = scaler.transform(dataSet)
inX_scaled = scaler.transform([inX])
# 计算输入样本与所有训练样本之间的欧几里得距离
distances = [np.sqrt(np.sum((inX_scaled[0] - x_train) ** 2)) for x_train in dataSet_scaled]
# 根据距离对训练样本进行排序,并获取前k个最近邻的索引
k_indices = np.argsort(distances)[:k]
# 根据索引获取前k个最近邻的标签
k_nearest_labels = [labels[i] for i in k_indices]
# 使用Counter找出出现次数最多的标签
most_common = Counter(k_nearest_labels).most_common(1)
# 返回出现次数最多的标签(即预测的分类标签)
return most_common[0][0]
def load_data(file_path):
"""
@@ -70,7 +92,7 @@ if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
train_file = "datingTrainSet2.tsv"
test_file = "datingTestSet2.tsv"
train_data, train_labels = load_data(train_file)
print(classify0([65915, 3.868359, 0.128078], train_data, train_labels))