generated from LufsX/Experiment-LogReg
This commit is contained in:
+5
-15
@@ -1,7 +1,6 @@
|
||||
import numpy as np
|
||||
from sklearn.ensemble import RandomForestClassifier
|
||||
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
|
||||
from sklearn.model_selection import GridSearchCV
|
||||
|
||||
id = "202210423104"
|
||||
name = "张钦诚"
|
||||
@@ -26,26 +25,17 @@ def load_data(filepath):
|
||||
def preprocess_data(X):
|
||||
scaler = StandardScaler()
|
||||
X_standardized = scaler.fit_transform(X)
|
||||
poly = PolynomialFeatures(degree=3, include_bias=False) # 尝试更高的次数
|
||||
poly = PolynomialFeatures(degree=2, include_bias=False)
|
||||
X_poly = poly.fit_transform(X_standardized)
|
||||
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 # 返回训练好的模型
|
||||
|
||||
# 使用网格搜索调参
|
||||
param_grid = {
|
||||
'n_estimators': [100, 200, 300],
|
||||
'max_depth': [5, 10, 15],
|
||||
'class_weight': ['balanced', None] # 处理不平衡数据
|
||||
}
|
||||
|
||||
model = RandomForestClassifier(random_state=42)
|
||||
grid_search = GridSearchCV(model, param_grid, cv=5)
|
||||
grid_search.fit(X_processed, y)
|
||||
return grid_search.best_estimator_ # 返回最佳模型
|
||||
|
||||
def predict_logreg(model, X):
|
||||
def predict_logreg(X, model):
|
||||
# 确保输入数据是一个 numpy 数组
|
||||
if len(X.shape) == 1:
|
||||
X = X.reshape(1, -1) # 保持输入数据的形状为 (1, n),符合模型的输入要求
|
||||
|
||||
Reference in New Issue
Block a user