generated from LufsX/Challenge-kNN
chore: try to opt running time
Gitea Actions Challenge Test / Challenge-Actions (push) Successful in 13s
Gitea Actions Challenge Test / Challenge-Actions (push) Successful in 13s
This commit is contained in:
+10
-8
@@ -1,6 +1,6 @@
|
||||
# function.py
|
||||
import numpy as np
|
||||
|
||||
import time
|
||||
"""
|
||||
挑战说明:
|
||||
- 自行编写实现 KNN 分类算法。
|
||||
@@ -57,13 +57,13 @@ def classify0(inX, dataSet, labels, k=8):
|
||||
diff = dataSet - inX
|
||||
|
||||
# 使用矩阵运算计算马氏距离
|
||||
distances = np.sqrt(np.sum(diff @ VI * diff, axis=1))
|
||||
distances = np.sum(diff @ VI * diff, axis=1)
|
||||
|
||||
# 对距离排序,获取前 k 个最近的样本索引
|
||||
sortedDistIndices = np.argsort(distances)[:k]
|
||||
sortedDistIndices = np.argsort(distances)
|
||||
|
||||
# 统计前 k 个样本的标签
|
||||
classCount = np.bincount(labels[sortedDistIndices], minlength=np.max(labels) + 1)
|
||||
classCount = np.bincount(labels[sortedDistIndices[:8]])
|
||||
|
||||
# 返回出现次数最多的标签
|
||||
return np.argmax(classCount)
|
||||
@@ -88,14 +88,14 @@ if __name__ == "__main__":
|
||||
|
||||
train_data, train_labels = load_data(train_file)
|
||||
test_data, test_labels = load_data(test_file)
|
||||
|
||||
for j in range(20):
|
||||
start_time = time.time()
|
||||
for j in range(1):
|
||||
correct = 0
|
||||
total = len(test_data)
|
||||
|
||||
for i in range(total):
|
||||
# 获取测试数据中的每个样本
|
||||
result = classify0(test_data[i], train_data, train_labels, k=j + 1)
|
||||
result = classify0(test_data[i], train_data, train_labels)
|
||||
if result == test_labels[i]:
|
||||
correct += 1
|
||||
# else:
|
||||
@@ -103,5 +103,7 @@ if __name__ == "__main__":
|
||||
# f"第 {i+1} 次测试错误,数据 {test_data[i]} 被分类到 {result} 实际是 {test_labels[i]}"
|
||||
# )
|
||||
if correct >= 96:
|
||||
print(f"KNN 分类算法,k={j+1}")
|
||||
# print(f"KNN 分类算法,k={j+1}")
|
||||
print(f"{correct}% 正确率")
|
||||
end_time = time.time()
|
||||
print(f"运行时间:{end_time - start_time} s")
|
||||
|
||||
Reference in New Issue
Block a user