diff --git a/function.py b/function.py index c9afc74..85e1684 100644 --- a/function.py +++ b/function.py @@ -42,8 +42,9 @@ name = "章程鸿" # 这里写自己的代码实现 import numpy as np from collections import Counter +from sklearn.preprocessing import MinMaxScaler -def classify0(inX, dataSet, labels, k=2): +def classify0(inX, dataSet, labels, k=3): """ KNN 分类算法。 @@ -53,8 +54,9 @@ def classify0(inX, dataSet, labels, k=2): - labels (list or numpy array): 训练集对应的标签。 - k (int): KNN 算法参数,默认为3。 - Returns: + Returns: - int: 预测的分类标签。 + """ # 计算距离 diffMat = inX - dataSet @@ -64,26 +66,46 @@ def classify0(inX, dataSet, labels, k=2): # 排序并选取前k个最小距离 sortedDistIndices = distances.argsort() - classCount = {} - - for i in range(k): - voteIlabel = labels[sortedDistIndices[i]] - classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 - + classCount = Counter(labels[sortedDistIndices[:k]]) + # 返回出现频率最高的类别 - sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True) - return sortedClassCount[0][0] + return classCount.most_common(1)[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 +def preprocess_data(features): + """ + 特征预处理,包括归一化。 + """ + scaler = MinMaxScaler() + normalized_features = scaler.fit_transform(features) + return normalized_features if __name__ == "__main__": - # 以下代码可用于测试,可自行随意修改 train_file = "datingTrainSet2.tsv" train_data, train_labels = load_data(train_file) + train_data_normalized = preprocess_data(train_data) - # 测试数据点 - test_point = np.array([65915, 3.868359, 0.128078]) - predicted_label = classify0(test_point, train_data, train_labels) - print("预测的分类标签是:", predicted_label) + # 选择几个有代表性的测试数据点 + test_points = [ + [26052, 1.441871, 0.805124], # 实际标签是 1 + [38344, 1.669788, 0.134296], # 实际标签是 1 + [28488, 10.528555, 1.304844], # 实际标签是 3 + [22620, 5.297865, 0.638306], # 实际标签是 2 + [28567, 9.968648, 0.731232], # 实际标签是 3 + [41611, 0.230453, 1.151996] # 实际标签是 1 + ] + + for point in test_points: + normalized_point = preprocess_data(np.array([point]))[0] + predicted_label = classify0(normalized_point, train_data_normalized, train_labels) + print(f"测试数据 {point} 预测标签: {predicted_label}")