generated from LufsX/Experiment-kNN
This commit is contained in:
+57
-15
@@ -25,8 +25,8 @@ import os
|
||||
"""
|
||||
请在这里填写学号和姓名,不填写即成绩无效。
|
||||
"""
|
||||
id = "202210423xxx"
|
||||
name = "test_name"
|
||||
id = "202210423103"
|
||||
name = "王坤"
|
||||
|
||||
|
||||
"""
|
||||
@@ -41,7 +41,16 @@ name = "test_name"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def classify(input_vector, dataSet, labels, k=0):
|
||||
import numpy as np
|
||||
import os
|
||||
|
||||
"""
|
||||
请在这里填写学号和姓名,不填写即成绩无效。
|
||||
"""
|
||||
id = "202210423xxx"
|
||||
name = "test_name"
|
||||
|
||||
def classify(input_vector, dataSet, labels, k=3):
|
||||
"""
|
||||
KNN 分类算法。
|
||||
|
||||
@@ -49,14 +58,26 @@ def classify(input_vector, dataSet, labels, k=0):
|
||||
- input_vector (numpy array): 输入待分类的样本。
|
||||
- dataSet (numpy array): 训练数据集。
|
||||
- labels (list or numpy array): 训练集对应的标签。
|
||||
- k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。
|
||||
- k (int): kNN 算法参数,默认设置为3。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
# 计算输入向量与训练集样本的欧氏距离
|
||||
distances = np.linalg.norm(dataSet - input_vector, axis=1)
|
||||
|
||||
# 按距离排序并获取前k个距离最小的索引
|
||||
sorted_indices = distances.argsort()[:k]
|
||||
|
||||
# 统计前k个邻居的标签
|
||||
nearest_labels = [labels[i] for i in sorted_indices]
|
||||
|
||||
# 返回出现次数最多的标签
|
||||
predicted_label = max(set(nearest_labels), key=nearest_labels.count)
|
||||
|
||||
return predicted_label
|
||||
|
||||
|
||||
# 这里也写自己的代码实现
|
||||
def load_dataset(directory):
|
||||
"""
|
||||
从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||
@@ -65,12 +86,25 @@ def load_dataset(directory):
|
||||
- directory (str): 数据文件夹路径。
|
||||
|
||||
Returns:
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
- 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):
|
||||
"""
|
||||
将二值图像转换为向量。
|
||||
@@ -80,12 +114,19 @@ def img_to_vector(filename):
|
||||
- filename (str): 图像文件路径。
|
||||
|
||||
Returns:
|
||||
- np.array: 二值图像向量。
|
||||
- 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
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
# 测试代码示例,加载训练集并进行分类
|
||||
train_data, train_labels = load_dataset("trainingDigits")
|
||||
|
||||
test_data = (
|
||||
@@ -122,10 +163,11 @@ if __name__ == "__main__":
|
||||
"00000000000001111111110000000000"
|
||||
"00000000000000000111100000000000"
|
||||
)
|
||||
predicted_label = classify(
|
||||
np.array([int(char) for char in test_data]).reshape(1, 1024),
|
||||
train_data,
|
||||
train_labels,
|
||||
)
|
||||
|
||||
# 将测试数据转换为向量
|
||||
test_vector = np.array([int(char) for char in test_data]).reshape(1, 1024)
|
||||
|
||||
# 使用 kNN 进行分类
|
||||
predicted_label = classify(test_vector, train_data, train_labels)
|
||||
|
||||
print(f"预测的标签: {predicted_label}")
|
||||
|
||||
Reference in New Issue
Block a user