{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":84493,"databundleVersionId":9871156,"sourceType":"competition"}],"dockerImageVersionId":30786,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Mainly for model training\n\nDepending on the size of your training set, you will need an [inference notebook](https://www.kaggle.com/code/regisvargas/inference-jane-street-a-beginner-s-notebook).","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport gc\n# Initialize a list to hold samples from each file\nsamples = []\n# Load a sample from each file\nfor i in range(10):\n#for i in [7]:\n    file_path = f\"/kaggle/input/jane-street-real-time-market-data-forecasting/train.parquet/partition_id={i}/part-0.parquet\"\n    chunk = pd.read_parquet(file_path)\n    \n    # Take a sample of the data (adjust sample size as needed)\n    #sample_chunk = chunk.sample(n=500000, random_state=42)  # For example, 100 rows\n    sample_chunk = chunk[:500000]\n    samples.append(sample_chunk)\n# Concatenate all samples into one DataFrame if needed\ndel chunk\ngc.collect()  # Forces garbage collection\nsample_df = pd.concat(samples, ignore_index=True)\ndel samples\ngc.collect()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:13:37.264931Z","iopub.execute_input":"2024-12-05T01:13:37.265568Z","iopub.status.idle":"2024-12-05T01:15:20.972237Z","shell.execute_reply.started":"2024-12-05T01:13:37.265508Z","shell.execute_reply":"2024-12-05T01:15:20.964691Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample_df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:15:20.980050Z","iopub.execute_input":"2024-12-05T01:15:20.980705Z","iopub.status.idle":"2024-12-05T01:15:21.044985Z","shell.execute_reply.started":"2024-12-05T01:15:20.980645Z","shell.execute_reply":"2024-12-05T01:15:21.042794Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Prepare data","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras import layers, models\n# Separate features and responders\nfeatures = sample_df.filter(regex='^feature_')\nresponders = sample_df.filter(regex='^responder_')\nweights = sample_df['weight']\n# Convert to numpy arrays for TensorFlow\nX = features.values  # Features for input\n#y = responders.values  # Responders for output\n# Assuming you have a DataFrame `y_train` with all responders\ny = responders[['responder_6']].values  # Keep only responder_6\nX = np.nan_to_num(X, nan=0.0, posinf=0.0, neginf=0.0)\ny = np.nan_to_num(y, nan=0.0, posinf=0.0, neginf=0.0)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:15:21.049800Z","iopub.execute_input":"2024-12-05T01:15:21.050366Z","iopub.status.idle":"2024-12-05T01:15:43.972620Z","shell.execute_reply.started":"2024-12-05T01:15:21.050317Z","shell.execute_reply":"2024-12-05T01:15:43.971072Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"Is_keras = True","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:15:43.976773Z","iopub.execute_input":"2024-12-05T01:15:43.977804Z","iopub.status.idle":"2024-12-05T01:15:43.986118Z","shell.execute_reply.started":"2024-12-05T01:15:43.977744Z","shell.execute_reply":"2024-12-05T01:15:43.983872Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_size = int(len(X) * 0.8)\n\n# Sequential split\nX_train = X[:train_size]\nX_val = X[train_size:]\ny_train = y[:train_size]\ny_val = y[train_size:]\nweights_train = weights[:train_size]\nweights_val = weights[train_size:]\n\nprint(f\"Train shapes: {X_train.shape}, {y_train.shape}, {weights_train.shape}\")\nprint(f\"Validation shapes: {X_val.shape}, {y_val.shape}, {weights_val.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:15:43.987732Z","iopub.execute_input":"2024-12-05T01:15:43.988157Z","iopub.status.idle":"2024-12-05T01:15:44.011901Z","shell.execute_reply.started":"2024-12-05T01:15:43.988117Z","shell.execute_reply":"2024-12-05T01:15:44.010175Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Training Autoencoder for compact representation","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras import layers, models\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau\n# Define the Autoencoder model\ninput_dim = X_train.shape[1]  # Number of features\nlatent_dim = 32  # Dimension of the bottleneck layer\nencoder_input = layers.Input(shape=(input_dim,))\nx = layers.Dense(128, activation='relu')(encoder_input)\nx = layers.Dense(64, activation='relu')(x)\nbottleneck = layers.Dense(latent_dim, activation='linear', name='bottleneck')(x)  # Encoder output\n# Decoder\nx = layers.Dense(64, activation='relu')(bottleneck)\nx = layers.Dense(128, activation='relu')(x)\ndecoder_output = layers.Dense(input_dim, activation='linear')(x)\nautoencoder = models.Model(encoder_input, decoder_output, name=\"Autoencoder\")\n# Compile the Autoencoder\nautoencoder.compile(optimizer=\"adam\", loss=\"mse\")\nautoencoder.summary()\n# Define callbacks\nearly_stopping = EarlyStopping(monitor=\"val_loss\", patience=10, restore_best_weights=True, min_delta = 0.00001)\nreduce_lr = ReduceLROnPlateau(monitor=\"val_loss\", factor=0.5, patience=3, min_lr=1e-6)\n# Train the Autoencoder\nhistory = autoencoder.fit(\n    X_train, X_train,\n    validation_data=(X_val, X_val),\n    epochs=1,\n    batch_size=32,\n    callbacks=[early_stopping, reduce_lr]\n)\n# Extract the encoder\nencoder = models.Model(encoder_input, bottleneck, name=\"Encoder\")\nencoder.save(\"/kaggle/working/pretrained_encoder.keras\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:15:44.014094Z","iopub.execute_input":"2024-12-05T01:15:44.015293Z","iopub.status.idle":"2024-12-05T01:21:32.307176Z","shell.execute_reply.started":"2024-12-05T01:15:44.015232Z","shell.execute_reply":"2024-12-05T01:21:32.305856Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# XGBoost\n\nSee [Feature engineering, xgboost](https://www.kaggle.com/code/dlarionov/feature-engineering-xgboost#Part-2,-xgboost) and [🥇🥇Jane Street Baseline lgb, xgb and catboost🥇🥇](https://www.kaggle.com/code/yuanzhezhou/jane-street-baseline-lgb-xgb-and-catboost)for details.","metadata":{}},{"cell_type":"code","source":"# Define a learning rate schedule\ndef learning_rate_scheduler_xgb(epoch):\n    initial_rate = 0.3\n    decay_rate = 0.999\n    return initial_rate * (decay_rate ** (np.log(epoch)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:21:32.309218Z","iopub.execute_input":"2024-12-05T01:21:32.309622Z","iopub.status.idle":"2024-12-05T01:21:32.315746Z","shell.execute_reply.started":"2024-12-05T01:21:32.309576Z","shell.execute_reply":"2024-12-05T01:21:32.314373Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from xgboost import XGBRegressor\n# Create an XGBoost model\nmodel_xgb = XGBRegressor(\n    n_estimators=5000,\n    learning_rate=learning_rate_scheduler_xgb,\n    tree_method='hist',\n    max_depth=6,\n    random_state=42\n)\n# Fit the model with sample weights and validation dataset\nmodel_xgb.fit(\n    X_train,\n    y_train,\n #   sample_weight=weights_train,\n    eval_set=[(X_val, y_val)],\n#    sample_weight_eval_set=[weights_train, weights_val],\n    eval_metric='rmse',\n    early_stopping_rounds=10,\n    verbose=False\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:21:32.317243Z","iopub.execute_input":"2024-12-05T01:21:32.317685Z","iopub.status.idle":"2024-12-05T01:22:19.875268Z","shell.execute_reply.started":"2024-12-05T01:21:32.317583Z","shell.execute_reply":"2024-12-05T01:22:19.874035Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_pred = model_xgb.predict(X_val)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:22:19.876796Z","iopub.execute_input":"2024-12-05T01:22:19.877458Z","iopub.status.idle":"2024-12-05T01:22:20.142476Z","shell.execute_reply.started":"2024-12-05T01:22:19.877418Z","shell.execute_reply":"2024-12-05T01:22:20.141645Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import mean_squared_error, r2_score\nmse = mean_squared_error(y_val, y_pred, squared=False)\nr2 = r2_score(y_val, y_pred)\nprint(f\"RMSE: {mse}\")\nprint(f\"R²: {r2}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:22:20.146342Z","iopub.execute_input":"2024-12-05T01:22:20.146794Z","iopub.status.idle":"2024-12-05T01:22:20.167658Z","shell.execute_reply.started":"2024-12-05T01:22:20.146742Z","shell.execute_reply":"2024-12-05T01:22:20.166017Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import joblib\n# Save the model\njoblib.dump(model_xgb, \"xgboost_sklearn.pkl\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:22:20.169302Z","iopub.execute_input":"2024-12-05T01:22:20.169834Z","iopub.status.idle":"2024-12-05T01:22:20.184610Z","shell.execute_reply.started":"2024-12-05T01:22:20.169783Z","shell.execute_reply":"2024-12-05T01:22:20.183631Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Build the Autoencoder Model","metadata":{}},{"cell_type":"markdown","source":"Gradient Centralization for Better Training Performance\n\nSee https://keras.io/examples/vision/gradient_centralization/ for details. ","metadata":{}},{"cell_type":"code","source":"from keras.optimizers import RMSprop\nclass GCRMSprop(RMSprop):\n    def get_gradients(self, loss, params):\n        # We here just provide a modified get_gradients() function since we are\n        # trying to just compute the centralized gradients.\n        grads = []\n        gradients = super().get_gradients()\n        for grad in gradients:\n            grad_len = len(grad.shape)\n            if grad_len > 1:\n                axis = list(range(grad_len - 1))\n                grad -= ops.mean(grad, axis=axis, keep_dims=True)\n            grads.append(grad)\n        return grads\noptimizer = GCRMSprop(learning_rate=1e-4)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:22:20.186455Z","iopub.execute_input":"2024-12-05T01:22:20.187276Z","iopub.status.idle":"2024-12-05T01:22:20.207282Z","shell.execute_reply.started":"2024-12-05T01:22:20.187221Z","shell.execute_reply":"2024-12-05T01:22:20.205176Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.regularizers import l2\n# Define the number of input and output nodes\ninput_dim = X.shape[1]  # Number of features (79)\noutput_dim = y.shape[1]  # Number of responders (9)\n# Define the model\nmodel = models.Sequential([\n    layers.Input(shape=(input_dim,)), # Input layer\n   # layers.LayerNormalization(),\n   # layers.BatchNormalization(),\n  #  layers.Dense(128, activation='relu'),\n  #  layers.Dropout(0.2),\n    layers.Dense(64, activation='linear'),  # Encoder\n    layers.Dense(32, activation='gelu'),  # Bottleneck layer (compression)\n    layers.Dense(output_dim, activation='linear'),  # Decoder\n#    layers.Dense(128, activation='relu'), \n    layers.Dropout(0.2)#,\n#    layers.Dense(output_dim, activation='linear'#, kernel_regularizer=l2(0.001))  # Output layer for responders\n])\nmodel.compile(optimizer=\"adam\", loss='mse')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:22:20.209105Z","iopub.execute_input":"2024-12-05T01:22:20.209737Z","iopub.status.idle":"2024-12-05T01:22:20.272754Z","shell.execute_reply.started":"2024-12-05T01:22:20.209683Z","shell.execute_reply":"2024-12-05T01:22:20.271066Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Train Autoencoder Model","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.callbacks import LearningRateScheduler\ndef step_decay(epoch):\n    initial_lr = 0.01\n    drop = 0.5\n    epochs_drop = 5\n    lr = initial_lr * (drop ** (epoch // epochs_drop))\n    return lr\nlr_scheduler = LearningRateScheduler(step_decay)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:22:20.274017Z","iopub.execute_input":"2024-12-05T01:22:20.274390Z","iopub.status.idle":"2024-12-05T01:22:20.280236Z","shell.execute_reply.started":"2024-12-05T01:22:20.274354Z","shell.execute_reply":"2024-12-05T01:22:20.278925Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.callbacks import ReduceLROnPlateau\nreduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=2, min_lr=1e-6)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:22:20.282216Z","iopub.execute_input":"2024-12-05T01:22:20.283112Z","iopub.status.idle":"2024-12-05T01:22:20.298522Z","shell.execute_reply.started":"2024-12-05T01:22:20.283061Z","shell.execute_reply":"2024-12-05T01:22:20.297358Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping\n# Define EarlyStopping\nearly_stopping = EarlyStopping(\n    monitor='val_loss',    # Monitor validation loss\n    patience=10,            # Number of epochs to wait for improvement\n    min_delta=0.00001,       # Minimum change to qualify as an improvement\n    restore_best_weights=True  # Restore weights from the best epoch\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:22:20.300444Z","iopub.execute_input":"2024-12-05T01:22:20.300980Z","iopub.status.idle":"2024-12-05T01:22:20.318766Z","shell.execute_reply.started":"2024-12-05T01:22:20.300909Z","shell.execute_reply":"2024-12-05T01:22:20.317504Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if Is_keras:\n    history = model.fit(\n    X_train, y_train,\n   # sample_weight=weights_train,  # Training sample weights\n    epochs=50,\n    batch_size=32,\n    validation_data=(X_val, y_val#, \n                     #weights_val\n                    ),  # Validation data with sample weights\n    callbacks=[early_stopping, reduce_lr]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-05T01:22:20.320548Z","iopub.execute_input":"2024-12-05T01:22:20.321104Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if Is_keras:\n    model.save(\"/kaggle/working/model.keras\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Submission\n\nSee [Jane Street RMF Demo Submission](https://www.kaggle.com/code/ryanholbrook/jane-street-rmf-demo-submission) for details.\n\nDepending on the size of your training set, you will need an [inference notebook](https://www.kaggle.com/code/regisvargas/inference-jane-street-a-beginner-s-notebook).","metadata":{}},{"cell_type":"code","source":"import os\nimport polars as pl\nimport kaggle_evaluation.jane_street_inference_server","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import polars as pl\nimport numpy as np\n# Assuming `model` is your trained model\n# Assuming features required by the model are named 'feature_00', 'feature_01', etc.\ndef predict(test: pl.DataFrame, lags: pl.DataFrame | None) -> pl.DataFrame | pd.DataFrame:\n    \"\"\"Make a prediction.\"\"\"\n    global lags_\n    if lags is not None:\n        lags_ = lags\n    # Extract the features for the model input\n    feature_columns = [col for col in test.columns if col.startswith(\"feature_\")]\n    features = test.select(feature_columns).to_numpy()  # Convert to numpy array for model input\n    features = np.nan_to_num(features, nan=0.0, posinf=0.0, neginf=0.0)\n    # Generate predictions using the model\n    #model_predictions = model.predict(features)\n    if Is_keras:\n        responder_6_predictions = model.predict(features)[:,0]\n    else:\n        responder_6_predictions = model_xgb.predict(features)\n   # print(responder_6_predictions)    \n    #responder_6_predictions = model_predictions[:, 6]  # Assuming responder_6 is at index 6\n    # Create a new Polars DataFrame with row_id and responder_6 predictions\n    predictions = test.select(\"row_id\").with_columns(\n        pl.Series(\"responder_6\", responder_6_predictions)\n    )\n    print(predictions)\n    # Ensure the output format and length requirements\n    if isinstance(predictions, pl.DataFrame):\n        assert predictions.columns == ['row_id', 'responder_6']\n    elif isinstance(predictions, pd.DataFrame):\n        assert (predictions.columns == ['row_id', 'responder_6']).all()\n    else:\n        raise TypeError('The predict function must return a DataFrame')\n    \n    assert len(predictions) == len(test)\n    return predictions","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"inference_server = kaggle_evaluation.jane_street_inference_server.JSInferenceServer(predict)\nif os.getenv('KAGGLE_IS_COMPETITION_RERUN'):\n    inference_server.serve()\nelse:\n    inference_server.run_local_gateway(\n        (\n            '/kaggle/input/jane-street-real-time-market-data-forecasting/test.parquet',\n            '/kaggle/input/jane-street-real-time-market-data-forecasting/lags.parquet',\n        )\n    )","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}