更新 function.py
Gitea Actions Challenge Test / Challenge-Actions (push) Successful in 12s

This commit is contained in:
2024-10-08 20:34:57 +08:00
parent 5d034ca174
commit 52d3419832
+24 -1
View File
@@ -83,10 +83,25 @@ def classify0(inX, dataSet, labels, k=3):
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__":
# 假设 load_data 和 normalize 函数已经定义
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)
@@ -110,5 +125,13 @@ if __name__ == "__main__":
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}")