generated from LufsX/Experiment-kNN
This commit is contained in:
+8
-11
@@ -5,7 +5,6 @@ import numpy as np
|
|||||||
import os
|
import os
|
||||||
from collections import Counter
|
from collections import Counter
|
||||||
from sklearn.preprocessing import MinMaxScaler
|
from sklearn.preprocessing import MinMaxScaler
|
||||||
from sklearn.neighbors import KDTree # 确保正确导入 KDTree
|
|
||||||
|
|
||||||
# 加载数据集
|
# 加载数据集
|
||||||
def load_dataset(directory):
|
def load_dataset(directory):
|
||||||
@@ -32,12 +31,13 @@ def img_to_vector(file_path):
|
|||||||
vector[32 * i + j] = int(lines[i][j])
|
vector[32 * i + j] = int(lines[i][j])
|
||||||
return vector
|
return vector
|
||||||
|
|
||||||
# 使用 KDTree 进行 kNN 分类
|
# 使用欧式距离进行 kNN 分类
|
||||||
def classify(input_vector, tree, labels, k=7):
|
def classify(input_vector, dataSet, labels, k=7):
|
||||||
# 使用 KDTree 查找最近邻
|
# 计算所有训练样本与输入样本的欧式距离
|
||||||
input_vector = input_vector.reshape(1, -1) # 确保 input_vector 是二维数组
|
distances = np.linalg.norm(dataSet - input_vector, axis=1)
|
||||||
distances, indices = tree.query(input_vector, k=k)
|
# 获取距离最近的k个样本的标签
|
||||||
nearest_labels = labels[indices.flatten()]
|
nearest_neighbors = np.argsort(distances)[:k]
|
||||||
|
nearest_labels = labels[nearest_neighbors]
|
||||||
|
|
||||||
# 投票,返回出现次数最多的标签
|
# 投票,返回出现次数最多的标签
|
||||||
most_common = Counter(nearest_labels).most_common(1)
|
most_common = Counter(nearest_labels).most_common(1)
|
||||||
@@ -57,16 +57,13 @@ def main():
|
|||||||
training_data = normalize_data(training_data)
|
training_data = normalize_data(training_data)
|
||||||
test_data = normalize_data(test_data)
|
test_data = normalize_data(test_data)
|
||||||
|
|
||||||
# 使用 KDTree 构建训练集的树结构
|
|
||||||
tree = KDTree(training_data)
|
|
||||||
|
|
||||||
# 测试 kNN 算法
|
# 测试 kNN 算法
|
||||||
total_tests = len(test_data)
|
total_tests = len(test_data)
|
||||||
correct_predictions = 0
|
correct_predictions = 0
|
||||||
|
|
||||||
for i in range(total_tests):
|
for i in range(total_tests):
|
||||||
test_sample = test_data[i]
|
test_sample = test_data[i]
|
||||||
prediction = classify(test_sample, tree, training_labels, k=7)
|
prediction = classify(test_sample, training_data, training_labels, k=7)
|
||||||
actual_label = test_labels[i]
|
actual_label = test_labels[i]
|
||||||
|
|
||||||
print(f"测试样本 {i+1}: 预测值 = {prediction}, 实际值 = {actual_label}")
|
print(f"测试样本 {i+1}: 预测值 = {prediction}, 实际值 = {actual_label}")
|
||||||
|
|||||||
Reference in New Issue
Block a user