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

This commit is contained in:
2024-10-14 17:14:59 +08:00
parent a52b5ac7b7
commit 409e55e21b
+18 -4
View File
@@ -25,8 +25,8 @@ import numpy as np
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423xxx"
name = "test_name"
id = "202210423213"
name = "熊浩燃"
"""
@@ -54,7 +54,19 @@ def classify0(inX, dataSet, labels, k=0):
Returns:
- int: 预测的分类标签。
"""
# 计算距离
distances = np.linalg.norm(dataSet - inX, axis=1)
# 获取距离最小的 k 个样本的索引
k_indices = np.argsort(distances)[:k]
# 获取这 k 个样本的标签
k_nearest_labels = [labels[i] for i in k_indices]
# 进行投票
most_common = np.bincount(k_nearest_labels).argmax()
return most_common
def load_data(file_path):
"""
@@ -70,7 +82,9 @@ 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))
# 测试分类
sample = np.array([65915, 3.868359, 0.128078])
predicted_label = classify0(sample, train_data, train_labels)
print(f"Predicted label: {predicted_label}")