generated from LufsX/Experiment-LogReg
This commit is contained in:
+23
-9
@@ -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}%")
|
||||
|
||||
Reference in New Issue
Block a user