diff --git a/function.py b/function.py index c9f3001..e214da1 100644 --- a/function.py +++ b/function.py @@ -41,6 +41,24 @@ name = "孔祥芷" # 这里写自己的代码实现 +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 分类算法。 @@ -66,56 +84,32 @@ def classify0(inX, dataSet, labels, k=3): else: return -1 -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 standardize(features): - mean = np.mean(features, axis=0) - std = np.std(features, axis=0) - standardized = (features - mean) / std - return standardized +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_file_path = "datingTrainSet2.tsv" train_features, train_labels = load_data(train_file_path) - test_file_path = "datingTestSet2.tsv" test_features, test_labels = load_data(test_file_path) - - # 特征标准化 - train_features = standardize(train_features) - test_features = standardize(test_features) - - # 尝试不同的 K 值 - best_k = 3 - best_accuracy = 0.0 - - for k in [1, 3, 5, 7, 9]: - 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}") + + # 归一化特征 + train_features = normalize(train_features) + test_features = normalize(test_features) + + 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=3) + if predict_label == -1: + continue + correct_count += (predict_label == test_labels[i]) + + accuracy = correct_count / len(test_features) + print(f"Accuracy: {accuracy:.2f}")