From aadc69da6e5fd0c56e6858b457ea5ad753512acb Mon Sep 17 00:00:00 2001 From: 202210423104 <1961532386@qq.com> Date: Sun, 3 Nov 2024 16:20:18 +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 | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/function.py b/function.py index 0e76974..185680b 100644 --- a/function.py +++ b/function.py @@ -1,6 +1,7 @@ import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import PolynomialFeatures, StandardScaler +from sklearn.model_selection import train_test_split, cross_val_score id = "202210423104" name = "张钦诚" @@ -35,12 +36,29 @@ def train_logreg(X, y): model.fit(X_processed, 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): + X_processed = preprocess_data(X.reshape(1, -1)) # 预处理单个测试样本 + return model.predict(X_processed)[0] # 预测并返回结果 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) + + # 训练模型 + model = train_logreg(X_train, y_train) + + # 预测 + y_pred = [] + for sample in X_test: + y_pred.append(predict_logreg(model, sample)) + + # 计算准确率 + accuracy = np.mean(y_pred == y_test) + print(f"测试出的正确率: {accuracy * 100:.2f}%") + + # 交叉验证 + cv_scores = cross_val_score(model, preprocess_data(X_train), y_train, cv=5) + print(f"交叉验证准确率: {np.mean(cv_scores) * 100:.2f}%")