generated from LufsX/Experiment-kNN
This commit is contained in:
+12
-29
@@ -1,9 +1,7 @@
|
|||||||
#function.py
|
# function.py
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import os
|
import os
|
||||||
from collections import Counter
|
|
||||||
id="202210423115"
|
|
||||||
name="李煜锋"
|
|
||||||
def img_to_vector(filename):
|
def img_to_vector(filename):
|
||||||
"""
|
"""
|
||||||
将二值图像转换为向量。
|
将二值图像转换为向量。
|
||||||
@@ -33,7 +31,6 @@ def load_dataset(directory):
|
|||||||
feature_list = []
|
feature_list = []
|
||||||
label_list = []
|
label_list = []
|
||||||
|
|
||||||
print(f"正在加载目录: {directory}")
|
|
||||||
# 遍历目录,加载数据
|
# 遍历目录,加载数据
|
||||||
for filename in os.listdir(directory):
|
for filename in os.listdir(directory):
|
||||||
if filename.endswith('.txt'):
|
if filename.endswith('.txt'):
|
||||||
@@ -52,6 +49,7 @@ def load_dataset(directory):
|
|||||||
labels = np.array(label_list)
|
labels = np.array(label_list)
|
||||||
|
|
||||||
return features, labels
|
return features, labels
|
||||||
|
from collections import Counter
|
||||||
|
|
||||||
def knn_classify(input_vector, dataSet, labels, k=3):
|
def knn_classify(input_vector, dataSet, labels, k=3):
|
||||||
"""
|
"""
|
||||||
@@ -79,29 +77,14 @@ def knn_classify(input_vector, dataSet, labels, k=3):
|
|||||||
label_count = Counter(top_k_labels)
|
label_count = Counter(top_k_labels)
|
||||||
|
|
||||||
return label_count.most_common(1)[0][0]
|
return label_count.most_common(1)[0][0]
|
||||||
|
# 加载训练数据
|
||||||
|
train_data, train_labels = load_dataset('C:\\Users\\Administrator\\Desktop\\trainingDigits')
|
||||||
|
|
||||||
# 主程序
|
# 加载测试数据
|
||||||
if __name__ == '__main__':
|
test_data, test_labels = load_dataset('C:\\Users\\Administrator\\Desktop\\testDigits')
|
||||||
# 使用绝对路径替换为你数据集的路径
|
|
||||||
train_directory = r'C:\Users\Administrator\Desktop\trainingDigits'
|
|
||||||
test_directory = r'C:\Users\Administrator\Desktop\testDigits'
|
|
||||||
|
|
||||||
# 加载训练数据
|
# 选择一个测试样本,进行分类
|
||||||
train_data, train_labels = load_dataset(train_directory)
|
for i in range(len(test_data)):
|
||||||
|
predicted_label = knn_classify(test_data[i], train_data, train_labels, k=3)
|
||||||
# 加载测试数据
|
true_label = test_labels[i]
|
||||||
test_data, test_labels = load_dataset(test_directory)
|
print(f"预测标签: {predicted_label}, 真实标签: {true_label}")
|
||||||
|
|
||||||
# 测试 kNN 分类器
|
|
||||||
correct_predictions = 0
|
|
||||||
|
|
||||||
for i in range(len(test_data)):
|
|
||||||
predicted_label = knn_classify(test_data[i], train_data, train_labels, k=3)
|
|
||||||
true_label = test_labels[i]
|
|
||||||
print(f"预测标签: {predicted_label}, 真实标签: {true_label}")
|
|
||||||
|
|
||||||
if predicted_label == true_label:
|
|
||||||
correct_predictions += 1
|
|
||||||
|
|
||||||
accuracy = correct_predictions / len(test_data) * 100
|
|
||||||
print(f"分类准确率: {accuracy:.2f}%")
|
|
||||||
|
|||||||
Reference in New Issue
Block a user