From 3eda544d807af5ab637dae0e8e5d88df417a0cfe Mon Sep 17 00:00:00 2001 From: Dengddd <3149942468@qq.com> Date: Thu, 31 Oct 2024 17:24:51 +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 | 34 ++++++++-------------------------- 1 file changed, 8 insertions(+), 26 deletions(-) diff --git a/function.py b/function.py index e144c58..109e848 100644 --- a/function.py +++ b/function.py @@ -26,6 +26,7 @@ name = "邓龙树" # user_code.py +import numpy as np from sklearn.preprocessing import StandardScaler def sigmoid(intX): @@ -47,7 +48,7 @@ def train_logreg(X, y, numIter=150): return weights -def predict(X, weights): +def predict_logreg(X, weights): predictions = [] for x in X: prob = sigmoid(np.dot(x, weights)) @@ -77,32 +78,13 @@ def load_data(filepath): def accuracy(X, y, weights): - predictions = predict(X, weights) + predictions = predict_logreg(X, weights) return np.mean(predictions == y) -def colicTest(): - X_train, y_train = load_data("./horse-colic.data") - X_test, y_test = load_data("./horse-colic.test") - trainWeights = train_logreg(X_train, y_train, 500) - errorCount = 0 - numTestVec = 0.0 - for x, true_label in zip(X_test, y_test): - if int(predict([x], trainWeights)[0])!= int(true_label): - errorCount += 1 - numTestVec += 1.0 - errorRate = (float(errorCount) / numTestVec) * 100 - print("测试集错误率为: %.2f%%" % errorRate) - - -def colicSklearn(): - X_train, y_train = load_data("./horse-colic.data") - X_test, y_test = load_data("./horse-colic.test") - classifier = LogisticRegression(solver='liblinear', max_iter=20).fit(X_train, y_train) - test_accurcy = classifier.score(X_test, y_test) * 100 - print('正确率:%f%%' % test_accurcy) - - if __name__ == '__main__': - # colicTest() - colicSklearn() + X_train, y_train = load_data("./horse-colic.data") + X_test, y_test = load_data("./horse-colic.test") + final_weights = train_logreg(X_train, y_train) + final_accuracy = accuracy(X_test, y_test, final_weights) + print(f"最终测试集的准确率: {final_accuracy:.4f}")