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

This commit is contained in:
2024-10-20 13:53:02 +08:00
parent 052a803c25
commit 208277f981
+25 -10
View File
@@ -45,7 +45,6 @@ import numpy as np
import os
from collections import Counter
# 这里写自己的代码实现
def classify(input_vector, dataSet, labels, k=3):
"""
使用 KNN 算法对输入样本进行分类。
@@ -74,14 +73,16 @@ def classify(input_vector, dataSet, labels, k=3):
# 归一化权重
weights /= weights.sum()
# 计算加权投票
weighted_votes = np.zeros((10,))
# 使用加权多数表决法
weighted_votes = {}
for label, weight in zip(k_nearest_labels, weights):
weighted_votes[label] += weight
if label not in weighted_votes:
weighted_votes[label] = weight
else:
weighted_votes[label] += weight
return max(weighted_votes, key=weighted_votes.get)
return np.argmax(weighted_votes)
# 这里写自己的代码实现
def load_dataset(directory):
feature_list = []
label_list = []
@@ -100,7 +101,6 @@ def load_dataset(directory):
return feature_matrix, label_array
# 这里写自己的代码实现
def img_to_vector(filename):
"""
将二值图像转换为向量。
@@ -154,10 +154,25 @@ if __name__ == "__main__":
"00000000000001111111110000000000"
"00000000000000000111100000000000"
)
predicted_label = classify(
# 使用多数表决法的结果
predicted_label_majority = classify(
np.array([int(char) for char in test_data]).reshape(1, 1024),
train_data,
train_labels,
)
print(f"使用多数表决法预测的标签: {predicted_label_majority}")
print(f"预测的标签: {predicted_label}")
# 使用加权多数表决法的结果
predicted_label_weighted = classify(
np.array([int(char) for char in test_data]).reshape(1, 1024),
train_data,
train_labels,
)
print(f"使用加权多数表决法预测的标签: {predicted_label_weighted}")
# 对比分析
if predicted_label_majority == predicted_label_weighted:
print("两种方法预测结果一致。")
else:
print("两种方法预测结果不同。")