generated from LufsX/Experiment-kNN
This commit is contained in:
+107
-63
@@ -27,85 +27,129 @@ import os
|
|||||||
"""
|
"""
|
||||||
id = "202210423122"
|
id = "202210423122"
|
||||||
name = "焦国波"
|
name = "焦国波"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
参数说明:
|
|
||||||
- input_vector (numpy array): 输入待分类的样本。
|
|
||||||
- dataSet (numpy array): 训练数据集。
|
|
||||||
- labels (list or numpy array): 训练集对应的标签。
|
|
||||||
- k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。
|
|
||||||
返回值:
|
|
||||||
- int: 预测的分类标签。
|
|
||||||
"""
|
|
||||||
def load_data(directory):
|
|
||||||
"""
|
|
||||||
加载数据集,将图像数据转换为向量形式,并提取标签。
|
|
||||||
|
|
||||||
参数:
|
|
||||||
- directory (str): 数据集目录路径。
|
|
||||||
|
|
||||||
返回值:
|
|
||||||
- images (numpy array): 图像数据。
|
|
||||||
- labels (list): 标签列表。
|
|
||||||
"""
|
|
||||||
images = []
|
|
||||||
labels = []
|
|
||||||
for filename in os.listdir(directory):
|
|
||||||
if filename.endswith(".png"):
|
|
||||||
label = int(filename.split('_')[0])
|
|
||||||
image = np.array([int(pixel) for pixel in open(os.path.join(directory, filename), 'rb').read()])
|
|
||||||
images.append(image)
|
|
||||||
labels.append(label)
|
|
||||||
return np.array(images), np.array(labels)
|
|
||||||
|
|
||||||
def classify(input_vector, dataSet, labels, k=3):
|
def classify(input_vector, dataSet, labels, k=3):
|
||||||
"""
|
"""
|
||||||
kNN 分类算法实现。
|
KNN 分类算法。
|
||||||
|
|
||||||
参数:
|
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 算法参数,默认值为 3。
|
- k (int): kNN 算法参数,默认设置为3。
|
||||||
|
|
||||||
返回值:
|
Returns:
|
||||||
- int: 预测的分类标签。
|
- int: 预测的分类标签。
|
||||||
"""
|
"""
|
||||||
# 计算输入向量与数据集中每个样本的欧式距离
|
# 计算输入向量与训练集样本的欧氏距离
|
||||||
distances = np.sqrt(np.sum((dataSet - input_vector) ** 2, axis=1))
|
distances = np.linalg.norm(dataSet - input_vector, axis=1)
|
||||||
|
|
||||||
# 获取 k 个最近邻的索引
|
# 按距离排序并获取前k个距离最小的索引
|
||||||
sortedDistIndices = distances.argsort()
|
sorted_indices = distances.argsort()[:k]
|
||||||
|
|
||||||
# 获取 k 个最近邻的标签
|
# 统计前k个邻居的标签
|
||||||
classCount = {}
|
nearest_labels = [labels[i] for i in sorted_indices]
|
||||||
for i in range(k):
|
|
||||||
voteLabel = labels[sortedDistIndices[i]]
|
# 返回出现次数最多的标签
|
||||||
classCount[voteLabel] = classCount.get(voteLabel, 0) + 1
|
predicted_label = max(set(nearest_labels), key=nearest_labels.count)
|
||||||
|
|
||||||
|
return predicted_label
|
||||||
|
|
||||||
|
|
||||||
|
def load_dataset(directory):
|
||||||
|
"""
|
||||||
|
从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- directory (str): 数据文件夹路径。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- np.array: 特征数据矩阵。
|
||||||
|
- np.array: 标签数组。
|
||||||
|
"""
|
||||||
|
file_list = os.listdir(directory)
|
||||||
|
num_files = len(file_list)
|
||||||
|
|
||||||
|
# 初始化数据矩阵和标签数组
|
||||||
|
data_matrix = np.zeros((num_files, 1024))
|
||||||
|
labels = []
|
||||||
|
|
||||||
|
for i, file_name in enumerate(file_list):
|
||||||
|
# 文件名格式:label_index.txt,例如 0_1.txt,标签为 0
|
||||||
|
label = int(file_name.split('_')[0])
|
||||||
|
labels.append(label)
|
||||||
|
data_matrix[i, :] = img_to_vector(os.path.join(directory, file_name))
|
||||||
|
|
||||||
|
return data_matrix, np.array(labels)
|
||||||
|
|
||||||
|
|
||||||
|
def img_to_vector(filename):
|
||||||
|
"""
|
||||||
|
将二值图像转换为向量。
|
||||||
|
该部分应为 load_dataset 函数的辅助子函数,可单独在这里实现,也可直接集成至 load_dataset 函数中。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- filename (str): 图像文件路径。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- np.array: 二值图像向量 (1x1024)。
|
||||||
|
"""
|
||||||
|
return_vector = np.zeros((1, 1024)) # 创建1x1024的零向量
|
||||||
|
with open(filename) as file:
|
||||||
|
for i in range(32): # 图像为32x32
|
||||||
|
line_str = file.readline()
|
||||||
|
for j in range(32):
|
||||||
|
return_vector[0, 32 * i + j] = int(line_str[j]) # 转换为1x1024向量
|
||||||
|
return return_vector
|
||||||
|
|
||||||
# 多数表决,返回出现次数最多的标签
|
|
||||||
sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)
|
|
||||||
return sortedClassCount[0][0]
|
|
||||||
|
|
||||||
# 以下代码用于测试和演示,实际使用时请删除或注释掉
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 加载训练集和测试集
|
# 测试代码示例,加载训练集并进行分类
|
||||||
X_train, y_train = load_data('trainingDigits')
|
train_data, train_labels = load_dataset("trainingDigits")
|
||||||
X_test, y_test = load_data('testDigits')
|
|
||||||
|
|
||||||
# 测试分类函数
|
|
||||||
test_samples = X_test[:5]
|
|
||||||
for sample in test_samples:
|
|
||||||
predicted_label = classify(sample, X_train, y_train)
|
|
||||||
print(f"Input Vector: {sample}, Predicted Label: {predicted_label}")
|
|
||||||
|
|
||||||
|
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"
|
"00000000000000000111100000000000"
|
||||||
)
|
)
|
||||||
predicted_label = classify(
|
|
||||||
np.array([int(char) for char in test_data]).reshape(1, 1024),
|
# 将测试数据转换为向量
|
||||||
train_data,
|
test_vector = np.array([int(char) for char in test_data]).reshape(1, 1024)
|
||||||
train_labels,
|
|
||||||
)
|
# 使用 kNN 进行分类
|
||||||
|
predicted_label = classify(test_vector, train_data, train_labels)
|
||||||
|
|
||||||
print(f"预测的标签: {predicted_label}")
|
print(f"预测的标签: {predicted_label}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Reference in New Issue
Block a user