From 0ae03eaa1eac470926d46da9194ea90b07c2be7a Mon Sep 17 00:00:00 2001 From: zhangchenghong <1598349064@qq.com> Date: Tue, 8 Oct 2024 20:47:22 +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 | 75 ++++++++++++++++------------------------------------- 1 file changed, 23 insertions(+), 52 deletions(-) diff --git a/function.py b/function.py index 0dc7f22..f3f6268 100644 --- a/function.py +++ b/function.py @@ -40,56 +40,27 @@ name = "章程鸿" # 这里写自己的代码实现 -import numpy as np -from collections import Counter -def classify0(inX, dataSet, labels, k=1): - """ - KNN 分类算法。 - - Args: - - inX (numpy array): 输入待分类的样本。 - - dataSet (numpy array): 训练数据集。 - - labels (list or numpy array): 训练集对应的标签。 - - k (int): KNN 算法参数,默认为3。 - - Returns: - - int: 预测的分类标签。 - """ - # 计算距离 - diffMat = inX - dataSet - sqDiffMat = diffMat ** 2 - sqDistances = sqDiffMat.sum(axis=1) - distances = sqDistances ** 0.5 - - # 排序并选取前k个最小距离 - sortedDistIndices = distances.argsort() - classCount = {} - - for i in range(k): - voteIlabel = labels[sortedDistIndices[i]] - classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 - - # 返回出现频率最高的类别 - sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True) - 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) - return features, labels - -if __name__ == "__main__": - # 以下代码可用于测试,可自行随意修改 - train_file = "datingTrainSet2.tsv" - - train_data, train_labels = load_data(train_file) - - # 测试数据点 - test_point = np.array([65915, 3.868359, 0.128078]) - predicted_label = classify0(test_point, train_data, train_labels) - print("预测的分类标签是:", predicted_label) \ No newline at end of file +def normalize_data(data): + """ + 对数据进行Min-Max归一化。 + + Args: + - data (numpy array): 原始数据。 + + Returns: + - numpy array: 归一化后的数据。 + """ + min_vals = np.min(data, axis=0) + max_vals = np.max(data, axis=0) + ranges = max_vals - min_vals + norm_data = np.where(ranges == 0, 0, (data - min_vals) / ranges) + return norm_data + +# 在加载数据后调用归一化函数 +train_data_normalized = normalize_data(train_data) +test_point_normalized = normalize_data(test_point.reshape(1, -1))[0] # 注意test_point需要reshape为二维数组 + +# 使用归一化后的数据进行分类 +predicted_label_normalized = classify0(test_point_normalized, train_data_normalized, train_labels) +print("归一化后预测的分类标签是:", predicted_label_normalized) \ No newline at end of file