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

This commit is contained in:
2024-10-22 19:50:34 +08:00
parent 4edfffa687
commit 279037c36f
+16 -7
View File
@@ -6,7 +6,7 @@ import time
id = "202210423220"
name = "方子涵"
def classify(input_vector, dataSet, labels, k=5):
def classify(input_vector, dataSet, labels, k=3):
"""
KNN 分类算法。
@@ -14,7 +14,7 @@ def classify(input_vector, dataSet, labels, k=5):
- input_vector (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。
- k (int): kNN 算法参数,默认值为 5。
- k (int): kNN 算法参数,默认值为 3。
Returns:
- int: 预测的分类标签。
@@ -27,10 +27,17 @@ def classify(input_vector, dataSet, labels, k=5):
# 获取距离最近的 k 个样本的索引
sortedDistIndices = distances.argsort()
classCount = {}
weightSum = {}
# 使用加权多数表决法
for i in range(k):
voteIlabel = labels[sortedDistIndices[i]]
# 统计每个类别的出现次数
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
# 统计每个类别的出现次数,并使用距离的倒数作为权重
weight = 1 / (distances[sortedDistIndices[i]] + 1e-5) # 加上一个小常数防止除以零
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + weight
weightSum[voteIlabel] = weightSum.get(voteIlabel, 0) + 1
# 计算加权平均值
for className in classCount:
classCount[className] /= weightSum[className]
# 返回出现次数最多的类别
sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)
return sortedClassCount[0][0]
@@ -127,8 +134,10 @@ if __name__ == "__main__":
)
test_data_vector = np.array([int(char) for char in test_data]).reshape(1, 1024)
# 使用k=5进行分类
# 测试不同的k值
k_values = [1, 3, 5, 7, 9]
for k in k_values:
start_time = time.time()
predicted_label = classify(test_data_vector, train_data, train_labels, k=5)
predicted_label = classify(test_data_vector, train_data, train_labels, k)
end_time = time.time()
print(f"k = 5, 预测的标签: {predicted_label}, 执行时间: {end_time - start_time:.2f} 秒")
print(f"k = {k}, 预测的标签: {predicted_label}, 执行时间: {end_time - start_time:.2f} 秒")