diff --git a/function.py b/function.py index b1f8c16..21e1b8f 100644 --- a/function.py +++ b/function.py @@ -1,4 +1,3 @@ -# function.py import numpy as np import os @@ -25,23 +24,11 @@ import os """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423117" +name = "程悦" -""" -参数说明: -- input_vector (numpy array): 输入待分类的样本。 -- dataSet (numpy array): 训练数据集。 -- labels (list or numpy array): 训练集对应的标签。 -- k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。 -返回值: -- int: 预测的分类标签。 -""" - - -# 这里写自己的代码实现 -def classify(input_vector, dataSet, labels, k=0): +def classify(input_vector, dataSet, labels, k=5): """ KNN 分类算法。 @@ -54,23 +41,15 @@ def classify(input_vector, dataSet, labels, k=0): Returns: - int: 预测的分类标签。 """ + num_samples = dataSet.shape[0] + diffs = np.tile(input_vector, (num_samples, 1)) - dataSet + distances = np.sum(diffs**2, axis=1)**0.5 + sorted_indices = np.argsort(distances) + k_nearest_labels = [labels[i] for i in sorted_indices[:k]] + unique_labels, counts = np.unique(k_nearest_labels, return_counts=True) + return unique_labels[np.argmax(counts)] -# 这里也写自己的代码实现 -def load_dataset(directory): - """ - 从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 - - Args: - - directory (str): 数据文件夹路径。 - - Returns: - - np.array: 特征数据。 - - np.array: 标签数据。 - """ - - -# 这里还写自己的代码实现 def img_to_vector(filename): """ 将二值图像转换为向量。 @@ -82,6 +61,31 @@ def img_to_vector(filename): Returns: - np.array: 二值图像向量。 """ + with open(filename, 'r') as f: + lines = f.readlines() + return np.array([int(char) for line in lines for char in line.strip()]) + + +def load_dataset(directory): + """ + 从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 + + Args: + - directory (str): 数据文件夹路径。 + + Returns: + - np.array: 特征数据。 + - np.array: 标签数据。 + """ + data = [] + labels = [] + for filename in os.listdir(directory): + if filename.endswith(".txt"): + label = int(filename[0]) + vector = img_to_vector(os.path.join(directory, filename)) + data.append(vector) + labels.append(label) + return np.array(data), np.array(labels) if __name__ == "__main__": @@ -128,4 +132,4 @@ if __name__ == "__main__": train_labels, ) - print(f"预测的标签: {predicted_label}") + print(f"预测的标签: {predicted_label}") \ No newline at end of file