From af98d5ec62b4575ff746c9ff58eb63119bd244d9 Mon Sep 17 00:00:00 2001 From: 202210423104 <1961532386@qq.com> Date: Sun, 3 Nov 2024 17:01:44 +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 | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/function.py b/function.py index a00a9fa..f255971 100644 --- a/function.py +++ b/function.py @@ -1,10 +1,14 @@ import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import PolynomialFeatures, StandardScaler +from sklearn.impute import SimpleImputer +from sklearn.metrics import accuracy_score +from sklearn.model_selection import train_test_split id = "202210423104" name = "张钦诚" + def load_data(filepath): data = [] with open(filepath, 'r') as file: @@ -16,12 +20,14 @@ def load_data(filepath): except ValueError as e: print(f"Error processing line: {line}. Error: {e}") data = np.array(data) - data = np.nan_to_num(data, nan=np.nanmean(data, axis=0)) + imputer = SimpleImputer(strategy='mean') + data = imputer.fit_transform(data) X = data[:, :-1] # 特征 - y = data[:, -1] # 标签 + y = data[:, -1] # 标签 return X, y + def preprocess_data(X): scaler = StandardScaler() X_standardized = scaler.fit_transform(X) @@ -29,18 +35,33 @@ def preprocess_data(X): X_poly = poly.fit_transform(X_standardized) return X_poly + def train_logreg(X, y): X_processed = preprocess_data(X) # 预处理训练数据 - model = RandomForestClassifier(n_estimators=200, max_depth=20, random_state=42) + model = RandomForestClassifier(n_estimators=200, max_depth=20, min_samples_split=5, random_state=42) 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 = X.reshape(1, -1) # 保持输入数据的形状为 (1, n) X_processed = preprocess_data(X) # 预处理测试数据 return model.predict(X_processed)[0] # 确保 model 是训练好的模型 + 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 = model.predict(preprocess_data(X_test)) + + # 计算准确率 + accuracy = accuracy_score(y_test, y_pred) + print(f"Accuracy: {accuracy:.2f}")