{"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":"gpu","dataSources":[{"sourceId":84493,"databundleVersionId":9871156,"sourceType":"competition"}],"dockerImageVersionId":30786,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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(3):\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=900000, random_state=42)  # For example, 100 rows\n    # sample_chunk = chunk[:700000]\n    samples.append(chunk)\n# Concatenate all samples into one DataFrame if needed\ndel chunk\ngc.collect()  # Forces garbage collection\ndf = pd.concat(samples, ignore_index=True)\ndel samples\ngc.collect()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-07T00:29:00.865223Z","iopub.execute_input":"2025-01-07T00:29:00.865878Z","iopub.status.idle":"2025-01-07T00:29:06.499748Z","shell.execute_reply.started":"2025-01-07T00:29:00.865845Z","shell.execute_reply":"2025-01-07T00:29:06.498898Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-07T00:29:06.501325Z","iopub.execute_input":"2025-01-07T00:29:06.501702Z","iopub.status.idle":"2025-01-07T00:29:06.530554Z","shell.execute_reply.started":"2025-01-07T00:29:06.501660Z","shell.execute_reply":"2025-01-07T00:29:06.529737Z"}},"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 = df.filter(regex='^feature_')\nresponders = df.filter(regex='^responder_')\nweights = 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":"2025-01-07T00:29:06.531484Z","iopub.execute_input":"2025-01-07T00:29:06.531811Z","iopub.status.idle":"2025-01-07T00:29:13.849411Z","shell.execute_reply.started":"2025-01-07T00:29:06.531771Z","shell.execute_reply":"2025-01-07T00:29:13.848397Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"features","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-07T00:29:13.851722Z","iopub.execute_input":"2025-01-07T00:29:13.852466Z","iopub.status.idle":"2025-01-07T00:29:14.742927Z","shell.execute_reply.started":"2025-01-07T00:29:13.852422Z","shell.execute_reply":"2025-01-07T00:29:14.742034Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"Is_keras = False","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-07T00:29:14.743968Z","iopub.execute_input":"2025-01-07T00:29:14.744244Z","iopub.status.idle":"2025-01-07T00:29:14.748143Z","shell.execute_reply.started":"2025-01-07T00:29:14.744218Z","shell.execute_reply":"2025-01-07T00:29:14.747265Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.preprocessing import StandardScaler\n\n# Sequential split\ntrain_size = int(len(X) * 0.8)\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\n# Standardization\nscaler = StandardScaler()\n\n# Fit the scaler on the training data and transform both train and validation data\nX_train = scaler.fit_transform(X_train)\nX_val = scaler.transform(X_val)\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}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-07T00:29:14.749206Z","iopub.execute_input":"2025-01-07T00:29:14.749481Z","iopub.status.idle":"2025-01-07T00:29:20.616838Z","shell.execute_reply.started":"2025-01-07T00:29:14.749440Z","shell.execute_reply":"2025-01-07T00:29:20.615909Z"}},"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)\n# x = 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":"2025-01-07T00:29:20.618125Z","iopub.execute_input":"2025-01-07T00:29:20.618513Z","iopub.status.idle":"2025-01-07T00:34:45.630132Z","shell.execute_reply.started":"2025-01-07T00:29:20.618472Z","shell.execute_reply":"2025-01-07T00:34:45.629383Z"}},"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":"2025-01-07T00:34:45.631368Z","iopub.execute_input":"2025-01-07T00:34:45.631810Z","iopub.status.idle":"2025-01-07T00:34:45.636638Z","shell.execute_reply.started":"2025-01-07T00:34:45.631770Z","shell.execute_reply":"2025-01-07T00:34:45.635797Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from xgboost import XGBRegressor\n# Create an XGBoost model\nmodel_xgb = XGBRegressor(\n    n_estimators=6000,\n    learning_rate=learning_rate_scheduler_xgb,\n    tree_method='hist',\n    max_depth=6\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_val],\n    eval_metric='rmse',\n    early_stopping_rounds=10,\n    verbose=False\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-07T00:34:45.637605Z","iopub.execute_input":"2025-01-07T00:34:45.637846Z","iopub.status.idle":"2025-01-07T00:35:57.498679Z","shell.execute_reply.started":"2025-01-07T00:34:45.637822Z","shell.execute_reply":"2025-01-07T00:35:57.497780Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_pred = model_xgb.predict(X_val)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-07T00:35:57.502257Z","iopub.execute_input":"2025-01-07T00:35:57.502547Z","iopub.status.idle":"2025-01-07T00:35:58.079156Z","shell.execute_reply.started":"2025-01-07T00:35:57.502520Z","shell.execute_reply":"2025-01-07T00:35:58.078401Z"}},"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":"2025-01-07T00:35:58.079939Z","iopub.execute_input":"2025-01-07T00:35:58.080200Z","iopub.status.idle":"2025-01-07T00:35:58.098303Z","shell.execute_reply.started":"2025-01-07T00:35:58.080174Z","shell.execute_reply":"2025-01-07T00:35:58.097671Z"}},"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":"2025-01-07T00:35:58.099667Z","iopub.execute_input":"2025-01-07T00:35:58.100023Z","iopub.status.idle":"2025-01-07T00:35:58.109020Z","shell.execute_reply.started":"2025-01-07T00:35:58.099961Z","shell.execute_reply":"2025-01-07T00:35:58.107263Z"}},"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":"2025-01-07T00:35:58.110323Z","iopub.execute_input":"2025-01-07T00:35:58.110559Z","iopub.status.idle":"2025-01-07T00:35:58.122356Z","shell.execute_reply.started":"2025-01-07T00:35:58.110534Z","shell.execute_reply":"2025-01-07T00:35:58.121834Z"}},"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='relu'),  # Encoder\n    layers.Dense(32, activation='relu'),  # Bottleneck layer (compression)\n    layers.Dense(64, activation='relu'),  # Decoder\n    layers.Dense(128, activation='relu'), \n    layers.Dropout(0.2),\n    layers.Dense(output_dim, activation='linear', kernel_regularizer=l2(0.001)\n                )  # Output layer for responders\n])\nmodel.compile(optimizer=\"adam\", loss='mse')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-07T00:35:58.123436Z","iopub.execute_input":"2025-01-07T00:35:58.123722Z","iopub.status.idle":"2025-01-07T00:35:58.191188Z","shell.execute_reply.started":"2025-01-07T00:35:58.123678Z","shell.execute_reply":"2025-01-07T00:35:58.190352Z"}},"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":"2025-01-07T00:35:58.192148Z","iopub.execute_input":"2025-01-07T00:35:58.192396Z","iopub.status.idle":"2025-01-07T00:35:58.196765Z","shell.execute_reply.started":"2025-01-07T00:35:58.192371Z","shell.execute_reply":"2025-01-07T00:35:58.195873Z"}},"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":"2025-01-07T00:35:58.197911Z","iopub.execute_input":"2025-01-07T00:35:58.198514Z","iopub.status.idle":"2025-01-07T00:35:58.206786Z","shell.execute_reply.started":"2025-01-07T00:35:58.198475Z","shell.execute_reply":"2025-01-07T00:35:58.205895Z"}},"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":"2025-01-07T00:35:58.208067Z","iopub.execute_input":"2025-01-07T00:35:58.208323Z","iopub.status.idle":"2025-01-07T00:35:58.217213Z","shell.execute_reply.started":"2025-01-07T00:35:58.208300Z","shell.execute_reply":"2025-01-07T00:35:58.216352Z"}},"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":"2025-01-07T00:35:58.218373Z","iopub.execute_input":"2025-01-07T00:35:58.219137Z","iopub.status.idle":"2025-01-07T00:35:58.225857Z","shell.execute_reply.started":"2025-01-07T00:35:58.219109Z","shell.execute_reply":"2025-01-07T00:35:58.225181Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if Is_keras:\n    model.save(\"/kaggle/working/model.keras\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-07T00:35:58.226819Z","iopub.execute_input":"2025-01-07T00:35:58.227162Z","iopub.status.idle":"2025-01-07T00:35:58.237156Z","shell.execute_reply.started":"2025-01-07T00:35:58.227123Z","shell.execute_reply":"2025-01-07T00:35:58.236388Z"}},"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,"execution":{"iopub.status.busy":"2025-01-07T00:35:58.238065Z","iopub.execute_input":"2025-01-07T00:35:58.238450Z","iopub.status.idle":"2025-01-07T00:35:58.249490Z","shell.execute_reply.started":"2025-01-07T00:35:58.238414Z","shell.execute_reply":"2025-01-07T00:35:58.248808Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import polars as pl\nimport numpy as np\nimport pandas as pd\n# Assuming `model` is your trained model\n# Assuming features required by the model are named 'feature_00', 'feature_01', etc.\n\n\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    \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    \n    # Replace NaN and inf values with 0.0\n    features = np.nan_to_num(features, nan=0.0, posinf=0.0, neginf=0.0)\n    \n    # Apply standardization\n    features = scaler.transform(features)  # Apply the pre-fitted scaler to the features\n    \n    # Generate predictions using the model\n    if Is_keras:\n        responder_6_predictions = model.predict(features)[:, 0]\n    else:\n        responder_6_predictions = model_xgb.predict(features)\n    \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    \n    print(predictions)\n    \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\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-07T00:35:58.250516Z","iopub.execute_input":"2025-01-07T00:35:58.250844Z","iopub.status.idle":"2025-01-07T00:35:58.261225Z","shell.execute_reply.started":"2025-01-07T00:35:58.250808Z","shell.execute_reply":"2025-01-07T00:35:58.260503Z"}},"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,"execution":{"iopub.status.busy":"2025-01-07T00:35:58.262115Z","iopub.execute_input":"2025-01-07T00:35:58.262432Z","iopub.status.idle":"2025-01-07T00:35:58.301153Z","shell.execute_reply.started":"2025-01-07T00:35:58.262408Z","shell.execute_reply":"2025-01-07T00:35:58.300440Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}