generated from LufsX/Experiment-kNN
This commit is contained in:
+55
-50
@@ -1,71 +1,83 @@
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
import os
|
import os
|
||||||
from sklearn.preprocessing import StandardScaler
|
|
||||||
from sklearn.neighbors import KDTree
|
from sklearn.neighbors import KDTree
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
实验说明:
|
||||||
|
|
||||||
|
- 自行编写实现数据加载与 kNN 的手写数字分类算法。
|
||||||
|
|
||||||
|
- 函数输入: 待分类的样本 input_vector, 训练数据集 dataSet, 训练集对应的标签 labels。
|
||||||
|
|
||||||
|
- 函数返回: 预测的分类标签。
|
||||||
|
|
||||||
请在这里填写学号和姓名,不填写即成绩无效。
|
请在这里填写学号和姓名,不填写即成绩无效。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
id = "202210423213"
|
id = "202210423213"
|
||||||
name = "熊浩燃"
|
name = "熊浩燃"
|
||||||
|
|
||||||
"""
|
|
||||||
参数说明:
|
|
||||||
- input_vector (numpy array): 输入待分类的样本。
|
|
||||||
- dataSet (numpy array): 训练数据集。
|
|
||||||
- labels (list or numpy array): 训练集对应的标签。
|
|
||||||
- k (int): kNN 算法参数,请自行设置默认值,评测时仅会使用其默认值,不修改默认值将无法通过评测,成绩为零。
|
|
||||||
返回值:
|
|
||||||
- int: 预测的分类标签。
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
def classify(input_vector, dataSet, labels, k=1, distance_metric='euclidean', weighted=False):
|
||||||
def classify(input_vector, dataSet, labels, k=1, distance_metric='euclidean', weighted=True):
|
|
||||||
"""
|
"""
|
||||||
KNN 分类算法.
|
KNN 分类算法。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
- input_vector (numpy array): 输入待分类的样本。
|
- input_vector (numpy array): 输入待分类的样本。
|
||||||
- dataSet (numpy array): 训练数据集。
|
- dataSet (numpy array): 训练数据集。
|
||||||
- labels (list or numpy array): 训练集对应的标签。
|
- labels (list or numpy array): 训练集对应的标签。
|
||||||
- k (int): kNN 算法参数,默认 k=1。
|
- k (int): kNN 算法参数,默认值为1。
|
||||||
- distance_metric (str): 距离度量方法,默认欧氏距离。
|
- distance_metric (str): 距离度量方式,支持'euclidean'和'manhattan'。
|
||||||
- weighted (bool): 是否使用加权投票机制,默认加权。
|
- weighted (bool): 是否使用加权投票。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
- int: 预测的分类标签。
|
- int: 预测的分类标签。
|
||||||
"""
|
"""
|
||||||
|
# 选择距离度量
|
||||||
if distance_metric == 'euclidean':
|
if distance_metric == 'euclidean':
|
||||||
# 欧氏距离
|
|
||||||
distances = np.linalg.norm(dataSet - input_vector, axis=1)
|
distances = np.linalg.norm(dataSet - input_vector, axis=1)
|
||||||
elif distance_metric == 'manhattan':
|
elif distance_metric == 'manhattan':
|
||||||
# 曼哈顿距离
|
|
||||||
distances = np.sum(np.abs(dataSet - input_vector), axis=1)
|
distances = np.sum(np.abs(dataSet - input_vector), axis=1)
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Unsupported distance metric: {distance_metric}")
|
||||||
|
|
||||||
# 使用KD树加速最近邻查找
|
# 获取距离最近的 k 个样本的索引
|
||||||
tree = KDTree(dataSet)
|
nearest_neighbors_indices = distances.argsort()[:k]
|
||||||
dist, indices = tree.query(input_vector.reshape(1, -1), k=k)
|
# 获取这些样本的标签
|
||||||
|
nearest_labels = np.array(labels)[nearest_neighbors_indices]
|
||||||
nearest_labels = np.array(labels)[indices[0]]
|
|
||||||
|
|
||||||
if weighted:
|
if weighted:
|
||||||
# 使用距离的倒数作为权重
|
# 使用加权投票:距离越近,权重越大
|
||||||
weights = 1 / (dist[0] + 1e-5)
|
nearest_distances = distances[nearest_neighbors_indices]
|
||||||
label_weights = {}
|
weights = 1 / (nearest_distances + 1e-5) # 防止距离为0
|
||||||
|
weighted_vote = np.bincount(nearest_labels, weights=weights)
|
||||||
for i, label in enumerate(nearest_labels):
|
predicted_label = weighted_vote.argmax()
|
||||||
label_weights[label] = label_weights.get(label, 0) + weights[i]
|
|
||||||
|
|
||||||
# 返回加权得分最高的标签
|
|
||||||
predicted_label = max(label_weights, key=label_weights.get)
|
|
||||||
else:
|
else:
|
||||||
# 直接使用多数投票
|
|
||||||
predicted_label = np.bincount(nearest_labels).argmax()
|
predicted_label = np.bincount(nearest_labels).argmax()
|
||||||
|
|
||||||
return predicted_label
|
return predicted_label
|
||||||
|
|
||||||
|
|
||||||
|
def classify_with_kdtree(input_vector, dataSet, labels, k=1):
|
||||||
|
"""
|
||||||
|
使用 KD-tree 进行加速的 kNN 分类算法。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- input_vector (numpy array): 输入待分类的样本。
|
||||||
|
- dataSet (numpy array): 训练数据集。
|
||||||
|
- labels (list or numpy array): 训练集对应的标签。
|
||||||
|
- k (int): kNN 算法参数,默认值为1。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- int: 预测的分类标签。
|
||||||
|
"""
|
||||||
|
tree = KDTree(dataSet) # 构建 KD-tree
|
||||||
|
dist, 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
|
||||||
|
|
||||||
|
|
||||||
def load_dataset(directory):
|
def load_dataset(directory):
|
||||||
"""
|
"""
|
||||||
从文件夹中加载数据,若不自行正确实现,则无法通过评测,不记录成绩。
|
从文件夹中加载数据,若不自行正确实现,则无法通过评测,不记录成绩。
|
||||||
@@ -74,32 +86,23 @@ def load_dataset(directory):
|
|||||||
- directory (str): 数据文件夹路径。
|
- directory (str): 数据文件夹路径。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
- np.array: 标准化后的特征数据。
|
- np.array: 特征数据。
|
||||||
- np.array: 标签数据。
|
- np.array: 标签数据。
|
||||||
"""
|
"""
|
||||||
labels = []
|
labels = []
|
||||||
data_list = []
|
data_list = []
|
||||||
|
|
||||||
for filename in os.listdir(directory):
|
for filename in os.listdir(directory):
|
||||||
if filename.endswith(".txt"): # 确保读取的是 txt 文件
|
if filename.endswith(".txt"): # 确保读取的是 txt 文件
|
||||||
label = int(filename.split('_')[0])
|
label = int(filename.split('_')[0])
|
||||||
labels.append(label)
|
labels.append(label)
|
||||||
vector = img_to_vector(os.path.join(directory, filename))
|
vector = img_to_vector(os.path.join(directory, filename))
|
||||||
data_list.append(vector)
|
data_list.append(vector)
|
||||||
|
return np.array(data_list), np.array(labels)
|
||||||
data_array = np.array(data_list)
|
|
||||||
|
|
||||||
# 标准化数据
|
|
||||||
scaler = StandardScaler()
|
|
||||||
scaled_data = scaler.fit_transform(data_array)
|
|
||||||
|
|
||||||
return scaled_data, np.array(labels)
|
|
||||||
|
|
||||||
|
|
||||||
def img_to_vector(filename):
|
def img_to_vector(filename):
|
||||||
"""
|
"""
|
||||||
将二值图像转换为向量。该部分应为 load_dataset 函数的辅助子函数,可单独在这里实现,也可直接集成至 load_dataset 函数中。
|
将二值图像转换为向量。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
- filename (str): 图像文件路径。
|
- filename (str): 图像文件路径。
|
||||||
|
|
||||||
@@ -108,13 +111,10 @@ def img_to_vector(filename):
|
|||||||
"""
|
"""
|
||||||
with open(filename, 'r') as f: # 确保使用文本模式读取
|
with open(filename, 'r') as f: # 确保使用文本模式读取
|
||||||
lines = f.readlines()
|
lines = f.readlines()
|
||||||
|
|
||||||
vector = np.zeros((1024,), dtype=int) # 将其改为 (1024,) 的一维数组
|
vector = np.zeros((1024,), dtype=int) # 将其改为 (1024,) 的一维数组
|
||||||
|
|
||||||
for i in range(32):
|
for i in range(32):
|
||||||
for j in range(32):
|
for j in range(32):
|
||||||
vector[32 * i + j] = int(lines[i][j])
|
vector[32 * i + j] = int(lines[i][j])
|
||||||
|
|
||||||
return vector
|
return vector
|
||||||
|
|
||||||
|
|
||||||
@@ -159,5 +159,10 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
test_vector = np.array([int(char) for char in test_data]).reshape(1, 1024)
|
test_vector = np.array([int(char) for char in test_data]).reshape(1, 1024)
|
||||||
|
|
||||||
|
# 使用默认的欧氏距离和不加权的投票机制
|
||||||
predicted_label = classify(test_vector, train_data, train_labels)
|
predicted_label = classify(test_vector, train_data, train_labels)
|
||||||
print(f"预测的标签: {predicted_label}")
|
print(f"预测的标签(普通分类): {predicted_label}")
|
||||||
|
|
||||||
|
# 使用 KD-tree 进行加速的分类
|
||||||
|
predicted_label_kdtree = classify_with_kdtree(test_vector, train_data, train_labels)
|
||||||
|
print(f"预测的标签(KD-tree 加速): {predicted_label_kdtree}")
|
||||||
|
|||||||
Reference in New Issue
Block a user