generated from LufsX/Experiment-kNN
This commit is contained in:
+94
-9
@@ -1,5 +1,6 @@
|
||||
# function.py
|
||||
import numpy as np
|
||||
from collections import Counter
|
||||
import os
|
||||
|
||||
"""
|
||||
@@ -41,7 +42,7 @@ name = "test_name"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def classify(input_vector, dataSet, labels, k=0):
|
||||
def classify(input_vector, dataSet, labels, k=3):
|
||||
"""
|
||||
KNN 分类算法。
|
||||
|
||||
@@ -49,39 +50,123 @@ 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.sqrt(np.sum((input_vector - dataSet) ** 2, axis=1))
|
||||
|
||||
# 获取距离最小的k个样本的索引
|
||||
k_indices = np.argsort(distances)[:k]
|
||||
|
||||
# 获取这些样本对应的标签
|
||||
k_nearest_labels = labels[k_indices]
|
||||
|
||||
# 使用Counter统计这些标签中出现次数最多的标签
|
||||
label_count = Counter(k_nearest_labels)
|
||||
|
||||
# 返回出现次数最多的标签
|
||||
return label_count.most_common(1)[0][0]
|
||||
|
||||
# 这里也写自己的代码实现
|
||||
def img_to_vector(filename):
|
||||
"""
|
||||
将二值图像转换为向量。
|
||||
|
||||
Args:
|
||||
- filename (str): 图像文件路径。
|
||||
|
||||
Returns:
|
||||
- np.array: 二值图像向量。
|
||||
"""
|
||||
return np.array([int(char) for line in open(filename) for char in line.strip()])
|
||||
|
||||
def load_dataset(directory):
|
||||
"""
|
||||
从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||
|
||||
从文件夹中加载数据。
|
||||
|
||||
Args:
|
||||
- directory (str): 数据文件夹路径。
|
||||
|
||||
|
||||
Returns:
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
images = []
|
||||
labels = []
|
||||
|
||||
# 遍历目录中的所有子目录
|
||||
for label_dir in os.listdir(directory):
|
||||
# 构建完整的子目录路径
|
||||
label_dir_path = os.path.join(directory, label_dir)
|
||||
|
||||
# 确保是目录而不是文件
|
||||
if os.path.isdir(label_dir_path):
|
||||
# 遍历目录中的所有文件
|
||||
for filename in os.listdir(label_dir_path):
|
||||
# 构建完整的文件路径
|
||||
file_path = os.path.join(label_dir_path, filename)
|
||||
|
||||
# 读取文件内容并转换为向量
|
||||
image_vector = img_to_vector(file_path)
|
||||
|
||||
# 添加向量和标签到列表中
|
||||
images.append(image_vector)
|
||||
labels.append(int(label_dir))
|
||||
|
||||
# 将列表转换为 NumPy 数组
|
||||
return np.array(images), np.array(labels)
|
||||
|
||||
# 示例用法
|
||||
if __name__ == "__main__":
|
||||
train_dir = "trainingDigits" # 训练集目录
|
||||
test_dir = "testDigits" # 测试集目录
|
||||
|
||||
train_images, train_labels = load_dataset(train_dir)
|
||||
test_images, test_labels = load_dataset(test_dir)
|
||||
|
||||
print("训练集特征形状:", train_images.shape)
|
||||
print("训练集标签形状:", train_labels.shape)
|
||||
print("测试集特征形状:", test_images.shape)
|
||||
print("测试集标签形状:", test_labels.shape)
|
||||
|
||||
|
||||
# 这里还写自己的代码实现
|
||||
def img_to_vector(filename):
|
||||
"""
|
||||
将二值图像转换为向量。
|
||||
该部分应为 load_dataset 函数的辅助子函数,可单独在这里实现,也可直接集成至 load_dataset 函数中。
|
||||
|
||||
|
||||
Args:
|
||||
- filename (str): 图像文件路径。
|
||||
|
||||
|
||||
Returns:
|
||||
- np.array: 二值图像向量。
|
||||
"""
|
||||
with open(filename, 'r') as file:
|
||||
# 读取文件的每一行
|
||||
lines = file.readlines()
|
||||
|
||||
# 初始化一个空列表来存储向量
|
||||
vector = []
|
||||
|
||||
# 遍历每一行,将每个字符转换为整数并添加到列表中
|
||||
for line in lines:
|
||||
vector.extend([int(pixel) for pixel in line.strip()])
|
||||
|
||||
# 将列表转换为 NumPy 数组并返回
|
||||
return np.array(vector)
|
||||
|
||||
# 示例用法
|
||||
if __name__ == "__main__":
|
||||
# 假设有一个图像文件路径
|
||||
filename = "path_to_your_image_file.txt"
|
||||
|
||||
# 调用函数并打印结果
|
||||
image_vector = img_to_vector(filename)
|
||||
print("图像向量:", image_vector)
|
||||
print("向量形状:", image_vector.shape)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user