diff --git a/function.py b/function.py index 8de62e1..012044f 100644 --- a/function.py +++ b/function.py @@ -58,11 +58,7 @@ def classify(input_vector, dataSet, labels, k=3): """ 使用欧式距离的 kNN 分类算法。 """ - distances = [np.linalg.norm(input_vector - x) for x in dataSet] - k_indices = np.argsort(distances)[:k] - k_nearest_labels = [labels[i] for i in k_indices] - most_common = Counter(k_nearest_labels).most_common(1) - return most_common[0][0] + # 这里也写自己的代码实现 @@ -78,25 +74,7 @@ def load_dataset(directory): - np.array: 特征数据。 - np.array: 标签数据。 """ - features = [] - labels = [] - for filename in os.listdir(directory): - filepath = os.path.join(directory, filename) - - # 检查文件是否为图片类型(如 png 或 jpg) - if filename.endswith(".png") or filename.endswith(".jpg"): - # 从文件名提取标签 - label = int(filename.split('_')[0]) - - # 加载图片并转换为灰度图 - image = Image.open(filepath).convert('L') - - # 展平为一维向量并添加到特征列表中 - feature = np.array(image).flatten() - features.append(feature) - labels.append(label) - - return np.array(features), np.array(labels) + # 这里还写自己的代码实现 @@ -111,8 +89,7 @@ def img_to_vector(filename): Returns: - np.array: 二值图像向量。 """ - image = Image.open(filename).convert('L') - return np.array(image).flatten() + if __name__ == "__main__":