generated from LufsX/Experiment-LogReg
This commit is contained in:
+4
-9
@@ -1,7 +1,6 @@
|
||||
import numpy as np
|
||||
from sklearn.ensemble import RandomForestClassifier
|
||||
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
|
||||
from sklearn.metrics import accuracy_score, f1_score
|
||||
|
||||
id = "202210423104"
|
||||
name = "张钦诚"
|
||||
@@ -42,18 +41,14 @@ def train_logreg(X, y):
|
||||
X_processed, scaler, poly = preprocess_data(X) # 预处理训练数据
|
||||
model = RandomForestClassifier(n_estimators=113, max_depth=10, random_state=42)
|
||||
model.fit(X_processed, y)
|
||||
return model, scaler, poly # 返回训练好的模型及预处理器
|
||||
return model, scaler, poly # 返回训练好的模型和预处理对象
|
||||
|
||||
def predict_logreg(model, X, scaler, poly):
|
||||
def predict_logreg(X, model, scaler, poly):
|
||||
# 确保输入数据是一个 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, scaler, poly) # 预处理测试数据
|
||||
return model.predict(X_processed)[0] # 确保 model 是训练好的模型
|
||||
return model.predict(X_processed)[0] # 返回预测结果
|
||||
|
||||
if __name__ == "__main__":
|
||||
X, y = load_data("./data/horse-colic.data")
|
||||
model, scaler, poly = train_logreg(X, y) # 训练模型
|
||||
y_pred = [predict_logreg(model, sample, scaler, poly) for sample in X] # 预测
|
||||
print(f"Accuracy: {accuracy_score(y, y_pred):.2f}")
|
||||
print(f"F1 Score: {f1_score(y, y_pred, average='weighted'):.2f}")
|
||||
|
||||
Reference in New Issue
Block a user