From 56eb877c824d1e74b0f76169ff7da5b2eebeab6b Mon Sep 17 00:00:00 2001 From: 202210423104 <1961532386@qq.com> Date: Sun, 3 Nov 2024 16:10:13 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=87=E4=BB=B6=E8=87=B3?= =?UTF-8?q?=20/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.py | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/function.py b/function.py index 0e76974..ed10793 100644 --- a/function.py +++ b/function.py @@ -1,4 +1,5 @@ import numpy as np +from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import PolynomialFeatures, StandardScaler @@ -30,17 +31,30 @@ def preprocess_data(X): return X_poly def train_logreg(X, y): - X_processed = preprocess_data(X) # 预处理训练数据 model = RandomForestClassifier(n_estimators=113, max_depth=10, random_state=42) - model.fit(X_processed, y) - return model # 返回训练好的模型 + model.fit(X, y) + return model -def predict_logreg(X, model): - # 确保输入数据是一个 numpy 数组 - if len(X.shape) == 1: - X = X.reshape(1, -1) # 保持输入数据的形状为 (1, n),符合模型的输入要求 - X_processed = preprocess_data(X) # 预处理测试数据 - return model.predict(X_processed)[0] # 确保 model 是训练好的模型 +def predict_logreg(model, X): + return model.predict(X) if __name__ == "__main__": + # 加载数据 X, y = load_data("./data/horse-colic.data") + + # 划分数据集 + X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + + # 数据预处理 + X_train_processed = preprocess_data(X_train) + X_test_processed = preprocess_data(X_test) + + # 训练模型 + model = train_logreg(X_train_processed, y_train) + + # 预测 + y_pred = predict_logreg(model, X_test_processed) + + # 计算正确率 + accuracy = np.mean(y_pred == y_test) + print(f"测试出的正确率: {accuracy * 100:.2f}%")