From 0efd997fd2a31cd82b671608d9a618568e969c8b Mon Sep 17 00:00:00 2001 From: 77 <3298722099@qq.com> Date: Thu, 21 Nov 2024 09:20:31 +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 | 38 ++++++++++++++++++-------------------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/function.py b/function.py index 61e1489..a10fe07 100644 --- a/function.py +++ b/function.py @@ -46,8 +46,19 @@ name = "陈瑞琪祥" -def classify0(inX, dataSet, labels, k): - result = classify0(test_data[i], train_data, train_labels, k=3) # 假设 k=3 是你选择的值 +def classify0(inX, dataSet, labels, k=3): + """ + KNN 分类算法。 + + Args: + - inX (numpy array): 输入待分类的样本。 + - dataSet (numpy array): 训练数据集。 + - labels (list or numpy array): 训练集对应的标签。 + - k (int): kNN 算法参数,默认值为 3。 + + Returns: + - int: 预测的分类标签。 + """ diffMat = np.tile(inX, (dataSet.shape[0], 1)) - dataSet sqDiffMat = diffMat**2 sqDistances = sqDiffMat.sum(axis=1) @@ -61,26 +72,15 @@ def classify0(inX, dataSet, labels, k): return sortedClassCount[0][0] def load_data(file_path): + """ + 加载 TSV 格式数据文件,并进行标准化处理。 + """ data = np.loadtxt(file_path, delimiter="\t") features = data[:, :-1] labels = data[:, -1].astype(int) features = (features - np.mean(features, axis=0)) / np.std(features, axis=0) return features, labels -def find_best_k(train_data, train_labels): - best_accuracy = 0 - best_k = 1 - for k in range(1, 26, 2): # 尝试奇数的 k 值,从 1 到 25 - correct_count = 0 - for i in range(train_data.shape[0]): - if classify0(train_data[i], train_data, train_labels, k) == train_labels[i]: - correct_count += 1 - accuracy = correct_count / train_data.shape[0] - if accuracy > best_accuracy: - best_accuracy = accuracy - best_k = k - return best_k - def preprocess_data(features): # 简单的异常值处理 Q1 = np.percentile(features, 25, axis=0) @@ -99,11 +99,9 @@ if __name__ == "__main__": train_data = preprocess_data(train_data) test_data = preprocess_data(test_data) - best_k = find_best_k(train_data, train_labels) - correct_count = 0 for i in range(test_data.shape[0]): - if classify0(test_data[i], train_data, train_labels, best_k) == test_labels[i]: + if classify0(test_data[i], train_data, train_labels, k=3) == test_labels[i]: correct_count += 1 - print(f"Accuracy with best k = {best_k}: {correct_count / test_data.shape[0] * 100:.2f}%") \ No newline at end of file + print(f"Accuracy: {correct_count / test_data.shape[0] * 100:.2f}%") \ No newline at end of file