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

This commit is contained in:
sn
2024-10-16 18:58:18 +08:00
parent 23c3e91261
commit 28ba669806
+23 -7
View File
@@ -25,8 +25,8 @@ import numpy as np
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423xxx"
name = "test_name"
id = "202210423112"
name = "严锡好"
"""
@@ -41,7 +41,7 @@ name = "test_name"
# 这里写自己的代码实现
def classify0(inX, dataSet, labels, k=0):
def classify0(inX, dataSet, labels, k=3):
"""
KNN 分类算法。
@@ -49,11 +49,26 @@ 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(np.sum((dataSet - inX) ** 2, axis=1))
# 获取距离最近的 k 个样本的索引
sortedDistIndices = distances.argsort()[:k]
# 获取这些样本对应的标签
classCount = {}
for i in sortedDistIndices:
voteLabel = labels[i]
classCount[voteLabel] = classCount.get(voteLabel, 0) + 1
# 选择出现次数最多的标签作为预测标签
sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)
return sortedClassCount[0][0]
def load_data(file_path):
@@ -68,9 +83,10 @@ 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))
# 测试一个样本
test_sample = np.array([65915, 3.868359, 0.128078])
predicted_label = classify0(test_sample, train_data, train_labels)
print(f"The predicted label for the test sample is: {predicted_label}")