generated from LufsX/Experiment-LogReg
This commit is contained in:
+9
-10
@@ -65,8 +65,7 @@ def train_logreg(X, y, learning_rate=0.1, n_estimators=200, max_depth=5):
|
||||
- max_depth (int): Maximum depth of each tree.
|
||||
|
||||
Returns:
|
||||
- GradientBoostingClassifier: Trained Gradient Boosting model as weights.
|
||||
- StandardScaler: Scaler fitted on training data for consistent scaling.
|
||||
- tuple: (Trained model and scaler) packed into 'weights' for predict_logreg compatibility.
|
||||
"""
|
||||
scaler = StandardScaler()
|
||||
X = scaler.fit_transform(X)
|
||||
@@ -79,23 +78,23 @@ def train_logreg(X, y, learning_rate=0.1, n_estimators=200, max_depth=5):
|
||||
)
|
||||
gb_model.fit(X, y)
|
||||
|
||||
# Return model and scaler separately
|
||||
return gb_model, scaler
|
||||
# Pack both model and scaler as weights
|
||||
return (gb_model, scaler)
|
||||
|
||||
|
||||
def predict_logreg(inX, model, scaler):
|
||||
def predict_logreg(inX, weights):
|
||||
"""
|
||||
Predict the class label for a given sample using Gradient Boosting.
|
||||
|
||||
Args:
|
||||
- inX (numpy array): Input sample for classification.
|
||||
- model (GradientBoostingClassifier): Trained model.
|
||||
- scaler (StandardScaler): Scaler for feature normalization.
|
||||
- weights (tuple): Packed tuple containing trained model and scaler.
|
||||
|
||||
Returns:
|
||||
- int: Predicted class label (0 or 1).
|
||||
"""
|
||||
inX = scaler.transform([inX])
|
||||
model, scaler = weights # Unpack model and scaler
|
||||
inX = scaler.transform([inX]) # Scale input
|
||||
prediction = model.predict(inX)
|
||||
return int(prediction[0])
|
||||
|
||||
@@ -106,8 +105,8 @@ if __name__ == "__main__":
|
||||
X_test, y_test = load_data("./data/horse-colic.test")
|
||||
|
||||
# 训练模型
|
||||
model, scaler = train_logreg(X_train, y_train)
|
||||
weights = train_logreg(X_train, y_train)
|
||||
|
||||
# 测试单个数据
|
||||
y_pred = predict_logreg(X_test[11], model, scaler)
|
||||
y_pred = predict_logreg(X_test[11], weights)
|
||||
print(f"预测结果: {y_pred}, 实际结果: {int(y_test[11])}")
|
||||
|
||||
Reference in New Issue
Block a user