From 1089ea001ee1b90ea7b219757f56d9631a99755e Mon Sep 17 00:00:00 2001 From: zhangchenghong <1598349064@qq.com> Date: Tue, 15 Oct 2024 11:08:02 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20function.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.py | 39 +++------------------------------------ 1 file changed, 3 insertions(+), 36 deletions(-) diff --git a/function.py b/function.py index b1b6d46..d2ed52e 100644 --- a/function.py +++ b/function.py @@ -47,52 +47,19 @@ from collections import Counter # 这里写自己的代码实现 -def classify(input_vector, dataSet, labels, k=3): +def classify(input_vector, dataSet, labels, k=2): """ 使用 KNN 算法对输入样本进行分类。 参数: - - input_vector (numpy array): 输入待分类的样本(1xN)。 - - dataSet (numpy array): 训练数据集(MxN)。 + - input_vector (numpy array): 输入待分类的样本(1xN)。 + - dataSet (numpy array): 训练数据集(MxN)。 - labels (list or numpy array): 训练集对应的标签。 - k (int): kNN 算法参数,默认值为 3。 返回: - int: 预测的分类标签。 """ - # 在 classify 函数中实现权重投票 - distances = np.sum((input_vector - dataSet) ** 2, axis=1) - sorted_indices = distances.argsort() - k_nearest_distances = distances[sorted_indices[:k]] - k_nearest_labels = labels[sorted_indices[:k]] - - # 计算权重(距离的倒数) - weights = 1 / k_nearest_distances - # 归一化权重 - weights /= weights.sum() - - # 计算加权投票 - weighted_votes = np.zeros((10,)) - for label, weight in zip(k_nearest_labels, weights): - weighted_votes[label] += weight - - return np.argmax(weighted_votes) - -# 在 load_dataset 函数中添加特征缩放 -def load_dataset(directory): - feature_list = [] - label_list = [] - for file in os.listdir(directory): - file_path = os.path.join(directory, file) - feature_vector = img_to_vector(file_path) - feature_list.append(feature_vector) - label_list.append(int(file.split('_')[0])) - feature_matrix = np.array(feature_list) - label_array = np.array(label_list) - - # 特征缩放 - feature_matrix = feature_matrix / 255.0 - return feature_matrix, label_array # 计算输入向量与训练集之间的欧氏距离 distances = np.sum((input_vector - dataSet) ** 2, axis=1) ** 0.5 # 根据距离排序并获取索引