# function.py import numpy as np """ 挑战说明: - 自行编写实现 KNN 分类算法。 - 函数输入: 待分类的样本 inX, 训练数据集 dataSet, 训练集对应的标签 labels。 - 函数返回: 预测的分类标签。 注意事项: - 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。 - 在 function.py 中实现 KNN 分类算法。 - 自动评测脚本仅会加载 classify0 函数,请勿修改函数名。 - 训练集在本目录下的 datingTrainSet2.tsv 中。 - 评测数据集在本目录下的 datingTestSet2.tsv 中。 挑战环境: - CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz - OS: Ubuntu 22.04.4 LTS - Python: 3.10.12 - numpy: 2.1.1 """ """ 请在这里填写学号和姓名,不填写即成绩无效。 """ id = "202210423109" name = "孔祥芷" """ 参数说明: - inX (numpy array): 输入待分类的样本。 - dataSet (numpy array): 训练数据集。 - labels (list or numpy array): 训练集对应的标签。 返回值: - int: 预测的分类标签。 """ # 这里写自己的代码实现 def load_data(file_path): """ 加载 TSV 格式数据文件。 Args: - file_path (str): 文件路径。 Returns: - features (numpy array): 特征数据。 - labels (numpy array): 标签数据。 """ data = np.loadtxt(file_path, delimiter="\t") features = data[:, :-1] labels = data[:, -1].astype(int) return features, labels def classify0(inX, dataSet, labels, k=3): """ KNN 分类算法。 Args: - inX (numpy array): 输入待分类的样本。 - dataSet (numpy array): 训练数据集。 - labels (list or numpy array): 训练集对应的标签。 - k (int): KNN 算法参数。 Returns: - int: 预测的分类标签。 """ dists = np.sum(np.abs(dataSet - inX), axis=1) sorted_index = np.argsort(dists) class_count = {} for i in range(k): vote_label = labels[sorted_index[i]] class_count[vote_label] = class_count.get(vote_label, 0) + 1 sorted_class_count = sorted(class_count.items(), key=lambda item: item[1], reverse=True) if sorted_class_count: return sorted_class_count[0][0] else: return -1 def load_data(file_path): data = np.loadtxt(file_path, delimiter="\t") features = data[:, :-1] labels = data[:, -1].astype(int) return features, labels def normalize(features): min_vals = features.min(axis=0) max_vals = features.max(axis=0) ranges = max_vals - min_vals normalized = (features - min_vals) / ranges normalized[ranges == 0] = 0 # 防止除以零的情况 return normalized if __name__ == "__main__": train_features, train_labels = load_data("datingTrainSet2.tsv") test_features, test_labels = load_data("datingTestSet2.tsv") # 在这里进行归一化处理 train_features = normalize(train_features) test_features = normalize(test_features) best_k = 3 best_accuracy = 0.0 for k in range(1, 10): # 尝试不同的 K 值 correct_count = 0 for i in range(len(test_features)): test_feature = test_features[i].reshape(1, -1) predict_label = classify0(test_feature, train_features, train_labels, k=k) if predict_label == -1: continue correct_count += (predict_label == test_labels[i]) accuracy = correct_count / len(test_features) print(f"Accuracy with k={k}: {accuracy:.2f}") if accuracy > best_accuracy: best_accuracy = accuracy best_k = k print(f"Best K: {best_k}, Best Accuracy: {best_accuracy:.2f}") accuracy = correct_count / len(test_features) print(f"Accuracy with k={k}: {accuracy:.2f}") if accuracy > best_accuracy: best_accuracy = accuracy best_k = k print(f"Best K: {best_k}, Best Accuracy: {best_accuracy:.2f}")