From 53cc0dae552250b2ba7dc73451483c2a447eba8b Mon Sep 17 00:00:00 2001 From: 202210423104 <1961532386@qq.com> Date: Sun, 3 Nov 2024 16:42:27 +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 | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/function.py b/function.py index 5968393..ca305c7 100644 --- a/function.py +++ b/function.py @@ -1,7 +1,6 @@ import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import PolynomialFeatures, StandardScaler -from sklearn.metrics import accuracy_score, f1_score id = "202210423104" name = "张钦诚" @@ -29,7 +28,7 @@ def preprocess_data(X, scaler=None, poly=None): X_standardized = scaler.fit_transform(X) else: X_standardized = scaler.transform(X) - + if poly is None: poly = PolynomialFeatures(degree=2, include_bias=False) X_poly = poly.fit_transform(X_standardized) @@ -42,18 +41,14 @@ def train_logreg(X, y): X_processed, scaler, poly = preprocess_data(X) # 预处理训练数据 model = RandomForestClassifier(n_estimators=113, max_depth=10, random_state=42) model.fit(X_processed, y) - return model, scaler, poly # 返回训练好的模型及预处理器 + return model, scaler, poly # 返回训练好的模型和预处理对象 -def predict_logreg(model, X, scaler, poly): +def predict_logreg(X, model, scaler, poly): # 确保输入数据是一个 numpy 数组 if len(X.shape) == 1: - X = X.reshape(1, -1) # 保持输入数据的形状为 (1, n),符合模型的输入要求 + X = X.reshape(1, -1) # 保持输入数据的形状为 (1, n) X_processed, _, _ = preprocess_data(X, scaler, poly) # 预处理测试数据 - return model.predict(X_processed)[0] # 确保 model 是训练好的模型 + return model.predict(X_processed)[0] # 返回预测结果 if __name__ == "__main__": X, y = load_data("./data/horse-colic.data") - model, scaler, poly = train_logreg(X, y) # 训练模型 - y_pred = [predict_logreg(model, sample, scaler, poly) for sample in X] # 预测 - print(f"Accuracy: {accuracy_score(y, y_pred):.2f}") - print(f"F1 Score: {f1_score(y, y_pred, average='weighted'):.2f}")