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

This commit is contained in:
2024-10-08 11:03:33 +08:00
parent f3806cb09f
commit 56ade127c2
+23 -9
View File
@@ -1,4 +1,3 @@
# function.py
import numpy as np
"""
@@ -23,10 +22,10 @@ import numpy as np
"""
请在这里填写学号和姓名,不填写即成绩无效。
qin
"""
id = "202210423xxx"
name = "test_name"
id = "202210423206"
name = "詹宇豪"
"""
@@ -40,7 +39,7 @@ name = "test_name"
# 这里写自己的代码实现
def classify0(inX, dataSet, labels, k=0):
def classify0(inX, dataSet, labels, k=3):
"""
KNN 分类算法。
@@ -48,11 +47,24 @@ def classify0(inX, dataSet, labels, k=0):
- inX (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。
- k (int): KNN 算法参数,请自行设置默认值,评测时仅会使用其默认值。
- k (int): KNN 算法参数,默认值为3。
Returns:
- int: 预测的分类标签。
"""
# 计算输入样本与训练数据集中每个样本的欧氏距离
distances = np.sqrt(((dataSet - inX) ** 2).sum(axis=1))
# 按距离从小到大排序并获取对应的索引
sorted_indices = distances.argsort()
# 选择距离最近的k个样本
top_k_labels = labels[sorted_indices[:k]]
# 统计k个样本中出现最多的类别
predicted_label = np.bincount(top_k_labels).argmax()
return predicted_label
def load_data(file_path):
@@ -66,10 +78,12 @@ def load_data(file_path):
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 测试代码,可以修改以便调试
train_file = "datingTrainSet2.tsv"
# 加载训练数据
train_data, train_labels = load_data(train_file)
print(classify0([65915, 3.868359, 0.128078], train_data, train_labels))
# 测试 classify0 函数
result = classify0(np.array([65915, 3.868359, 0.128078]), train_data, train_labels)
print("Predicted label:", result)