# ============================================================ # F1 LIVE WINNER PREDICTION # COMPRESSED LAP-LEVEL DATA # XGBOOST + OPTUNA # # ENVIRONMENT: # VS CODE / LOCAL PYTHON # # INPUT: # F1_2026_compressed_merged.csv # # OUTPUT: # F1_Model/ # f1_live_winner_model.pkl # f1_live_winner_best_params.json # f1_live_winner_optuna_study.pkl # f1_live_winner_feature_importance.csv # f1_live_winner_feature_schema.json # ============================================================ # ============================================================ # 1. INSTALL REQUIRED PACKAGES # ============================================================ # Run this ONCE in your VS Code terminal if required: # # pip install pandas numpy scikit-learn xgboost optuna joblib # # Do NOT put the pip command inside the Python script. # ============================================================ # 2. IMPORTS # ============================================================ import json import warnings from pathlib import Path import joblib import numpy as np import optuna import pandas as pd import xgboost as xgb from sklearn.compose import ColumnTransformer from sklearn.impute import SimpleImputer from sklearn.metrics import ( accuracy_score, log_loss, roc_auc_score ) from sklearn.pipeline import Pipeline from sklearn.preprocessing import OneHotEncoder warnings.filterwarnings("ignore") # ============================================================ # 3. CONFIGURATION # ============================================================ # ------------------------------------------------------------ # INPUT DATASET # # Keep the CSV in the same folder as this Python script. # ------------------------------------------------------------ DATASET_PATH = "C:\\Users\\Admin\\Desktop\\PitLane\\F1_2026_model_training_data.csv" # ------------------------------------------------------------ # OUTPUT DIRECTORY # ------------------------------------------------------------ OUTPUT_DIR = "F1_Model" Path( OUTPUT_DIR ).mkdir( parents=True, exist_ok=True ) # ------------------------------------------------------------ # OUTPUT FILES # ------------------------------------------------------------ MODEL_OUTPUT = ( f"{OUTPUT_DIR}/f1_live_winner_model.pkl" ) PARAMS_OUTPUT = ( f"{OUTPUT_DIR}/f1_live_winner_best_params.json" ) STUDY_OUTPUT = ( f"{OUTPUT_DIR}/f1_live_winner_optuna_study.pkl" ) FEATURE_IMPORTANCE_OUTPUT = ( f"{OUTPUT_DIR}/f1_live_winner_feature_importance.csv" ) FEATURE_SCHEMA_OUTPUT = ( f"{OUTPUT_DIR}/f1_live_winner_feature_schema.json" ) # ------------------------------------------------------------ # GENERAL SETTINGS # ------------------------------------------------------------ RANDOM_STATE = 42 # Increase this after the pipeline is working correctly. N_TRIALS = 50 TARGET_COLUMN = "Winner" RACE_COLUMN = "RaceDate" DRIVER_COLUMN = "Driver" # ============================================================ # 4. LOAD DATASET # ============================================================ print("=" * 80) print("F1 LIVE WINNER MODEL TRAINING") print("=" * 80) dataset_path = Path( DATASET_PATH ) if not dataset_path.exists(): raise FileNotFoundError( "\nDataset not found:\n" f"{dataset_path.resolve()}\n\n" "Place the CSV in the same folder as this script " "or change DATASET_PATH." ) print("\nLoading compressed dataset...") df = pd.read_csv( dataset_path, low_memory=False ) print( f"Rows : {len(df):,}" ) print( f"Columns : {len(df.columns)}" ) # ============================================================ # 5. REQUIRED COLUMN VALIDATION # ============================================================ required_columns = [ RACE_COLUMN, DRIVER_COLUMN, TARGET_COLUMN ] missing_columns = [ column for column in required_columns if column not in df.columns ] if missing_columns: raise ValueError( "\nMissing required columns:\n" + "\n".join(missing_columns) ) # ============================================================ # 6. PARSE RACE DATE # ============================================================ print("\nPreparing race dates...") df[RACE_COLUMN] = pd.to_datetime( df[RACE_COLUMN], errors="coerce" ) invalid_dates = ( df[RACE_COLUMN] .isna() .sum() ) if invalid_dates > 0: print( f"WARNING: {invalid_dates:,} rows have invalid RaceDate." ) df = df[ df[RACE_COLUMN].notna() ].copy() # ============================================================ # 7. CLEAN DRIVER # ============================================================ df[DRIVER_COLUMN] = ( df[DRIVER_COLUMN] .fillna("UNKNOWN") .astype(str) ) # ============================================================ # 8. CLEAN TARGET # ============================================================ df[TARGET_COLUMN] = pd.to_numeric( df[TARGET_COLUMN], errors="coerce" ) invalid_targets = ( ~df[TARGET_COLUMN].isin([0, 1]) ) if invalid_targets.any(): print( f"WARNING: Removing " f"{invalid_targets.sum():,} rows " "with invalid Winner values." ) df = df[ ~invalid_targets ].copy() df[TARGET_COLUMN] = ( df[TARGET_COLUMN] .astype(int) ) # ============================================================ # 9. SORT DATA CHRONOLOGICALLY # ============================================================ sort_columns = [ RACE_COLUMN, DRIVER_COLUMN ] if "LapNumber" in df.columns: sort_columns.append( "LapNumber" ) df = ( df .sort_values( sort_columns, kind="stable" ) .reset_index( drop=True ) ) # ============================================================ # 10. CHECK AVAILABLE RACES # ============================================================ race_dates = ( df[RACE_COLUMN] .drop_duplicates() .sort_values() .to_numpy() ) number_of_races = len( race_dates ) print( f"\nUnique races: " f"{number_of_races}" ) if number_of_races < 5: raise ValueError( f"Only {number_of_races} races were found.\n" "You need more races for a meaningful " "train/validation/test split." ) # ============================================================ # 11. VALIDATE ONE WINNER PER RACE # ============================================================ print("\n") print("=" * 80) print("VALIDATING TARGET") print("=" * 80) winner_counts = ( df .groupby( RACE_COLUMN )[TARGET_COLUMN] .sum() ) invalid_races = winner_counts[ winner_counts != 1 ] if not invalid_races.empty: print( "\nWARNING:" ) print( "The following races do not have exactly " "one Winner=1:" ) for race, count in ( invalid_races.items() ): print( f" {race.date()} -> " f"{count}" ) else: print( "Target validation PASSED." ) print( "Every race has exactly one Winner=1." ) # ============================================================ # 12. CHRONOLOGICAL RACE SPLIT # ============================================================ print("\n") print("=" * 80) print("CREATING CHRONOLOGICAL RACE SPLIT") print("=" * 80) # ------------------------------------------------------------ # 70% TRAIN # 15% VALIDATION # 15% TEST # # Split by WHOLE RACES, never individual rows. # ------------------------------------------------------------ train_count = max( 1, int( number_of_races * 0.70 ) ) validation_count = max( 1, int( number_of_races * 0.15 ) ) # Guarantee test races if ( train_count + validation_count >= number_of_races ): train_count = ( number_of_races - 2 ) validation_count = 1 train_races = race_dates[ :train_count ] validation_races = race_dates[ train_count: train_count + validation_count ] test_races = race_dates[ train_count + validation_count: ] print( f"\nTraining races : " f"{len(train_races)}" ) print( f"Validation races : " f"{len(validation_races)}" ) print( f"Test races : " f"{len(test_races)}" ) print("\nTRAINING RACES") for race in train_races: print( f" {pd.Timestamp(race).date()}" ) print("\nVALIDATION RACES") for race in validation_races: print( f" {pd.Timestamp(race).date()}" ) print("\nTEST RACES") for race in test_races: print( f" {pd.Timestamp(race).date()}" ) # ============================================================ # 13. CREATE SPLIT DATASETS # ============================================================ train_df = df[ df[RACE_COLUMN] .isin(train_races) ].copy() validation_df = df[ df[RACE_COLUMN] .isin(validation_races) ].copy() test_df = df[ df[RACE_COLUMN] .isin(test_races) ].copy() print("\nSplit sizes:") print( f"Training : " f"{len(train_df):,}" ) print( f"Validation : " f"{len(validation_df):,}" ) print( f"Test : " f"{len(test_df):,}" ) # ============================================================ # 14. RACE-BALANCED SAMPLE WEIGHTS # ============================================================ def create_race_balanced_weights( dataframe ): """ Each driver receives approximately equal total weight within each race. This prevents a driver/race with more telemetry/lap rows from dominating the training objective simply because it has more observations. """ weights = pd.Series( 0.0, index=dataframe.index, dtype=float ) for race_date, race_group in ( dataframe.groupby( RACE_COLUMN ) ): drivers = ( race_group[ DRIVER_COLUMN ] .nunique() ) if drivers <= 0: continue for driver, driver_group in ( race_group.groupby( DRIVER_COLUMN ) ): row_count = len( driver_group ) if row_count <= 0: continue weight = ( 1.0 / drivers / row_count ) weights.loc[ driver_group.index ] = weight mean_weight = ( weights.mean() ) if mean_weight > 0: weights = ( weights / mean_weight ) return weights.to_numpy() train_weights = ( create_race_balanced_weights( train_df ) ) validation_weights = ( create_race_balanced_weights( validation_df ) ) test_weights = ( create_race_balanced_weights( test_df ) ) # ============================================================ # 15. PREPARE MODEL INPUT # ============================================================ def prepare_X( dataframe ): data = dataframe.copy() # -------------------------------------------------------- # TARGET / METADATA / LEAKAGE # -------------------------------------------------------- drop_columns = [ # Target TARGET_COLUMN, # Used only for chronological splitting RACE_COLUMN, # Defensive protection against accidental leakage "winning_driver_number", "WinningDriver", "WinningDriverName", # Race/session metadata "RaceID", "session_key", "meeting_key", "location", "country_name", "RoundNumber", "EventName", # Internal fields "_RaceDate", "RaceDate" ] data = data.drop( columns=[ column for column in drop_columns if column in data.columns ], errors="ignore" ) return data X_train = prepare_X( train_df ) X_validation = prepare_X( validation_df ) X_test = prepare_X( test_df ) y_train = ( train_df[TARGET_COLUMN] ) y_validation = ( validation_df[TARGET_COLUMN] ) y_test = ( test_df[TARGET_COLUMN] ) # ============================================================ # 16. FORCE IDENTICAL FEATURE ORDER # ============================================================ feature_columns = ( X_train.columns.tolist() ) X_validation = ( X_validation .reindex( columns=feature_columns ) ) X_test = ( X_test .reindex( columns=feature_columns ) ) print("\n") print("=" * 80) print("MODEL FEATURE SCHEMA") print("=" * 80) print( f"\nRaw model features: " f"{len(feature_columns)}" ) # ============================================================ # 17. IDENTIFY NUMERIC / CATEGORICAL FEATURES # ============================================================ numeric_features = ( X_train .select_dtypes( include=[ "number", "bool" ] ) .columns .tolist() ) categorical_features = [ column for column in feature_columns if column not in numeric_features ] print( f"Numeric features : " f"{len(numeric_features)}" ) print( f"Categorical features : " f"{len(categorical_features)}" ) # ============================================================ # 18. PREPROCESSING PIPELINE # ============================================================ print( "\nCreating preprocessing pipeline..." ) numeric_pipeline = Pipeline( steps=[ ( "imputer", SimpleImputer( strategy="median" ) ) ] ) categorical_pipeline = Pipeline( steps=[ ( "imputer", SimpleImputer( strategy="most_frequent" ) ), ( "encoder", OneHotEncoder( handle_unknown="ignore", sparse_output=True ) ) ] ) preprocessor = ColumnTransformer( transformers=[ ( "numeric", numeric_pipeline, numeric_features ), ( "categorical", categorical_pipeline, categorical_features ) ], remainder="drop" ) # ============================================================ # 19. FIT PREPROCESSOR ONLY ON TRAINING DATA # ============================================================ print( "Fitting preprocessing pipeline " "on training data..." ) X_train_processed = ( preprocessor .fit_transform( X_train ) ) X_validation_processed = ( preprocessor .transform( X_validation ) ) X_test_processed = ( preprocessor .transform( X_test ) ) print( f"Processed training features: " f"{X_train_processed.shape[1]}" ) # ============================================================ # 20. OPTUNA OBJECTIVE # ============================================================ def objective( trial ): # -------------------------------------------------------- # Hyperparameter search space # -------------------------------------------------------- params = { "objective": "binary:logistic", "eval_metric": "logloss", "tree_method": "hist", "random_state": RANDOM_STATE, # ---------------------------------------------------- # Tree depth / complexity # ---------------------------------------------------- "max_depth": trial.suggest_int( "max_depth", 3, 10 ), "min_child_weight": trial.suggest_int( "min_child_weight", 1, 20 ), # ---------------------------------------------------- # Boosting # ---------------------------------------------------- "n_estimators": trial.suggest_int( "n_estimators", 200, 1200 ), "learning_rate": trial.suggest_float( "learning_rate", 0.005, 0.15, log=True ), # ---------------------------------------------------- # Sampling # ---------------------------------------------------- "subsample": trial.suggest_float( "subsample", 0.65, 1.0 ), "colsample_bytree": trial.suggest_float( "colsample_bytree", 0.65, 1.0 ), # ---------------------------------------------------- # Regularization # ---------------------------------------------------- "gamma": trial.suggest_float( "gamma", 0.0, 5.0 ), "reg_alpha": trial.suggest_float( "reg_alpha", 1e-8, 10.0, log=True ), "reg_lambda": trial.suggest_float( "reg_lambda", 1e-8, 20.0, log=True ) } model = xgb.XGBClassifier( **params ) model.fit( X_train_processed, y_train, sample_weight=train_weights, eval_set=[ ( X_validation_processed, y_validation ) ], verbose=False ) validation_probabilities = ( model .predict_proba( X_validation_processed )[:, 1] ) # Optimize probability quality rather than # simple classification accuracy. score = log_loss( y_validation, validation_probabilities, labels=[0, 1], sample_weight=validation_weights ) return score # ============================================================ # 21. RUN OPTUNA # ============================================================ print("\n") print("=" * 80) print("OPTUNA HYPERPARAMETER OPTIMIZATION") print("=" * 80) print( f"\nNumber of trials: " f"{N_TRIALS}" ) study = optuna.create_study( study_name=( "F1_Live_Winner_XGBoost" ), direction="minimize", sampler=( optuna.samplers.TPESampler( seed=RANDOM_STATE ) ) ) study.optimize( objective, n_trials=N_TRIALS, show_progress_bar=True ) # ============================================================ # 22. EXTRACT BEST PARAMETERS # ============================================================ best_params = ( study .best_params .copy() ) best_params.update( { "objective": "binary:logistic", "eval_metric": "logloss", "tree_method": "hist", "random_state": RANDOM_STATE } ) print("\n") print("=" * 80) print("OPTUNA COMPLETE") print("=" * 80) print( f"\nBest validation log loss: " f"{study.best_value:.6f}" ) print("\nBest parameters:") for parameter, value in ( study.best_params.items() ): print( f" {parameter}: {value}" ) # ============================================================ # 23. TRAIN FINAL MODEL # ============================================================ print("\n") print("=" * 80) print("TRAINING FINAL XGBOOST MODEL") print("=" * 80) final_model = xgb.XGBClassifier( **best_params ) final_model.fit( X_train_processed, y_train, sample_weight=train_weights, eval_set=[ ( X_validation_processed, y_validation ) ], verbose=False ) # ============================================================ # 24. GENERATE PREDICTIONS # ============================================================ validation_probabilities = ( final_model .predict_proba( X_validation_processed )[:, 1] ) test_probabilities = ( final_model .predict_proba( X_test_processed )[:, 1] ) # ============================================================ # TEST RACE AUDIT # ============================================================ audit_df = test_df.copy() audit_df["PredictedProbability"] = test_probabilities audit_results = [] for race_date, race_group in audit_df.groupby("RaceDate"): race_group = race_group.copy() # -------------------------------------------------------- # Driver predicted most likely to win # -------------------------------------------------------- predicted_idx = ( race_group[ "PredictedProbability" ].idxmax() ) predicted_row = race_group.loc[ predicted_idx ] # -------------------------------------------------------- # Actual winner # -------------------------------------------------------- actual_rows = race_group[ race_group["Winner"] == 1 ] if actual_rows.empty: continue actual_row = actual_rows.iloc[0] # -------------------------------------------------------- # Rank every driver in this race # -------------------------------------------------------- race_group["PredictionRank"] = ( race_group[ "PredictedProbability" ] .rank( ascending=False, method="min" ) ) actual_winner_index = ( actual_rows.index[0] ) actual_rank = ( race_group.loc[ actual_winner_index, "PredictionRank" ] ) # -------------------------------------------------------- # Save result # -------------------------------------------------------- audit_results.append({ "RaceDate": race_date, "ActualWinner": actual_row["Driver"], "ActualWinnerProbability": actual_row[ "PredictedProbability" ], "ActualWinnerRank": int(actual_rank), "PredictedWinner": predicted_row["Driver"], "PredictedWinnerProbability": predicted_row[ "PredictedProbability" ], "Correct": ( predicted_row["Driver"] == actual_row["Driver"] ) }) # ============================================================ # CREATE AUDIT TABLE # ============================================================ audit_results = pd.DataFrame( audit_results ) print("\n") print("=" * 100) print("TEST RACE AUDIT") print("=" * 100) if audit_results.empty: print( "No test-race results available." ) else: print( audit_results.to_string( index=False ) ) # ============================================================ # SAVE AUDIT # ============================================================ audit_results.to_csv( "F1_Model/test_race_audit.csv", index=False ) # ============================================================ # ACTUAL WINNER RANK DISTRIBUTION # ============================================================ if not audit_results.empty: print("\n") print("=" * 100) print("ACTUAL WINNER PREDICTION RANK") print("=" * 100) print( audit_results[ "ActualWinnerRank" ] .value_counts() .sort_index() ) # ============================================================ # TOP-3 ACCURACY # ============================================================ if not audit_results.empty: top3_accuracy = ( audit_results[ "ActualWinnerRank" ] <= 3 ).mean() print( f"\nTop-3 race winner accuracy: " f"{top3_accuracy:.4f}" ) # Binary predictions at 0.5 validation_predictions = ( validation_probabilities >= 0.5 ).astype(int) test_predictions = ( test_probabilities >= 0.5 ).astype(int) # ============================================================ # 25. STANDARD METRICS # ============================================================ validation_logloss = log_loss( y_validation, validation_probabilities, labels=[0, 1], sample_weight=validation_weights ) validation_auc = roc_auc_score( y_validation, validation_probabilities, sample_weight=validation_weights ) validation_accuracy = accuracy_score( y_validation, validation_predictions ) test_logloss = log_loss( y_test, test_probabilities, labels=[0, 1], sample_weight=test_weights ) test_auc = roc_auc_score( y_test, test_probabilities, sample_weight=test_weights ) test_accuracy = accuracy_score( y_test, test_predictions ) print("\n") print("=" * 80) print("STANDARD METRICS") print("=" * 80) print("\nVALIDATION") print( f"Log Loss : " f"{validation_logloss:.6f}" ) print( f"ROC AUC : " f"{validation_auc:.6f}" ) print( f"Accuracy : " f"{validation_accuracy:.6f}" ) print("\nUNSEEN TEST RACES") print( f"Log Loss : " f"{test_logloss:.6f}" ) print( f"ROC AUC : " f"{test_auc:.6f}" ) print( f"Accuracy : " f"{test_accuracy:.6f}" ) # ============================================================ # 26. RACE-LEVEL EVALUATION # ============================================================ def evaluate_race_winners( dataframe, probabilities ): evaluation_columns = [ RACE_COLUMN, DRIVER_COLUMN, TARGET_COLUMN ] if "DriverNumber" in dataframe.columns: evaluation_columns.append( "DriverNumber" ) evaluation = dataframe[ evaluation_columns ].copy() evaluation[ "WinProbability" ] = probabilities results = [] for race_date, race_group in ( evaluation .groupby( RACE_COLUMN ) ): # ---------------------------------------------------- # Predicted winner = highest probability # ---------------------------------------------------- predicted_index = ( race_group[ "WinProbability" ].idxmax() ) predicted_row = ( race_group.loc[ predicted_index ] ) # ---------------------------------------------------- # Actual winner # ---------------------------------------------------- actual_rows = race_group[ race_group[ TARGET_COLUMN ] == 1 ] if actual_rows.empty: continue actual_row = ( actual_rows.iloc[0] ) result = { "RaceDate": race_date, "PredictedWinner": predicted_row[ DRIVER_COLUMN ], "PredictedProbability": float( predicted_row[ "WinProbability" ] ), "ActualWinner": actual_row[ DRIVER_COLUMN ], "Correct": ( predicted_row[ DRIVER_COLUMN ] == actual_row[ DRIVER_COLUMN ] ) } if "DriverNumber" in evaluation.columns: result[ "PredictedDriverNumber" ] = predicted_row[ "DriverNumber" ] results.append( result ) results_df = pd.DataFrame( results ) if results_df.empty: return ( results_df, np.nan ) accuracy = ( results_df[ "Correct" ] .mean() ) return ( results_df, accuracy ) # ============================================================ # 27. VALIDATION RACE ACCURACY # ============================================================ ( validation_race_results, validation_race_accuracy ) = evaluate_race_winners( validation_df, validation_probabilities ) # ============================================================ # 28. TEST RACE ACCURACY # ============================================================ ( test_race_results, test_race_accuracy ) = evaluate_race_winners( test_df, test_probabilities ) print("\n") print("=" * 80) print("RACE-LEVEL WINNER PERFORMANCE") print("=" * 80) print( f"\nValidation race winner accuracy:" f" {validation_race_accuracy:.4f}" ) print( f"Test race winner accuracy:" f" {test_race_accuracy:.4f}" ) # ============================================================ # 29. SHOW TEST RESULTS # ============================================================ if not test_race_results.empty: print("\n") print( "UNSEEN TEST RACE RESULTS" ) print( test_race_results .sort_values( "RaceDate" ) .to_string( index=False ) ) # ============================================================ # 30. FEATURE IMPORTANCE # ============================================================ try: processed_feature_names = ( preprocessor .get_feature_names_out() .tolist() ) except Exception: processed_feature_names = [] if processed_feature_names: feature_importance_df = pd.DataFrame( { "Feature": processed_feature_names, "Importance": final_model .feature_importances_ } ) feature_importance_df = ( feature_importance_df .sort_values( "Importance", ascending=False ) .reset_index( drop=True ) ) print("\n") print("=" * 80) print("TOP 30 FEATURES") print("=" * 80) print( feature_importance_df .head(30) .to_string( index=False ) ) feature_importance_df.to_csv( FEATURE_IMPORTANCE_OUTPUT, index=False ) print( f"\nFeature importance saved:" f"\n{FEATURE_IMPORTANCE_OUTPUT}" ) # ============================================================ # 31. SAVE FEATURE SCHEMA # ============================================================ feature_schema = { "target": TARGET_COLUMN, "race_column": RACE_COLUMN, "driver_column": DRIVER_COLUMN, "model_features": feature_columns, "numeric_features": numeric_features, "categorical_features": categorical_features, "processed_feature_names": processed_feature_names, "raw_feature_count": len(feature_columns), "processed_feature_count": len(processed_feature_names), "pipeline_version": "f1_lap_level_xgboost_v1" } with open( FEATURE_SCHEMA_OUTPUT, "w", encoding="utf-8" ) as file: json.dump( feature_schema, file, indent=4 ) # ============================================================ # 32. BUILD MODEL BUNDLE # ============================================================ model_bundle = { # -------------------------------------------------------- # Model # -------------------------------------------------------- "model": final_model, # -------------------------------------------------------- # Preprocessor # -------------------------------------------------------- "preprocessor": preprocessor, # -------------------------------------------------------- # EXACT FEATURE ORDER # -------------------------------------------------------- "feature_columns": feature_columns, # -------------------------------------------------------- # FEATURE TYPES # -------------------------------------------------------- "numeric_features": numeric_features, "categorical_features": categorical_features, # -------------------------------------------------------- # ENCODED FEATURE NAMES # -------------------------------------------------------- "processed_feature_names": processed_feature_names, # -------------------------------------------------------- # TARGET # -------------------------------------------------------- "target_column": TARGET_COLUMN, # -------------------------------------------------------- # BEST OPTUNA PARAMETERS # -------------------------------------------------------- "best_params": best_params, # -------------------------------------------------------- # RACE SPLIT INFORMATION # -------------------------------------------------------- "training_races": [ str( pd.Timestamp( race ).date() ) for race in train_races ], "validation_races": [ str( pd.Timestamp( race ).date() ) for race in validation_races ], "test_races": [ str( pd.Timestamp( race ).date() ) for race in test_races ], # -------------------------------------------------------- # VALIDATION METRICS # -------------------------------------------------------- "validation_logloss": float( validation_logloss ), "validation_auc": float( validation_auc ), "validation_accuracy": float( validation_accuracy ), "validation_race_accuracy": ( float( validation_race_accuracy ) if not pd.isna( validation_race_accuracy ) else None ), # -------------------------------------------------------- # TEST METRICS # -------------------------------------------------------- "test_logloss": float( test_logloss ), "test_auc": float( test_auc ), "test_accuracy": float( test_accuracy ), "test_race_accuracy": ( float( test_race_accuracy ) if not pd.isna( test_race_accuracy ) else None ), # -------------------------------------------------------- # VERSION # -------------------------------------------------------- "xgboost_version": xgb.__version__, "pipeline_version": "f1_lap_level_xgboost_v1", "random_state": RANDOM_STATE } # ============================================================ # 33. SAVE MODEL # ============================================================ print("\n") print("=" * 80) print("SAVING MODEL") print("=" * 80) joblib.dump( model_bundle, MODEL_OUTPUT ) print( f"\nModel saved to:" f"\n{MODEL_OUTPUT}" ) # ============================================================ # 34. SAVE BEST PARAMETERS # ============================================================ with open( PARAMS_OUTPUT, "w", encoding="utf-8" ) as file: json.dump( best_params, file, indent=4 ) print( f"\nBest parameters saved to:" f"\n{PARAMS_OUTPUT}" ) # ============================================================ # 35. SAVE OPTUNA STUDY # ============================================================ joblib.dump( study, STUDY_OUTPUT ) print( f"\nOptuna study saved to:" f"\n{STUDY_OUTPUT}" ) # ============================================================ # 36. VERIFY MODEL FILE # ============================================================ if not Path( MODEL_OUTPUT ).exists(): raise RuntimeError( "Model file was not created." ) # ============================================================ # 37. FINAL SUMMARY # ============================================================ print("\n") print("=" * 80) print("TRAINING COMPLETE") print("=" * 80) print( f"\nInput dataset:" f"\n{dataset_path.resolve()}" ) print( f"\nTotal rows:" f" {len(df):,}" ) print( f"Total races:" f" {number_of_races}" ) print( f"Raw model features:" f" {len(feature_columns)}" ) print( f"Encoded features:" f" {len(processed_feature_names)}" ) print( f"\nTest ROC AUC:" f" {test_auc:.4f}" ) print( f"Test Log Loss:" f" {test_logloss:.4f}" ) print( f"Test row accuracy:" f" {test_accuracy:.4f}" ) print( f"Test race winner accuracy:" f" {test_race_accuracy:.4f}" ) print( "\nSaved artifacts:" ) print( f" Model:" f"\n {MODEL_OUTPUT}" ) print( f" Parameters:" f"\n {PARAMS_OUTPUT}" ) print( f" Optuna study:" f"\n {STUDY_OUTPUT}" ) print( f" Feature importance:" f"\n {FEATURE_IMPORTANCE_OUTPUT}" ) print( f" Feature schema:" f"\n {FEATURE_SCHEMA_OUTPUT}" ) print("\n") print("=" * 80) print("READY FOR LIVE INFERENCE") print("=" * 80)