generated from LufsX/Experiment-kNN
This commit is contained in:
+60
-17
@@ -1,6 +1,8 @@
|
||||
# function.py
|
||||
import numpy as np
|
||||
import os
|
||||
from scipy.spatial import distance
|
||||
from sklearn.neighbors import KDTree
|
||||
|
||||
"""
|
||||
实验说明:
|
||||
@@ -41,26 +43,63 @@ name = "熊浩燃"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def classify(input_vector, dataSet, labels, k=3):
|
||||
def classify_optimized(input_vector, dataSet, labels, k=3, metric='euclidean', decision_rule='uniform'):
|
||||
"""
|
||||
KNN 分类算法。
|
||||
|
||||
优化后的 KNN 分类算法,包括 k 值调优、距离度量、决策规则和加速方法。
|
||||
|
||||
Args:
|
||||
- input_vector (numpy array): 输入待分类的样本。
|
||||
- dataSet (numpy array): 训练数据集。
|
||||
- labels (list or numpy array): 训练集对应的标签。
|
||||
- k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。
|
||||
|
||||
- k (int): kNN 算法中的 k 值。
|
||||
- metric (str): 距离度量方式,默认是 'euclidean',可以选择 'manhattan', 'cosine', 'mahalanobis' 等。
|
||||
- decision_rule (str): 决策规则,'uniform' 为普通投票,'weighted' 为加权投票。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
# 计算欧氏距离
|
||||
distances = np.linalg.norm(dataSet - input_vector, axis=1)
|
||||
# 获取距离最近的 k 个样本的索引
|
||||
# 选择距离度量
|
||||
if metric == 'euclidean':
|
||||
distances = np.linalg.norm(dataSet - input_vector, axis=1)
|
||||
elif metric == 'manhattan':
|
||||
distances = np.sum(np.abs(dataSet - input_vector), axis=1)
|
||||
elif metric == 'cosine':
|
||||
distances = distance.cdist([input_vector], dataSet, 'cosine')[0]
|
||||
elif metric == 'mahalanobis':
|
||||
VI = np.linalg.inv(np.cov(dataSet.T))
|
||||
distances = distance.cdist([input_vector], dataSet, 'mahalanobis', VI=VI)[0]
|
||||
|
||||
# 获取最近的 k 个样本
|
||||
nearest_neighbors_indices = distances.argsort()[:k]
|
||||
# 获取这些样本的标签
|
||||
nearest_labels = np.array(labels)[nearest_neighbors_indices]
|
||||
# 统计出现次数最多的标签并返回
|
||||
|
||||
# 决策规则
|
||||
if decision_rule == 'uniform':
|
||||
predicted_label = np.bincount(nearest_labels).argmax()
|
||||
elif decision_rule == 'weighted':
|
||||
weights = 1 / (distances[nearest_neighbors_indices] + 1e-5) # 避免距离为0时除零
|
||||
predicted_label = np.bincount(nearest_labels, weights=weights).argmax()
|
||||
|
||||
return predicted_label
|
||||
|
||||
# KDTree 加速 KNN 分类算法
|
||||
def classify_with_kdtree(input_vector, dataSet, labels, k=3):
|
||||
"""
|
||||
使用 KDTree 加速 KNN 算法。
|
||||
|
||||
Args:
|
||||
- input_vector (numpy array): 输入待分类的样本。
|
||||
- dataSet (numpy array): 训练数据集。
|
||||
- labels (list or numpy array): 训练集对应的标签。
|
||||
- k (int): kNN 算法中的 k 值。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
tree = KDTree(dataSet)
|
||||
distances, indices = tree.query(input_vector.reshape(1, -1), k=k)
|
||||
nearest_labels = np.array(labels)[indices[0]]
|
||||
|
||||
predicted_label = np.bincount(nearest_labels).argmax()
|
||||
return predicted_label
|
||||
|
||||
@@ -68,10 +107,10 @@ def classify(input_vector, dataSet, labels, k=3):
|
||||
def load_dataset(directory):
|
||||
"""
|
||||
从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||
|
||||
|
||||
Args:
|
||||
- directory (str): 数据文件夹路径。
|
||||
|
||||
|
||||
Returns:
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
@@ -85,16 +124,15 @@ def load_dataset(directory):
|
||||
vector = img_to_vector(os.path.join(directory, filename))
|
||||
data_list.append(vector)
|
||||
return np.array(data_list), np.array(labels)
|
||||
|
||||
# 这里还写自己的代码实现
|
||||
def img_to_vector(filename):
|
||||
"""
|
||||
将二值图像转换为向量。
|
||||
该部分应为 load_dataset 函数的辅助子函数,可单独在这里实现,也可直接集成至 load_dataset 函数中。
|
||||
|
||||
|
||||
Args:
|
||||
- filename (str): 图像文件路径。
|
||||
|
||||
|
||||
Returns:
|
||||
- np.array: 二值图像向量。
|
||||
"""
|
||||
@@ -148,5 +186,10 @@ if __name__ == "__main__":
|
||||
|
||||
test_vector = np.array([int(char) for char in test_data]).reshape(1, 1024)
|
||||
|
||||
predicted_label = classify(test_vector, train_data, train_labels)
|
||||
print(f"预测的标签: {predicted_label}")
|
||||
# 使用优化后的 KNN 进行预测
|
||||
predicted_label_optimized = classify_optimized(test_vector, train_data, train_labels, k=5, metric='cosine', decision_rule='weighted')
|
||||
print(f"优化后的预测标签: {predicted_label_optimized}")
|
||||
|
||||
# 使用 KDTree 加速的 KNN 进行预测
|
||||
predicted_label_kdtree = classify_with_kdtree(test_vector, train_data, train_labels, k=5)
|
||||
print(f"KDTree 加速后的预测标签: {predicted_label_kdtree}")
|
||||
Reference in New Issue
Block a user