From 5842e23dfef3d3009078260132b7c74c8fd5376e Mon Sep 17 00:00:00 2001 From: mogu-king <1547976000@qq.com> Date: Sun, 3 Nov 2024 05:35:17 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20function.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.py | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/function.py b/function.py index 72eff9f..050f4ae 100644 --- a/function.py +++ b/function.py @@ -26,6 +26,16 @@ name = "刘义天" def load_data(filepath): + """ + Load data from a specified file path and handle missing values. + + Args: + - filepath (str): The path to the data file. + + Returns: + - np.array: Feature data. + - np.array: Label data. + """ data = [] with open(filepath, 'r') as file: for line in file: @@ -44,6 +54,20 @@ def load_data(filepath): def train_logreg(X, y, learning_rate=0.1, n_estimators=200, max_depth=5): + """ + Train a Gradient Boosting model. + + Args: + - X (numpy array): Feature data. + - y (numpy array): Label data. + - learning_rate (float): Learning rate for gradient boosting. + - n_estimators (int): Number of trees. + - 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. + """ scaler = StandardScaler() X = scaler.fit_transform(X) @@ -54,10 +78,23 @@ def train_logreg(X, y, learning_rate=0.1, n_estimators=200, max_depth=5): random_state=42 ) gb_model.fit(X, y) + + # Return model and scaler separately return gb_model, scaler def predict_logreg(inX, model, scaler): + """ + 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. + + Returns: + - int: Predicted class label (0 or 1). + """ inX = scaler.transform([inX]) prediction = model.predict(inX) return int(prediction[0]) @@ -73,4 +110,4 @@ if __name__ == "__main__": # 测试单个数据 y_pred = predict_logreg(X_test[11], model, scaler) - print(f"预测结果: {y_pred}, 实际结果: {int(y_test[11])}") \ No newline at end of file + print(f"预测结果: {y_pred}, 实际结果: {int(y_test[11])}")