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

This commit is contained in:
cy
2024-10-01 19:42:55 +08:00
parent dee208bd9b
commit 90a236b4ac
+4 -3
View File
@@ -1,5 +1,7 @@
# function.py
import numpy as np
from collections import Counter
from scipy.spatial import distance
"""
挑战说明:
@@ -53,14 +55,13 @@ def classify0(inX, dataSet, labels, k=3):
"""
# 计算输入样本与训练集中每个样本的欧几里得距离
distances = [np.sqrt(np.sum((x_train - inX) ** 2)) for x_train in dataSet]
distances = distance.cdist(dataSet, [inX], metric='euclidean').flatten()
# 按距离排序并选择前k个最小的距离
k_indices = np.argsort(distances)[:k]
k_nearest_labels = [labels[i] for i in k_indices]
# 计算多数标签
from collections import Counter
label_counts = Counter(k_nearest_labels)
most_common_label = label_counts.most_common(1)[0][0]
@@ -90,7 +91,7 @@ if __name__ == "__main__":
predicted_label = classify0(test_sample, train_data, train_labels)
print(f"Predicted label: {predicted_label}, Actual label: {test_labels[0]}")
# 你也可以遍历整个测试集来评估分类器的性能
# 遍历整个测试集来评估分类器的性能
correct_count = 0
for i in range(len(test_data)):
predicted_label = classify0(test_data[i], train_data, train_labels)