From a3a1d0d6a7686e2cf4554e1b91a53946a9bd0cb8 Mon Sep 17 00:00:00 2001 From: zhangchenghong <1598349064@qq.com> Date: Thu, 31 Oct 2024 16:54:38 +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 | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/function.py b/function.py index 68c6c40..ad04fe9 100644 --- a/function.py +++ b/function.py @@ -27,7 +27,7 @@ name = "章程鸿" # 这里写自己的代码实现 import numpy as np - +from sklearn.model_selection import KFold def sigmoid(z): return 1 / (1 + np.exp(-z)) @@ -92,6 +92,21 @@ def load_data(filepath): X = data[:, :-1] y = data[:, -1] return X, y +def cross_validate(X, y, k=5, learning_rate=0.01, iterations=1000): + kf = KFold(n_splits=k) + accuracies = [] + + for train_index, test_index in kf.split(X): + X_train, X_test = X[train_index], X[test_index] + y_train, y_test = y[train_index], y[test_index] + + weights = train_logreg(X_train, y_train, learning_rate, iterations) + predictions = [predict_logreg(x, weights) for x in X_test] + + accuracy = np.mean(predictions == y_test) + accuracies.append(accuracy) + + return np.mean(accuracies) if __name__ == "__main__": # 以下代码可用于测试,可自行随意修改 @@ -102,8 +117,7 @@ if __name__ == "__main__": X_test, y_test = load_data("./data/horse-colic.test") # 训练对率回归模型 - weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=10000) + k = 5 # 设置折数 + accuracy = cross_validate(X, y, k=k, learning_rate=0.01, iterations=5000) - # 测试单个数据 - y_pred = predict_logreg(X_test[11], weights) - print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") + print(f"{k}-折交叉验证的平均准确率: {accuracy:.2f}")