generated from LufsX/Experiment-kNN
147 lines
4.7 KiB
Python
147 lines
4.7 KiB
Python
import numpy as np
|
|
import os
|
|
|
|
"""
|
|
实验说明:
|
|
- 自行编写实现数据加载与 kNN 的手写数字分类算法。
|
|
- 函数输入: 待分类的样本 input_vector, 训练数据集 dataSet, 训练集对应的标签 labels。
|
|
- 函数返回: 预测的分类标签。
|
|
|
|
注意事项:
|
|
- 在 function.py 中实现 kNN 分类算法。
|
|
- 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。
|
|
- 自动评测脚本仅会加载 classify 和 load_data 函数,请勿修改函数名。
|
|
- 训练集和测试集需手动下载解压,并放入当前目录下。
|
|
|
|
测评环境:
|
|
- CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz
|
|
- OS: Ubuntu 22.04.4 LTS
|
|
- Python: 3.10.12
|
|
- numpy: 2.1.1
|
|
"""
|
|
|
|
"""
|
|
请在这里填写学号和姓名,不填写即成绩无效。
|
|
"""
|
|
id = "202210423203"
|
|
name = "赵昊龙"
|
|
|
|
def classify(input_vector, dataSet, labels, k=3):
|
|
"""
|
|
KNN 分类算法。
|
|
|
|
Args:
|
|
- input_vector (numpy array): 输入待分类的样本。
|
|
- dataSet (numpy array): 训练数据集。
|
|
- labels (list or numpy array): 训练集对应的标签。
|
|
- k (int): kNN 算法参数。
|
|
|
|
Returns:
|
|
- int: 预测的分类标签。
|
|
"""
|
|
# 欧式距离
|
|
diffMat = np.tile(input_vector, (dataSet.shape[0], 1)) - dataSet
|
|
sqDiffMat = diffMat**2
|
|
sqDistances = sqDiffMat.sum(axis=1)
|
|
distances = sqDistances**0.5
|
|
sortedDistIndices = distances.argsort()
|
|
|
|
# 取出距离最近的k个点的标签
|
|
classCount = {}
|
|
for i in range(k):
|
|
voteIlabel = labels[sortedDistIndices[i]]
|
|
# 统计每个类别的出现次数
|
|
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
|
|
|
|
# 选择出现次数最多的类别作为预测标签
|
|
sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)
|
|
return sortedClassCount[0][0]
|
|
|
|
def load_dataset(directory):
|
|
"""
|
|
从文件夹中加载数据。
|
|
|
|
Args:
|
|
- directory (str): 数据文件夹路径。
|
|
|
|
Returns:
|
|
- np.array: 特征数据。
|
|
- np.array: 标签数据。
|
|
"""
|
|
fileList = os.listdir(directory)
|
|
m = len(fileList)
|
|
dataSet = np.zeros((m, 1024)) # 28*28的二值图像数据
|
|
labels = []
|
|
|
|
for i in range(m):
|
|
filename = fileList[i]
|
|
fileWithPath = os.path.join(directory, filename)
|
|
vector = img_to_vector(fileWithPath)
|
|
dataSet[i, :] = vector
|
|
label = int(filename.split('.')[0]) # 假设文件名的格式为"数字.txt"
|
|
labels.append(label)
|
|
|
|
return dataSet, np.array(labels)
|
|
|
|
def img_to_vector(filename):
|
|
"""
|
|
将二值图像转换为向量。
|
|
|
|
Args:
|
|
- filename (str): 图像文件路径。
|
|
|
|
Returns:
|
|
- np.array: 二值图像向量。
|
|
"""
|
|
returnVect = np.zeros((1024,)) # 28*28的二值图像数据
|
|
with open(filename, 'r') as file:
|
|
lines = file.readlines()
|
|
n = 0
|
|
for line in lines:
|
|
for i in range(len(line)-1):
|
|
returnVect[n] = int(line[i])
|
|
n = n + 1
|
|
return returnVect
|
|
|
|
if __name__ == "__main__":
|
|
train_data, train_labels = load_dataset("trainingDigits")
|
|
test_data = (
|
|
"00000000000000110000000000000000"
|
|
"00000000000011111000000000000000"
|
|
"00000000000011111100000000000000"
|
|
"00000000001111111110000000000000"
|
|
"00000000001111111110000000000000"
|
|
"00000000001111111100000000000000"
|
|
"00000000011111111000000000000000"
|
|
"00000000111111111000000000000000"
|
|
"00000000111111110000000000000000"
|
|
"00000000111111110000000000000000"
|
|
"00000000111111110000000000000000"
|
|
"00000000111111110000000000000000"
|
|
"00000000111111100000000000000000"
|
|
"00000001111111100000000000000000"
|
|
"00000001111111100000000000000000"
|
|
"00000001111111100000000000000000"
|
|
"00000001111111111111000000000000"
|
|
"00000001111111111111111000000000"
|
|
"00000001111111111111111100000000"
|
|
"00000011111111111111111110000000"
|
|
"00000011111111111111111110000000"
|
|
"00000001111111111111111110000000"
|
|
"00000001111111111111111110000000"
|
|
"00000000111111111100111111100000"
|
|
"00000000111111111000111111100000"
|
|
"00000000011111111001111111100000"
|
|
"00000000011111111111111111000000"
|
|
"00000000001111111111111111000000"
|
|
"00000000000111111111111111000000"
|
|
"00000000000011111111111100000000"
|
|
"00000000000001111111110000000000"
|
|
"00000000000000000111100000000000"
|
|
)
|
|
predicted_label = classify(
|
|
np.array([int(char) for char in test_data]).reshape(1, 1024),
|
|
train_data,
|
|
train_labels,
|
|
)
|
|
print(f"预测的标签: {predicted_label}") |