From 84423f7537664e087c63d9a2a93dfb23e6626331 Mon Sep 17 00:00:00 2001 From: 202210423104 <1961532386@qq.com> Date: Sun, 3 Nov 2024 17:24:08 +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 | 33 ++++++++++++--------------------- 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/function.py b/function.py index d2bd3bb..aaae632 100644 --- a/function.py +++ b/function.py @@ -3,12 +3,11 @@ 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, GridSearchCV +from sklearn.model_selection import train_test_split id = "202210423104" name = "张钦诚" - def load_data(filepath): data = [] with open(filepath, 'r') as file: @@ -27,7 +26,6 @@ def load_data(filepath): y = data[:, -1] # 标签 return X, y - def preprocess_data(X): scaler = StandardScaler() X_standardized = scaler.fit_transform(X) @@ -35,24 +33,17 @@ def preprocess_data(X): X_poly = poly.fit_transform(X_standardized) return X_poly - def train_logreg(X, y): X_processed = preprocess_data(X) # 预处理训练数据 - - # 超参数调优 - param_grid = { - 'n_estimators': [100, 200, 300], - 'max_depth': [None, 15, 25], - 'min_samples_split': [2, 5, 10], - 'class_weight': ['balanced', None] - } - - model = RandomForestClassifier(random_state=42) - grid_search = GridSearchCV(model, param_grid, cv=5, scoring='accuracy', n_jobs=-1) - grid_search.fit(X_processed, y) - - return grid_search.best_estimator_ # 返回最佳模型 - + model = RandomForestClassifier( + n_estimators=300, # 增加树的数量 + max_depth=25, # 调整最大深度 + min_samples_split=5, + class_weight='balanced', # 处理类别不平衡 + random_state=42 # 固定随机种子 + ) + model.fit(X_processed, y) + return model # 返回训练好的模型 def predict_logreg(X, model): if len(X.shape) == 1: @@ -60,11 +51,11 @@ def predict_logreg(X, model): 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) # 训练模型