aigo25 / train.py
hibana2077's picture
Refactor data loading and hyperparameter tuning for improved model performance
f23b6eb
import polars as pl
import tsfel
import numpy as np
from tqdm import tqdm
import warnings
import os
import optuna # Added import for Optuna
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import FunctionTransformer
from sklearn.base import BaseEstimator, TransformerMixin
from xgboost import XGBClassifier
from lightgbm import LGBMClassifier
from cfg import DROP_LIST
# Rest of the imports and class definitions remain unchanged...
def load_and_balance_data(filename, ratio=1/60):
"""
Loads data from a CSV file and balances classes to address potential imbalance.
Args:
filename (str): Path to the CSV file
ratio (float): Ratio of positive to negative examples to balance
Returns:
pl.DataFrame: Balanced dataframe
"""
print(f"Ratio: {ratio}")
# Load the CSV file
data = pl.read_csv(filename)
positive = data.filter(pl.col("飆股") == 1)
negative = data.filter(pl.col("飆股") == 0)
# Balance the classes
negative = negative.sample(fraction=ratio)
# Combine the balanced classes
combined = positive.vstack(negative)
return combined
def create_stock_prediction_pipeline(params=None):
start_end_list = [
# ("個股", "收盤價"),
# ("上市加權指數", "收盤價"),
# ("外資券商", "分點進出"),
# ("主力券商", "分點進出"),
# ("個股", "成交量")
]
# Use default parameters if none provided
if params is None:
classifier = XGBClassifier(n_jobs=-1)
else:
classifier = XGBClassifier(
# booster="dart",
n_jobs=-1,
**params
)
pipeline = Pipeline([
# ('time_series_features', TimeSeriesFeatureExtractor(start_end_list=start_end_list)),
('classifier', classifier)
])
return pipeline
def objective(trial, X, y):
"""Optuna objective function for hyperparameter tuning"""
# Define the hyperparameters to tune
params = {
# 'booster': trial.suggest_categorical('booster', ['gbtree', 'dart']),
'learning_rate': trial.suggest_float('learning_rate', 0.001, 0.3, log=True),
'max_depth': trial.suggest_int('max_depth', 3, 140),
'n_estimators': trial.suggest_int('n_estimators', 50, 3000),
'subsample': trial.suggest_float('subsample', 0.5, 1.0),
'colsample_bytree': trial.suggest_float('colsample_bytree', 0.5, 1.0),
'gamma': trial.suggest_float('gamma', 0, 5),
'min_child_weight': trial.suggest_int('min_child_weight', 1, 10),
'reg_alpha': trial.suggest_float('reg_alpha', 0, 10),
'reg_lambda': trial.suggest_float('reg_lambda', 1, 10)
}
# Create and evaluate the pipeline
pipeline = create_stock_prediction_pipeline(params)
# Use 3-fold cross validation for stability
scores = cross_val_score(pipeline, X, y, cv=3, scoring='f1')
# Return the mean F1 score
return scores.mean()
def main():
# Load and preprocess training data
print("Loading and preprocessing training data...")
combined = load_and_balance_data('./cleaned_training.csv', ratio=1/90)
# Define features and target
X = combined.drop(DROP_LIST)
y = combined["飆股"]
# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Hyperparameter tuning with Optuna
print("Starting hyperparameter optimization with Optuna...")
study = optuna.create_study(direction='maximize') # We want to maximize the F1 score
study.optimize(lambda trial: objective(trial, X_train, y_train), n_trials=100, show_progress_bar=True)
# Print the best parameters
best_params = study.best_params
best_value = study.best_value
print(f"Best F1 score: {best_value:.4f}")
print("Best hyperparameters:", best_params)
# Create and train the pipeline with the best parameters
print("Training final model with the best parameters...")
pipeline = create_stock_prediction_pipeline(best_params)
pipeline.fit(X_train, y_train)
# Evaluate the model
print("Evaluating the model...")
y_pred = pipeline.predict(X_test)
# Calculate metrics
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, confusion_matrix
accuracy = accuracy_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.4f}")
print(f"F1 Score: {f1:.4f}")
print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
# Confusion matrix
cm = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(cm)
# Load and predict on test data
print("Loading test data and making predictions...")
test = pl.read_csv('./38_Public_Test_Set_and_Submmision_Template/38_Public_Test_Set_and_Submmision_Template/public_x.csv')
template = pl.read_csv('./38_Public_Test_Set_and_Submmision_Template/38_Public_Test_Set_and_Submmision_Template/submission_template_public.csv')
# Ensure test data has the same columns as training data
selected = test.select(X.columns)
# Make predictions
y_pred_test = pipeline.predict(selected)
# Count predictions
unique, counts = np.unique(y_pred_test, return_counts=True)
print("Prediction counts:", dict(zip(unique, counts)))
# Save predictions to submission file
template = template.with_columns(pl.Series("飆股", y_pred_test))
template.write_csv("submission.csv")
print("Predictions saved to submission.csv")
if __name__ == "__main__":
main()