{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "29f93930", "metadata": { "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19", "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5", "execution": { "iopub.execute_input": "2025-06-30T18:33:21.460315Z", "iopub.status.busy": "2025-06-30T18:33:21.459991Z", "iopub.status.idle": "2025-06-30T18:33:22.876157Z", "shell.execute_reply": "2025-06-30T18:33:22.875331Z" }, "papermill": { "duration": 1.420892, "end_time": "2025-06-30T18:33:22.877295", "exception": false, "start_time": "2025-06-30T18:33:21.456403", "status": "completed" }, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/kaggle/input/drw-crypto-market-prediction/sample_submission.csv\n", "/kaggle/input/drw-crypto-market-prediction/train.parquet\n", "/kaggle/input/drw-crypto-market-prediction/test.parquet\n" ] } ], "source": [ "# This Python 3 environment comes with many helpful analytics libraries installed\n", "# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n", "# For example, here's several helpful packages to load\n", "\n", "import numpy as np # linear algebra\n", "import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n", "\n", "# Input data files are available in the read-only \"../input/\" directory\n", "# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n", "\n", "import os\n", "for dirname, _, filenames in os.walk('/kaggle/input'):\n", " for filename in filenames:\n", " print(os.path.join(dirname, filename))\n", "\n", "# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n", "# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session" ] }, { "cell_type": "code", "execution_count": 2, "id": "722ea210", "metadata": { "execution": { "iopub.execute_input": "2025-06-30T18:33:22.882612Z", "iopub.status.busy": "2025-06-30T18:33:22.882260Z", "iopub.status.idle": "2025-07-01T04:45:09.686323Z", "shell.execute_reply": "2025-07-01T04:45:09.685475Z" }, "papermill": { "duration": 36706.813726, "end_time": "2025-07-01T04:45:09.693024", "exception": false, "start_time": "2025-06-30T18:33:22.879298", "status": "completed" }, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Using device: cpu\n", "Loaded data - Train: (525887, 32), Test: (538150, 31), Submission: (538150, 2)\n", "\n", "=== Outlier Analysis ===\n", " Strategy 'reduce': Adjusted 525 outliers (0.1% of data)\n", "\n", "Total outliers detected: 525 (0.10%)\n", "\n", "Label statistics:\n", " Normal samples - Mean: 0.0379, Std: 0.9730\n", " Outlier samples - Mean: -1.7577, Std: 8.4272\n", " Label range - Normal: [-15.8988, 20.7403]\n", " Label range - Outliers: [-24.4166, 13.1532]\n", "\n", "Top features with extreme values in outliers:\n", " X345: 974.9% difference (outlier: -0.2079, normal: 0.0238)\n", " X598: 688.8% difference (outlier: -0.1776, normal: 0.0302)\n", " buy_qty: 367.4% difference (outlier: 613.4614, normal: 131.2453)\n", " X385: 121.7% difference (outlier: -0.0153, normal: 0.0704)\n", " X168: 82.7% difference (outlier: 0.0255, normal: 0.1475)\n", " X603: 82.2% difference (outlier: 0.2858, normal: 0.1568)\n", " X174: 79.9% difference (outlier: 0.0296, normal: 0.1474)\n", " X302: 72.7% difference (outlier: 0.0634, normal: 0.2318)\n", " X415: 61.9% difference (outlier: 0.0684, normal: 0.1798)\n", " X862: 58.3% difference (outlier: -0.8237, normal: -0.5202)\n", "\n", "=== Training XGBoost Models with Outlier Strategy Comparison ===\n", "\n", "==================================================\n", "Testing outlier strategy: REDUCE\n", "==================================================\n", "\n", "--- Fold 1/3 ---\n", " Training slice: full_data, samples: 350591\n", " Training slice: last_90pct, samples: 350591\n", " Training slice: last_85pct, samples: 350591\n", " Training slice: last_80pct, samples: 350591\n", " Training slice: oldest_25pct, samples: 0\n", " Strategy 'reduce': Adjusted 350 outliers (0.1% of data)\n", " Training slice: full_data_outlier_adj, samples: 350591\n", " Strategy 'reduce': Adjusted 350 outliers (0.1% of data)\n", " Training slice: last_90pct_outlier_adj, samples: 350591\n", " Strategy 'reduce': Adjusted 350 outliers (0.1% of data)\n", " Training slice: last_85pct_outlier_adj, samples: 350591\n", " Strategy 'reduce': Adjusted 350 outliers (0.1% of data)\n", " Training slice: last_80pct_outlier_adj, samples: 350591\n", " Training slice: oldest_25pct_outlier_adj, samples: 0\n", "\n", "--- Fold 2/3 ---\n", " Training slice: full_data, samples: 350591\n", " Training slice: last_90pct, samples: 298003\n", " Training slice: last_85pct, samples: 271708\n", " Training slice: last_80pct, samples: 245414\n", " Training slice: oldest_25pct, samples: 131471\n", " Strategy 'reduce': Adjusted 350 outliers (0.1% of data)\n", " Training slice: full_data_outlier_adj, samples: 350591\n", " Strategy 'reduce': Adjusted 298 outliers (0.1% of data)\n", " Training slice: last_90pct_outlier_adj, samples: 298003\n", " Strategy 'reduce': Adjusted 271 outliers (0.1% of data)\n", " Training slice: last_85pct_outlier_adj, samples: 271708\n", " Strategy 'reduce': Adjusted 245 outliers (0.1% of data)\n", " Training slice: last_80pct_outlier_adj, samples: 245414\n", " Strategy 'reduce': Adjusted 131 outliers (0.1% of data)\n", " Training slice: oldest_25pct_outlier_adj, samples: 131471\n", "\n", "--- Fold 3/3 ---\n", " Training slice: full_data, samples: 350592\n", " Training slice: last_90pct, samples: 298004\n", " Training slice: last_85pct, samples: 271709\n", " Training slice: last_80pct, samples: 245415\n", " Training slice: oldest_25pct, samples: 131471\n", " Strategy 'reduce': Adjusted 350 outliers (0.1% of data)\n", " Training slice: full_data_outlier_adj, samples: 350592\n", " Strategy 'reduce': Adjusted 298 outliers (0.1% of data)\n", " Training slice: last_90pct_outlier_adj, samples: 298004\n", " Strategy 'reduce': Adjusted 271 outliers (0.1% of data)\n", " Training slice: last_85pct_outlier_adj, samples: 271709\n", " Strategy 'reduce': Adjusted 245 outliers (0.1% of data)\n", " Training slice: last_80pct_outlier_adj, samples: 245415\n", " Strategy 'reduce': Adjusted 131 outliers (0.1% of data)\n", " Training slice: oldest_25pct_outlier_adj, samples: 131471\n", "\n", "REDUCE Strategy - Weighted Ensemble Pearson: 0.1101\n", " full_data_outlier_adj: 0.1077 (weight: 0.112)\n", " last_90pct_outlier_adj: 0.1096 (weight: 0.112)\n", " last_85pct_outlier_adj: 0.1010 (weight: 0.112)\n", " last_80pct_outlier_adj: 0.0992 (weight: 0.112)\n", " oldest_25pct_outlier_adj: 0.0727 (weight: 0.025)\n", "\n", "==================================================\n", "Testing outlier strategy: REMOVE\n", "==================================================\n", "\n", "--- Fold 1/3 ---\n", " Training slice: full_data, samples: 350591\n", " Training slice: last_90pct, samples: 350591\n", " Training slice: last_85pct, samples: 350591\n", " Training slice: last_80pct, samples: 350591\n", " Training slice: oldest_25pct, samples: 0\n", " Strategy 'remove': Adjusted 350 outliers (0.1% of data)\n", " Training slice: full_data_outlier_adj, samples: 350591\n", " Strategy 'remove': Adjusted 350 outliers (0.1% of data)\n", " Training slice: last_90pct_outlier_adj, samples: 350591\n", " Strategy 'remove': Adjusted 350 outliers (0.1% of data)\n", " Training slice: last_85pct_outlier_adj, samples: 350591\n", " Strategy 'remove': Adjusted 350 outliers (0.1% of data)\n", " Training slice: last_80pct_outlier_adj, samples: 350591\n", " Training slice: oldest_25pct_outlier_adj, samples: 0\n", "\n", "--- Fold 2/3 ---\n", " Training slice: full_data, samples: 350591\n", " Training slice: last_90pct, samples: 298003\n", " Training slice: last_85pct, samples: 271708\n", " Training slice: last_80pct, samples: 245414\n", " Training slice: oldest_25pct, samples: 131471\n", " Strategy 'remove': Adjusted 350 outliers (0.1% of data)\n", " Training slice: full_data_outlier_adj, samples: 350591\n", " Strategy 'remove': Adjusted 298 outliers (0.1% of data)\n", " Training slice: last_90pct_outlier_adj, samples: 298003\n", " Strategy 'remove': Adjusted 271 outliers (0.1% of data)\n", " Training slice: last_85pct_outlier_adj, samples: 271708\n", " Strategy 'remove': Adjusted 245 outliers (0.1% of data)\n", " Training slice: last_80pct_outlier_adj, samples: 245414\n", " Strategy 'remove': Adjusted 131 outliers (0.1% of data)\n", " Training slice: oldest_25pct_outlier_adj, samples: 131471\n", "\n", "--- Fold 3/3 ---\n", " Training slice: full_data, samples: 350592\n", " Training slice: last_90pct, samples: 298004\n", " Training slice: last_85pct, samples: 271709\n", " Training slice: last_80pct, samples: 245415\n", " Training slice: oldest_25pct, samples: 131471\n", " Strategy 'remove': Adjusted 350 outliers (0.1% of data)\n", " Training slice: full_data_outlier_adj, samples: 350592\n", " Strategy 'remove': Adjusted 298 outliers (0.1% of data)\n", " Training slice: last_90pct_outlier_adj, samples: 298004\n", " Strategy 'remove': Adjusted 271 outliers (0.1% of data)\n", " Training slice: last_85pct_outlier_adj, samples: 271709\n", " Strategy 'remove': Adjusted 245 outliers (0.1% of data)\n", " Training slice: last_80pct_outlier_adj, samples: 245415\n", " Strategy 'remove': Adjusted 131 outliers (0.1% of data)\n", " Training slice: oldest_25pct_outlier_adj, samples: 131471\n", "\n", "REMOVE Strategy - Weighted Ensemble Pearson: 0.1107\n", " full_data_outlier_adj: 0.1092 (weight: 0.112)\n", " last_90pct_outlier_adj: 0.1140 (weight: 0.112)\n", " last_85pct_outlier_adj: 0.1009 (weight: 0.112)\n", " last_80pct_outlier_adj: 0.0978 (weight: 0.112)\n", " oldest_25pct_outlier_adj: 0.0738 (weight: 0.025)\n", "\n", "==================================================\n", "Testing outlier strategy: DOUBLE\n", "==================================================\n", "\n", "--- Fold 1/3 ---\n", " Training slice: full_data, samples: 350591\n", " Training slice: last_90pct, samples: 350591\n", " Training slice: last_85pct, samples: 350591\n", " Training slice: last_80pct, samples: 350591\n", " Training slice: oldest_25pct, samples: 0\n", " Strategy 'double': Adjusted 350 outliers (0.1% of data)\n", " Training slice: full_data_outlier_adj, samples: 350591\n", " Strategy 'double': Adjusted 350 outliers (0.1% of data)\n", " Training slice: last_90pct_outlier_adj, samples: 350591\n", " Strategy 'double': Adjusted 350 outliers (0.1% of data)\n", " Training slice: last_85pct_outlier_adj, samples: 350591\n", " Strategy 'double': Adjusted 350 outliers (0.1% of data)\n", " Training slice: last_80pct_outlier_adj, samples: 350591\n", " Training slice: oldest_25pct_outlier_adj, samples: 0\n", "\n", "--- Fold 2/3 ---\n", " Training slice: full_data, samples: 350591\n", " Training slice: last_90pct, samples: 298003\n", " Training slice: last_85pct, samples: 271708\n", " Training slice: last_80pct, samples: 245414\n", " Training slice: oldest_25pct, samples: 131471\n", " Strategy 'double': Adjusted 350 outliers (0.1% of data)\n", " Training slice: full_data_outlier_adj, samples: 350591\n", " Strategy 'double': Adjusted 298 outliers (0.1% of data)\n", " Training slice: last_90pct_outlier_adj, samples: 298003\n", " Strategy 'double': Adjusted 271 outliers (0.1% of data)\n", " Training slice: last_85pct_outlier_adj, samples: 271708\n", " Strategy 'double': Adjusted 245 outliers (0.1% of data)\n", " Training slice: last_80pct_outlier_adj, samples: 245414\n", " Strategy 'double': Adjusted 131 outliers (0.1% of data)\n", " Training slice: oldest_25pct_outlier_adj, samples: 131471\n", "\n", "--- Fold 3/3 ---\n", " Training slice: full_data, samples: 350592\n", " Training slice: last_90pct, samples: 298004\n", " Training slice: last_85pct, samples: 271709\n", " Training slice: last_80pct, samples: 245415\n", " Training slice: oldest_25pct, samples: 131471\n", " Strategy 'double': Adjusted 350 outliers (0.1% of data)\n", " Training slice: full_data_outlier_adj, samples: 350592\n", " Strategy 'double': Adjusted 298 outliers (0.1% of data)\n", " Training slice: last_90pct_outlier_adj, samples: 298004\n", " Strategy 'double': Adjusted 271 outliers (0.1% of data)\n", " Training slice: last_85pct_outlier_adj, samples: 271709\n", " Strategy 'double': Adjusted 245 outliers (0.1% of data)\n", " Training slice: last_80pct_outlier_adj, samples: 245415\n", " Strategy 'double': Adjusted 131 outliers (0.1% of data)\n", " Training slice: oldest_25pct_outlier_adj, samples: 131471\n", "\n", "DOUBLE Strategy - Weighted Ensemble Pearson: 0.1108\n", " full_data_outlier_adj: 0.1085 (weight: 0.112)\n", " last_90pct_outlier_adj: 0.1073 (weight: 0.112)\n", " last_85pct_outlier_adj: 0.1060 (weight: 0.112)\n", " last_80pct_outlier_adj: 0.1007 (weight: 0.112)\n", " oldest_25pct_outlier_adj: 0.0684 (weight: 0.025)\n", "\n", "==================================================\n", "Testing outlier strategy: NONE\n", "==================================================\n", "\n", "--- Fold 1/3 ---\n", " Training slice: full_data, samples: 350591\n", " Training slice: last_90pct, samples: 350591\n", " Training slice: last_85pct, samples: 350591\n", " Training slice: last_80pct, samples: 350591\n", " Training slice: oldest_25pct, samples: 0\n", " Training slice: full_data_outlier_adj, samples: 350591\n", " Training slice: last_90pct_outlier_adj, samples: 350591\n", " Training slice: last_85pct_outlier_adj, samples: 350591\n", " Training slice: last_80pct_outlier_adj, samples: 350591\n", " Training slice: oldest_25pct_outlier_adj, samples: 0\n", "\n", "--- Fold 2/3 ---\n", " Training slice: full_data, samples: 350591\n", " Training slice: last_90pct, samples: 298003\n", " Training slice: last_85pct, samples: 271708\n", " Training slice: last_80pct, samples: 245414\n", " Training slice: oldest_25pct, samples: 131471\n", " Training slice: full_data_outlier_adj, samples: 350591\n", " Training slice: last_90pct_outlier_adj, samples: 298003\n", " Training slice: last_85pct_outlier_adj, samples: 271708\n", " Training slice: last_80pct_outlier_adj, samples: 245414\n", " Training slice: oldest_25pct_outlier_adj, samples: 131471\n", "\n", "--- Fold 3/3 ---\n", " Training slice: full_data, samples: 350592\n", " Training slice: last_90pct, samples: 298004\n", " Training slice: last_85pct, samples: 271709\n", " Training slice: last_80pct, samples: 245415\n", " Training slice: oldest_25pct, samples: 131471\n", " Training slice: full_data_outlier_adj, samples: 350592\n", " Training slice: last_90pct_outlier_adj, samples: 298004\n", " Training slice: last_85pct_outlier_adj, samples: 271709\n", " Training slice: last_80pct_outlier_adj, samples: 245415\n", " Training slice: oldest_25pct_outlier_adj, samples: 131471\n", "\n", "NONE Strategy - Weighted Ensemble Pearson: 0.1106\n", " full_data_outlier_adj: 0.1121 (weight: 0.112)\n", " last_90pct_outlier_adj: 0.1084 (weight: 0.112)\n", " last_85pct_outlier_adj: 0.1032 (weight: 0.112)\n", " last_80pct_outlier_adj: 0.1004 (weight: 0.112)\n", " oldest_25pct_outlier_adj: 0.0737 (weight: 0.025)\n", "\n", "==================================================\n", "OUTLIER STRATEGY COMPARISON SUMMARY\n", "==================================================\n", "REDUCE: 0.1101 \n", "REMOVE: 0.1107 \n", "DOUBLE: 0.1108 ← BEST\n", "NONE: 0.1106 \n", "\n", "Relative performance vs 'reduce' strategy:\n", " remove: +0.59%\n", " double: +0.65%\n", " none: +0.50%\n", "\n", "XGB Weighted Ensemble Pearson: 0.1108\n", "\n", "Individual slice OOF scores and weights:\n", " full_data: 0.1121 (weight: 0.124)\n", " last_90pct: 0.1084 (weight: 0.124)\n", " last_85pct: 0.1032 (weight: 0.124)\n", " last_80pct: 0.1004 (weight: 0.124)\n", " oldest_25pct: 0.0737 (weight: 0.031)\n", " full_data_outlier_adj: 0.1085 (weight: 0.112)\n", " last_90pct_outlier_adj: 0.1073 (weight: 0.112)\n", " last_85pct_outlier_adj: 0.1060 (weight: 0.112)\n", " last_80pct_outlier_adj: 0.1007 (weight: 0.112)\n", " oldest_25pct_outlier_adj: 0.0684 (weight: 0.025)\n", "\n", "Saved: submission_xgboost_double.csv\n", "\n", "=== Training MLP Model ===\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Epoch 1/10: 100%|██████████| 13/13 [00:07<00:00, 1.68it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Training Loss: 16059.1512\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Validation: 100%|██████████| 4/4 [00:01<00:00, 2.93it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Validation Pearson Coef: 0.0700 | Loss: 15180.1740\n", "✅ New best model saved with Pearson: 0.0700\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Epoch 2/10: 100%|██████████| 13/13 [00:06<00:00, 2.02it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Training Loss: 15595.0242\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Validation: 100%|██████████| 4/4 [00:01<00:00, 3.01it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Validation Pearson Coef: 0.0838 | Loss: 15198.4545\n", "✅ New best model saved with Pearson: 0.0838\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Epoch 3/10: 100%|██████████| 13/13 [00:06<00:00, 1.91it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Training Loss: 15456.7179\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Validation: 100%|██████████| 4/4 [00:01<00:00, 3.01it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Validation Pearson Coef: 0.0992 | Loss: 15219.1834\n", "✅ New best model saved with Pearson: 0.0992\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Epoch 4/10: 100%|██████████| 13/13 [00:06<00:00, 2.04it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Training Loss: 15348.7826\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Validation: 100%|██████████| 4/4 [00:01<00:00, 2.97it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Validation Pearson Coef: 0.1021 | Loss: 15224.5020\n", "✅ New best model saved with Pearson: 0.1021\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Epoch 5/10: 100%|██████████| 13/13 [00:06<00:00, 2.01it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Training Loss: 15229.8266\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Validation: 100%|██████████| 4/4 [00:01<00:00, 2.84it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Validation Pearson Coef: 0.1045 | Loss: 15242.1837\n", "✅ New best model saved with Pearson: 0.1045\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Epoch 6/10: 100%|██████████| 13/13 [00:06<00:00, 1.89it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Training Loss: 15138.1736\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Validation: 100%|██████████| 4/4 [00:01<00:00, 2.99it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Validation Pearson Coef: 0.1075 | Loss: 15256.6681\n", "✅ New best model saved with Pearson: 0.1075\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Epoch 7/10: 100%|██████████| 13/13 [00:06<00:00, 1.96it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Training Loss: 15046.1952\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Validation: 100%|██████████| 4/4 [00:01<00:00, 2.80it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Validation Pearson Coef: 0.1046 | Loss: 15321.9877\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Epoch 8/10: 100%|██████████| 13/13 [00:06<00:00, 1.91it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Training Loss: 14938.4061\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Validation: 100%|██████████| 4/4 [00:01<00:00, 2.91it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Validation Pearson Coef: 0.1099 | Loss: 15279.2798\n", "✅ New best model saved with Pearson: 0.1099\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Epoch 9/10: 100%|██████████| 13/13 [00:06<00:00, 1.89it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Training Loss: 14854.4186\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Validation: 100%|██████████| 4/4 [00:01<00:00, 2.88it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Validation Pearson Coef: 0.1111 | Loss: 15291.8269\n", "✅ New best model saved with Pearson: 0.1111\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Epoch 10/10: 100%|██████████| 13/13 [00:07<00:00, 1.85it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Training Loss: 14737.5036\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Validation: 100%|██████████| 4/4 [00:01<00:00, 2.71it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Validation Pearson Coef: 0.1117 | Loss: 15297.1565\n", "✅ New best model saved with Pearson: 0.1117\n", "Model loaded from best_mlp_model.pt with best Pearson: 0.1117\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Predicting: 100%|██████████| 17/17 [00:04<00:00, 3.75it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Saved: submission_mlp.csv\n", "\n", "Saved: submission_ensemble_double.csv (XGBoost: 90.0%, MLP: 10.0%)\n", "\n", "============================================================\n", "FINAL SUMMARY\n", "============================================================\n", "\n", "Best outlier strategy: DOUBLE\n", "Best XGBoost CV score: 0.1108\n", "\n", "Strategy comparison (XGBoost ensemble scores):\n", " reduce: 0.1101\n", " remove: 0.1107\n", " double: 0.1108\n", " none: 0.1106\n", "\n", "Created submission files:\n", "1. submission_xgboost_double.csv - XGBoost with double strategy\n", "2. submission_mlp.csv - MLP only\n", "3. submission_ensemble_double.csv - 90% XGBoost + 10% MLP\n", "\n", "Sample predictions (first 10 rows):\n", " ID XGBoost MLP Ensemble\n", "0 1 0.035090 0.217608 0.053342\n", "1 2 0.018095 -0.070474 0.009238\n", "2 3 0.136497 0.070964 0.129943\n", "3 4 -0.085066 -0.007894 -0.077348\n", "4 5 0.211597 0.238769 0.214314\n", "5 6 -0.172887 -0.198609 -0.175459\n", "6 7 -0.419656 -0.523997 -0.430090\n", "7 8 -0.154374 -0.422084 -0.181145\n", "8 9 0.222065 -0.204875 0.179371\n", "9 10 0.096913 0.106206 0.097842\n", "\n", "============================================================\n", "RECOMMENDATIONS\n", "============================================================\n", "\n", "1. Outlier Handling Impact:\n", " ! Doubling outlier weights performs better\n", " → This suggests outliers contain valuable signal for extreme movements\n", "\n", "2. Overfitting Risk Assessment:\n", " ✓ Emphasizing outliers improves performance\n", " → Model benefits from learning extreme patterns\n", "\n", "3. Next Steps:\n", " • Test different outlier fractions (0.05%, 0.2%, 0.5%)\n", " • Try adaptive outlier detection per time slice\n", " • Consider feature-specific outlier handling\n", " • Monitor LB score vs CV score for overfitting signs\n", "\n", "4. Outlier Insights:\n", " • Detected 525 outliers (0.10% of data)\n", " • Consider creating synthetic outliers if 'double' strategy works well\n", " • Analyze time distribution of outliers for market regime insights\n" ] } ], "source": [ "from sklearn.model_selection import KFold, train_test_split\n", "from xgboost import XGBRegressor\n", "from scipy.stats import pearsonr\n", "import numpy as np\n", "import pandas as pd\n", "from sklearn.ensemble import RandomForestRegressor\n", "from sklearn.preprocessing import StandardScaler\n", "from tqdm import tqdm\n", "import random\n", "import warnings\n", "warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n", "\n", "# Deep Learning imports\n", "import torch\n", "import torch.nn as nn\n", "import torch.optim as optim\n", "from torch.utils.data import DataLoader, TensorDataset\n", "\n", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "print(f\"Using device: {device}\")\n", "\n", "# =========================\n", "# Configuration\n", "# =========================\n", "class Config:\n", " TRAIN_PATH = \"/kaggle/input/drw-crypto-market-prediction/train.parquet\"\n", " TEST_PATH = \"/kaggle/input/drw-crypto-market-prediction/test.parquet\"\n", " SUBMISSION_PATH = \"/kaggle/input/drw-crypto-market-prediction/sample_submission.csv\"\n", "\n", " FEATURES = [\n", " \"X863\", \"X856\", \"X598\", \"X862\", \"X385\", \"X852\", \"X603\", \"X860\", \"X674\",\n", " \"X415\", \"X345\", \"X855\", \"X174\", \"X302\", \"X178\", \"X168\", \"X612\", \"bid_qty\",\n", " \"ask_qty\", \"buy_qty\", \"sell_qty\", \"volume\", \"X888\", \"X421\", \"X333\",\"X817\", \n", " \"X586\", \"X292\"\n", " ]\n", " \n", " # Features for MLP (subset)\n", " MLP_FEATURES = [\n", " \"X863\", \"X856\", \"X344\", \"X598\", \"X862\", \"X385\", \"X852\", \"X603\", \"X860\", \"X674\",\n", " \"X415\", \"X345\", \"X137\", \"X855\", \"X174\", \"X302\", \"X178\", \"X532\", \"X168\", \"X612\",\n", " \"bid_qty\", \"ask_qty\", \"buy_qty\", \"sell_qty\", \"volume\"\n", " ]\n", "\n", " LABEL_COLUMN = \"label\"\n", " N_FOLDS = 3\n", " RANDOM_STATE = 42\n", " OUTLIER_FRACTION = 0.001 # 0.1% of records\n", " \n", " # Outlier handling strategies to test\n", " OUTLIER_STRATEGIES = [\"reduce\", \"remove\", \"double\", \"none\"]\n", "\n", "XGB_PARAMS = {\n", " \"tree_method\": \"hist\",\n", " \"device\": \"gpu\" if torch.cuda.is_available() else \"cpu\",\n", " \"colsample_bylevel\": 0.4778,\n", " \"colsample_bynode\": 0.3628,\n", " \"colsample_bytree\": 0.7107,\n", " \"gamma\": 1.7095,\n", " \"learning_rate\": 0.02213,\n", " \"max_depth\": 20,\n", " \"max_leaves\": 12,\n", " \"min_child_weight\": 16,\n", " \"n_estimators\": 1667,\n", " \"subsample\": 0.06567,\n", " \"reg_alpha\": 39.3524,\n", " \"reg_lambda\": 75.4484,\n", " \"verbosity\": 0,\n", " \"random_state\": Config.RANDOM_STATE,\n", " \"n_jobs\": -1\n", "}\n", "\n", "LEARNERS = [\n", " {\"name\": \"xgb\", \"Estimator\": XGBRegressor, \"params\": XGB_PARAMS}\n", "]\n", "\n", "# =========================\n", "# Deep Learning Components\n", "# =========================\n", "def set_seed(seed=42):\n", " random.seed(seed)\n", " np.random.seed(seed)\n", " torch.manual_seed(seed)\n", " torch.cuda.manual_seed(seed)\n", " torch.cuda.manual_seed_all(seed)\n", " torch.backends.cudnn.deterministic = True\n", " torch.backends.cudnn.benchmark = False\n", "\n", "def get_activation_function(name):\n", " \"\"\"Return the activation function based on the name.\"\"\"\n", " if name == None:\n", " return None\n", " name = name.lower()\n", " if name == 'relu':\n", " return nn.ReLU()\n", " elif name == 'tanh':\n", " return nn.Tanh()\n", " elif name == 'sigmoid':\n", " return nn.Sigmoid()\n", " else:\n", " raise ValueError(f\"Unsupported activation function: {name}\")\n", "\n", "class MLP(nn.Module):\n", " def __init__(self, dropout_rate=0.6, \n", " layers=[128, 64], activation='relu', last_activation=None):\n", " super(MLP, self).__init__()\n", " \n", " self.linears = nn.ModuleList()\n", " self.activation = get_activation_function(activation)\n", " self.last_activation = get_activation_function(last_activation)\n", "\n", " for i in range(len(layers) - 1):\n", " self.linears.append(nn.Linear(layers[i], layers[i + 1]))\n", "\n", " self.dropout = nn.Dropout(dropout_rate)\n", "\n", " def forward(self, x):\n", " for k in range(len(self.linears) - 1):\n", " x = self.activation(self.linears[k](x))\n", " x = self.dropout(x)\n", " x = self.linears[-1](x)\n", " if self.last_activation is not None:\n", " x = self.last_activation(x)\n", " return x\n", "\n", "class Checkpointer:\n", " def __init__(self, path=\"best_model.pt\"):\n", " self.path = path\n", " self.best_pearson = -np.inf\n", "\n", " def load(self, model):\n", " \"\"\"Load the best model weights.\"\"\"\n", " model.load_state_dict(torch.load(self.path, map_location=device))\n", " print(f\"Model loaded from {self.path} with best Pearson: {self.best_pearson:.4f}\")\n", " return model\n", "\n", " def __call__(self, pearson_coef, model):\n", " \"\"\"Call method to save the model if the Pearson coefficient is better than the best one.\"\"\"\n", " if pearson_coef > self.best_pearson:\n", " self.best_pearson = pearson_coef\n", " torch.save(model.state_dict(), self.path)\n", " print(f\"✅ New best model saved with Pearson: {pearson_coef:.4f}\")\n", "\n", "def get_dataloaders(X, Y, hparams, device, shuffle=True):\n", " \"\"\"Create DataLoader for training and validation datasets.\"\"\"\n", " X_tensor = torch.tensor(X, dtype=torch.float32, device=device)\n", " if Y is not None:\n", " Y_tensor = torch.tensor(Y.values if hasattr(Y, 'values') else Y, \n", " dtype=torch.float32, device=device).unsqueeze(1)\n", " dataset = TensorDataset(X_tensor, Y_tensor)\n", " else:\n", " dataset = TensorDataset(X_tensor)\n", " \n", " dataloader = DataLoader(dataset, batch_size=hparams[\"batch_size\"], shuffle=shuffle, \n", " generator=torch.Generator().manual_seed(hparams[\"seed\"]))\n", " return dataloader\n", "\n", "# =========================\n", "# Feature Engineering\n", "# =========================\n", "def add_features(df):\n", " # Original features\n", " df['bid_ask_interaction'] = df['bid_qty'] * df['ask_qty']\n", " df['bid_buy_interaction'] = df['bid_qty'] * df['buy_qty']\n", " df['bid_sell_interaction'] = df['bid_qty'] * df['sell_qty']\n", " df['ask_buy_interaction'] = df['ask_qty'] * df['buy_qty']\n", " df['ask_sell_interaction'] = df['ask_qty'] * df['sell_qty']\n", "\n", " df['volume_weighted_sell'] = df['sell_qty'] * df['volume']\n", " df['buy_sell_ratio'] = df['buy_qty'] / (df['sell_qty'] + 1e-10)\n", " df['selling_pressure'] = df['sell_qty'] / (df['volume'] + 1e-10)\n", " df['log_volume'] = np.log1p(df['volume'])\n", "\n", " df['effective_spread_proxy'] = np.abs(df['buy_qty'] - df['sell_qty']) / (df['volume'] + 1e-10)\n", " df['bid_ask_imbalance'] = (df['bid_qty'] - df['ask_qty']) / (df['bid_qty'] + df['ask_qty'] + 1e-10)\n", " df['order_flow_imbalance'] = (df['buy_qty'] - df['sell_qty']) / (df['buy_qty'] + df['sell_qty'] + 1e-10)\n", " df['liquidity_ratio'] = (df['bid_qty'] + df['ask_qty']) / (df['volume'] + 1e-10)\n", " \n", " # === NEW MICROSTRUCTURE FEATURES ===\n", " \n", " # Price Pressure Indicators\n", " df['net_order_flow'] = df['buy_qty'] - df['sell_qty']\n", " df['normalized_net_flow'] = df['net_order_flow'] / (df['volume'] + 1e-10)\n", " df['buying_pressure'] = df['buy_qty'] / (df['volume'] + 1e-10)\n", " df['volume_weighted_buy'] = df['buy_qty'] * df['volume']\n", " \n", " # Liquidity Depth Measures\n", " df['total_depth'] = df['bid_qty'] + df['ask_qty']\n", " df['depth_imbalance'] = (df['bid_qty'] - df['ask_qty']) / (df['total_depth'] + 1e-10)\n", " df['relative_spread'] = np.abs(df['bid_qty'] - df['ask_qty']) / (df['total_depth'] + 1e-10)\n", " df['log_depth'] = np.log1p(df['total_depth'])\n", " \n", " # Order Flow Toxicity Proxies\n", " df['kyle_lambda'] = np.abs(df['net_order_flow']) / (df['volume'] + 1e-10)\n", " df['flow_toxicity'] = np.abs(df['order_flow_imbalance']) * df['volume']\n", " df['aggressive_flow_ratio'] = (df['buy_qty'] + df['sell_qty']) / (df['total_depth'] + 1e-10)\n", " \n", " # Market Activity Indicators\n", " df['volume_depth_ratio'] = df['volume'] / (df['total_depth'] + 1e-10)\n", " df['activity_intensity'] = (df['buy_qty'] + df['sell_qty']) / (df['volume'] + 1e-10)\n", " df['log_buy_qty'] = np.log1p(df['buy_qty'])\n", " df['log_sell_qty'] = np.log1p(df['sell_qty'])\n", " df['log_bid_qty'] = np.log1p(df['bid_qty'])\n", " df['log_ask_qty'] = np.log1p(df['ask_qty'])\n", " \n", " # Microstructure Volatility Proxies\n", " df['realized_spread_proxy'] = 2 * np.abs(df['net_order_flow']) / (df['volume'] + 1e-10)\n", " df['price_impact_proxy'] = df['net_order_flow'] / (df['total_depth'] + 1e-10)\n", " df['quote_volatility_proxy'] = np.abs(df['depth_imbalance'])\n", " \n", " # Complex Interaction Terms\n", " df['flow_depth_interaction'] = df['net_order_flow'] * df['total_depth']\n", " df['imbalance_volume_interaction'] = df['order_flow_imbalance'] * df['volume']\n", " df['depth_volume_interaction'] = df['total_depth'] * df['volume']\n", " df['buy_sell_spread'] = np.abs(df['buy_qty'] - df['sell_qty'])\n", " df['bid_ask_spread'] = np.abs(df['bid_qty'] - df['ask_qty'])\n", " \n", " # Information Asymmetry Measures\n", " df['trade_informativeness'] = df['net_order_flow'] / (df['bid_qty'] + df['ask_qty'] + 1e-10)\n", " df['execution_shortfall_proxy'] = df['buy_sell_spread'] / (df['volume'] + 1e-10)\n", " df['adverse_selection_proxy'] = df['net_order_flow'] / (df['total_depth'] + 1e-10) * df['volume']\n", " \n", " # Market Efficiency Indicators\n", " df['fill_probability'] = df['volume'] / (df['buy_qty'] + df['sell_qty'] + 1e-10)\n", " df['execution_rate'] = (df['buy_qty'] + df['sell_qty']) / (df['total_depth'] + 1e-10)\n", " df['market_efficiency'] = df['volume'] / (df['bid_ask_spread'] + 1e-10)\n", " \n", " # Non-linear Transformations\n", " df['sqrt_volume'] = np.sqrt(df['volume'])\n", " df['sqrt_depth'] = np.sqrt(df['total_depth'])\n", " df['volume_squared'] = df['volume'] ** 2\n", " df['imbalance_squared'] = df['order_flow_imbalance'] ** 2\n", " \n", " # Relative Measures\n", " df['bid_ratio'] = df['bid_qty'] / (df['total_depth'] + 1e-10)\n", " df['ask_ratio'] = df['ask_qty'] / (df['total_depth'] + 1e-10)\n", " df['buy_ratio'] = df['buy_qty'] / (df['buy_qty'] + df['sell_qty'] + 1e-10)\n", " df['sell_ratio'] = df['sell_qty'] / (df['buy_qty'] + df['sell_qty'] + 1e-10)\n", " \n", " # Market Stress Indicators\n", " df['liquidity_consumption'] = (df['buy_qty'] + df['sell_qty']) / (df['total_depth'] + 1e-10)\n", " df['market_stress'] = df['volume'] / (df['total_depth'] + 1e-10) * np.abs(df['order_flow_imbalance'])\n", " df['depth_depletion'] = df['volume'] / (df['bid_qty'] + df['ask_qty'] + 1e-10)\n", " \n", " # Directional Indicators\n", " df['net_buying_ratio'] = df['net_order_flow'] / (df['volume'] + 1e-10)\n", " df['directional_volume'] = df['net_order_flow'] * np.log1p(df['volume'])\n", " df['signed_volume'] = np.sign(df['net_order_flow']) * df['volume']\n", " \n", " # Replace infinities and NaNs\n", " df = df.replace([np.inf, -np.inf], 0).fillna(0)\n", " \n", " return df\n", "\n", "def create_time_decay_weights(n: int, decay: float = 0.9) -> np.ndarray:\n", " positions = np.arange(n)\n", " normalized = positions / (n - 1) if n > 1 else positions\n", " weights = decay ** (1.0 - normalized)\n", " return weights * n / weights.sum()\n", "\n", "def detect_outliers_and_adjust_weights(X, y, sample_weights, outlier_fraction=0.001, strategy=\"reduce\"):\n", " \"\"\"\n", " Detect outliers based on prediction residuals and adjust their weights.\n", " \n", " Strategies:\n", " - \"reduce\": Current approach - reduce weights to 0.2-0.8x\n", " - \"remove\": Set outlier weights to 0 (effectively removing them)\n", " - \"double\": Double the weights of outliers\n", " - \"none\": No adjustment\n", " \"\"\"\n", " if strategy == \"none\":\n", " return sample_weights, np.zeros(len(y), dtype=bool)\n", " \n", " # Ensure we have at least some samples to detect outliers\n", " n_samples = len(y)\n", " if n_samples < 100: # Not enough samples for meaningful outlier detection\n", " print(f\" Too few samples ({n_samples}) for outlier detection\")\n", " return sample_weights, np.zeros(n_samples, dtype=bool)\n", " \n", " # Train a simple model to get residuals\n", " rf = RandomForestRegressor(n_estimators=50, max_depth=10, random_state=42, n_jobs=-1)\n", " rf.fit(X, y, sample_weight=sample_weights)\n", " \n", " # Calculate residuals\n", " predictions = rf.predict(X)\n", " residuals = np.abs(y - predictions)\n", " \n", " # Find threshold for top outlier_fraction\n", " # Ensure we have at least 1 outlier\n", " n_outliers = max(1, int(len(residuals) * outlier_fraction))\n", " \n", " # Sort residuals and get threshold\n", " sorted_residuals = np.sort(residuals)\n", " threshold = sorted_residuals[-n_outliers] if n_outliers <= len(residuals) else sorted_residuals[-1]\n", " \n", " # Create outlier mask\n", " outlier_mask = residuals >= threshold\n", " \n", " # Ensure we have exactly n_outliers (handle ties at threshold)\n", " if np.sum(outlier_mask) > n_outliers:\n", " # If we have too many due to ties, randomly select to get exact number\n", " outlier_indices = np.where(outlier_mask)[0]\n", " np.random.seed(42)\n", " selected_indices = np.random.choice(outlier_indices, n_outliers, replace=False)\n", " outlier_mask = np.zeros(len(y), dtype=bool)\n", " outlier_mask[selected_indices] = True\n", " \n", " # Adjust weights based on strategy\n", " adjusted_weights = sample_weights.copy()\n", " \n", " if outlier_mask.any():\n", " if strategy == \"reduce\":\n", " # Original approach: reduce weights proportionally\n", " outlier_residuals = residuals[outlier_mask]\n", " min_outlier_res = outlier_residuals.min()\n", " max_outlier_res = outlier_residuals.max()\n", " \n", " if max_outlier_res > min_outlier_res:\n", " normalized_residuals = (outlier_residuals - min_outlier_res) / (max_outlier_res - min_outlier_res)\n", " else:\n", " normalized_residuals = np.ones_like(outlier_residuals)\n", " \n", " weight_factors = 0.8 - 0.6 * normalized_residuals\n", " adjusted_weights[outlier_mask] *= weight_factors\n", " \n", " elif strategy == \"remove\":\n", " # Set outlier weights to 0\n", " adjusted_weights[outlier_mask] = 0\n", " \n", " elif strategy == \"double\":\n", " # Double the weights of outliers\n", " adjusted_weights[outlier_mask] *= 2.0\n", " \n", " print(f\" Strategy '{strategy}': Adjusted {n_outliers} outliers ({outlier_fraction*100:.1f}% of data)\")\n", " \n", " return adjusted_weights, outlier_mask\n", "\n", "def load_data():\n", " # Load data with all features available\n", " all_features = list(set(Config.FEATURES + Config.MLP_FEATURES))\n", " train_df = pd.read_parquet(Config.TRAIN_PATH, columns=all_features + [Config.LABEL_COLUMN])\n", " test_df = pd.read_parquet(Config.TEST_PATH, columns=all_features)\n", " submission_df = pd.read_csv(Config.SUBMISSION_PATH)\n", " print(f\"Loaded data - Train: {train_df.shape}, Test: {test_df.shape}, Submission: {submission_df.shape}\")\n", "\n", " # Add features\n", " train_df = add_features(train_df)\n", " test_df = add_features(test_df)\n", "\n", " # Update Config.FEATURES with new features\n", " Config.FEATURES += [\n", " \"log_volume\", 'bid_ask_interaction', 'bid_buy_interaction', 'bid_sell_interaction', \n", " 'ask_buy_interaction', 'ask_sell_interaction', 'net_order_flow', 'normalized_net_flow',\n", " 'buying_pressure', 'volume_weighted_buy', 'total_depth', 'depth_imbalance',\n", " 'relative_spread', 'log_depth', 'kyle_lambda', 'flow_toxicity', 'aggressive_flow_ratio',\n", " 'volume_depth_ratio', 'activity_intensity', 'log_buy_qty', 'log_sell_qty',\n", " 'log_bid_qty', 'log_ask_qty', 'realized_spread_proxy', 'price_impact_proxy',\n", " 'quote_volatility_proxy', 'flow_depth_interaction', 'imbalance_volume_interaction',\n", " 'depth_volume_interaction', 'buy_sell_spread', 'bid_ask_spread', 'trade_informativeness',\n", " 'execution_shortfall_proxy', 'adverse_selection_proxy', 'fill_probability',\n", " 'execution_rate', 'market_efficiency', 'sqrt_volume', 'sqrt_depth', 'volume_squared',\n", " 'imbalance_squared', 'bid_ratio', 'ask_ratio', 'buy_ratio', 'sell_ratio',\n", " 'liquidity_consumption', 'market_stress', 'depth_depletion', 'net_buying_ratio',\n", " 'directional_volume', 'signed_volume'\n", " ]\n", "\n", " return train_df.reset_index(drop=True), test_df.reset_index(drop=True), submission_df\n", "\n", "def get_model_slices(n_samples: int):\n", " # Original 5 slices\n", " base_slices = [\n", " {\"name\": \"full_data\", \"cutoff\": 0, \"is_oldest\": False, \"outlier_adjusted\": False},\n", " {\"name\": \"last_90pct\", \"cutoff\": int(0.10 * n_samples), \"is_oldest\": False, \"outlier_adjusted\": False},\n", " {\"name\": \"last_85pct\", \"cutoff\": int(0.15 * n_samples), \"is_oldest\": False, \"outlier_adjusted\": False},\n", " {\"name\": \"last_80pct\", \"cutoff\": int(0.20 * n_samples), \"is_oldest\": False, \"outlier_adjusted\": False},\n", " {\"name\": \"oldest_25pct\", \"cutoff\": int(0.25 * n_samples), \"is_oldest\": True, \"outlier_adjusted\": False},\n", " ]\n", " \n", " # Duplicate slices with outlier adjustment\n", " outlier_adjusted_slices = []\n", " for slice_info in base_slices:\n", " adjusted_slice = slice_info.copy()\n", " adjusted_slice[\"name\"] = f\"{slice_info['name']}_outlier_adj\"\n", " adjusted_slice[\"outlier_adjusted\"] = True\n", " outlier_adjusted_slices.append(adjusted_slice)\n", " \n", " return base_slices + outlier_adjusted_slices\n", "\n", "# =========================\n", "# Outlier Analysis Functions\n", "# =========================\n", "def analyze_outliers(train_df):\n", " \"\"\"Analyze outliers in the training data\"\"\"\n", " print(\"\\n=== Outlier Analysis ===\")\n", " \n", " X = train_df[Config.FEATURES].values\n", " y = train_df[Config.LABEL_COLUMN].values\n", " \n", " # Get base weights\n", " sample_weights = create_time_decay_weights(len(train_df))\n", " \n", " # Detect outliers\n", " _, outlier_mask = detect_outliers_and_adjust_weights(\n", " X, y, sample_weights, outlier_fraction=Config.OUTLIER_FRACTION, strategy=\"reduce\"\n", " )\n", " \n", " # Analyze outlier characteristics\n", " outlier_indices = np.where(outlier_mask)[0]\n", " n_outliers = len(outlier_indices)\n", " \n", " print(f\"\\nTotal outliers detected: {n_outliers} ({n_outliers/len(train_df)*100:.2f}%)\")\n", " \n", " if n_outliers > 0:\n", " # Statistical analysis\n", " outlier_labels = y[outlier_mask]\n", " normal_labels = y[~outlier_mask]\n", " \n", " print(f\"\\nLabel statistics:\")\n", " print(f\" Normal samples - Mean: {normal_labels.mean():.4f}, Std: {normal_labels.std():.4f}\")\n", " print(f\" Outlier samples - Mean: {outlier_labels.mean():.4f}, Std: {outlier_labels.std():.4f}\")\n", " print(f\" Label range - Normal: [{normal_labels.min():.4f}, {normal_labels.max():.4f}]\")\n", " print(f\" Label range - Outliers: [{outlier_labels.min():.4f}, {outlier_labels.max():.4f}]\")\n", " \n", " # Feature analysis for outliers\n", " print(f\"\\nTop features with extreme values in outliers:\")\n", " feature_names = Config.FEATURES[:20] # Analyze first 20 features\n", " outlier_features = train_df.iloc[outlier_indices][feature_names]\n", " normal_features = train_df.iloc[~outlier_mask][feature_names]\n", " \n", " feature_diffs = []\n", " for feat in feature_names:\n", " outlier_mean = outlier_features[feat].mean()\n", " normal_mean = normal_features[feat].mean()\n", " if normal_mean != 0:\n", " rel_diff = abs(outlier_mean - normal_mean) / abs(normal_mean)\n", " feature_diffs.append((feat, rel_diff, outlier_mean, normal_mean))\n", " \n", " feature_diffs.sort(key=lambda x: x[1], reverse=True)\n", " for feat, diff, out_mean, norm_mean in feature_diffs[:10]:\n", " print(f\" {feat}: {diff*100:.1f}% difference (outlier: {out_mean:.4f}, normal: {norm_mean:.4f})\")\n", " else:\n", " print(\"\\nNo outliers detected with current threshold. Consider adjusting outlier_fraction.\")\n", " \n", " return outlier_indices\n", "\n", "# =========================\n", "# XGBoost Training with Outlier Strategy Comparison\n", "# =========================\n", "def train_xgboost_with_outlier_comparison(train_df, test_df):\n", " \"\"\"Train XGBoost with different outlier handling strategies and compare results\"\"\"\n", " n_samples = len(train_df)\n", " \n", " # Store results for each strategy\n", " strategy_results = {strategy: {\"oof_scores\": [], \"slice_scores\": {}} \n", " for strategy in Config.OUTLIER_STRATEGIES}\n", " \n", " # For final ensemble\n", " best_strategy = \"reduce\" # Default to current approach\n", " best_score = -np.inf\n", " best_oof_preds = None\n", " best_test_preds = None\n", " \n", " for strategy in Config.OUTLIER_STRATEGIES:\n", " print(f\"\\n{'='*50}\")\n", " print(f\"Testing outlier strategy: {strategy.upper()}\")\n", " print(f\"{'='*50}\")\n", " \n", " # Get model slices for this strategy\n", " model_slices = get_model_slices(n_samples)\n", " \n", " oof_preds = {\n", " learner[\"name\"]: {s[\"name\"]: np.zeros(n_samples) for s in model_slices}\n", " for learner in LEARNERS\n", " }\n", " test_preds = {\n", " learner[\"name\"]: {s[\"name\"]: np.zeros(len(test_df)) for s in model_slices}\n", " for learner in LEARNERS\n", " }\n", " \n", " full_weights = create_time_decay_weights(n_samples)\n", " kf = KFold(n_splits=Config.N_FOLDS, shuffle=False)\n", " \n", " for fold, (train_idx, valid_idx) in enumerate(kf.split(train_df), start=1):\n", " print(f\"\\n--- Fold {fold}/{Config.N_FOLDS} ---\")\n", " X_valid = train_df.iloc[valid_idx][Config.FEATURES]\n", " y_valid = train_df.iloc[valid_idx][Config.LABEL_COLUMN]\n", " \n", " for s in model_slices:\n", " cutoff = s[\"cutoff\"]\n", " slice_name = s[\"name\"]\n", " is_oldest = s[\"is_oldest\"]\n", " outlier_adjusted = s.get(\"outlier_adjusted\", False)\n", " \n", " if is_oldest:\n", " subset = train_df.iloc[:cutoff].reset_index(drop=True)\n", " rel_idx = train_idx[train_idx < cutoff]\n", " sw = np.ones(len(rel_idx))\n", " else:\n", " subset = train_df.iloc[cutoff:].reset_index(drop=True)\n", " rel_idx = train_idx[train_idx >= cutoff] - cutoff\n", " sw = create_time_decay_weights(len(subset))[rel_idx] if cutoff > 0 else full_weights[train_idx]\n", " \n", " X_train = subset.iloc[rel_idx][Config.FEATURES]\n", " y_train = subset.iloc[rel_idx][Config.LABEL_COLUMN]\n", " \n", " # Apply outlier strategy if this is an outlier-adjusted slice\n", " if outlier_adjusted and len(X_train) > 100:\n", " sw, _ = detect_outliers_and_adjust_weights(\n", " X_train.values, \n", " y_train.values, \n", " sw, \n", " outlier_fraction=Config.OUTLIER_FRACTION,\n", " strategy=strategy\n", " )\n", " \n", " print(f\" Training slice: {slice_name}, samples: {len(X_train)}\")\n", " \n", " for learner in LEARNERS:\n", " model = learner[\"Estimator\"](**learner[\"params\"])\n", " model.fit(X_train, y_train, sample_weight=sw, eval_set=[(X_valid, y_valid)], verbose=False)\n", " \n", " if is_oldest:\n", " oof_preds[learner[\"name\"]][slice_name][valid_idx] = model.predict(\n", " train_df.iloc[valid_idx][Config.FEATURES]\n", " )\n", " else:\n", " mask = valid_idx >= cutoff\n", " if mask.any():\n", " idxs = valid_idx[mask]\n", " oof_preds[learner[\"name\"]][slice_name][idxs] = model.predict(\n", " train_df.iloc[idxs][Config.FEATURES]\n", " )\n", " if cutoff > 0 and (~mask).any():\n", " base_slice_name = slice_name.replace(\"_outlier_adj\", \"\")\n", " if base_slice_name == slice_name:\n", " fallback_slice = \"full_data\"\n", " else:\n", " fallback_slice = \"full_data_outlier_adj\"\n", " oof_preds[learner[\"name\"]][slice_name][valid_idx[~mask]] = oof_preds[learner[\"name\"]][fallback_slice][\n", " valid_idx[~mask]\n", " ]\n", " \n", " test_preds[learner[\"name\"]][slice_name] += model.predict(test_df[Config.FEATURES])\n", " \n", " # Normalize test predictions\n", " for learner_name in test_preds:\n", " for slice_name in test_preds[learner_name]:\n", " test_preds[learner_name][slice_name] /= Config.N_FOLDS\n", " \n", " # Evaluate this strategy\n", " learner_name = 'xgb'\n", " \n", " # Weights for ensemble\n", " weights = np.array([\n", " 1.0, # full_data\n", " 1.0, # last_90pct\n", " 1.0, # last_85pct\n", " 1.0, # last_80pct\n", " 0.25, # oldest_25pct\n", " 0.9, # full_data_outlier_adj\n", " 0.9, # last_90pct_outlier_adj\n", " 0.9, # last_85pct_outlier_adj\n", " 0.9, # last_80pct_outlier_adj\n", " 0.2 # oldest_25pct_outlier_adj\n", " ])\n", " weights = weights / weights.sum()\n", " \n", " oof_weighted = pd.DataFrame(oof_preds[learner_name]).values @ weights\n", " test_weighted = pd.DataFrame(test_preds[learner_name]).values @ weights\n", " score_weighted = pearsonr(train_df[Config.LABEL_COLUMN], oof_weighted)[0]\n", " \n", " print(f\"\\n{strategy.upper()} Strategy - Weighted Ensemble Pearson: {score_weighted:.4f}\")\n", " \n", " # Store individual slice scores\n", " slice_names = list(oof_preds[learner_name].keys())\n", " for i, slice_name in enumerate(slice_names):\n", " score = pearsonr(train_df[Config.LABEL_COLUMN], oof_preds[learner_name][slice_name])[0]\n", " strategy_results[strategy][\"slice_scores\"][slice_name] = score\n", " if \"outlier_adj\" in slice_name:\n", " print(f\" {slice_name}: {score:.4f} (weight: {weights[i]:.3f})\")\n", " \n", " strategy_results[strategy][\"oof_scores\"].append(score_weighted)\n", " strategy_results[strategy][\"ensemble_score\"] = score_weighted\n", " strategy_results[strategy][\"oof_preds\"] = oof_weighted\n", " strategy_results[strategy][\"test_preds\"] = test_weighted\n", " \n", " # Track best strategy\n", " if score_weighted > best_score:\n", " best_score = score_weighted\n", " best_strategy = strategy\n", " best_oof_preds = oof_preds\n", " best_test_preds = test_preds\n", " \n", " # Print comparison summary\n", " print(f\"\\n{'='*50}\")\n", " print(\"OUTLIER STRATEGY COMPARISON SUMMARY\")\n", " print(f\"{'='*50}\")\n", " \n", " for strategy in Config.OUTLIER_STRATEGIES:\n", " score = strategy_results[strategy][\"ensemble_score\"]\n", " print(f\"{strategy.upper()}: {score:.4f} {'← BEST' if strategy == best_strategy else ''}\")\n", " \n", " # Analyze differences\n", " print(f\"\\nRelative performance vs 'reduce' strategy:\")\n", " reduce_score = strategy_results[\"reduce\"][\"ensemble_score\"]\n", " for strategy in Config.OUTLIER_STRATEGIES:\n", " if strategy != \"reduce\":\n", " score = strategy_results[strategy][\"ensemble_score\"]\n", " diff = (score - reduce_score) / reduce_score * 100\n", " print(f\" {strategy}: {diff:+.2f}%\")\n", " \n", " return best_oof_preds, best_test_preds, model_slices, strategy_results, best_strategy\n", "\n", "# =========================\n", "# MLP Training (unchanged)\n", "# =========================\n", "def train_mlp(train_df, test_df):\n", " print(\"\\n=== Training MLP Model ===\")\n", " \n", " # Hyperparameters\n", " hparams = {\n", " \"seed\": 42,\n", " \"num_epochs\": 10,\n", " \"batch_size\": 1024 * 8 * 4,\n", " \"learning_rate\": 0.001,\n", " \"weight_decay\": 1e-3,\n", " \"dropout_rate\": 0.6,\n", " \"layers\": [len(Config.MLP_FEATURES), 256, 64, 1],\n", " \"hidden_activation\": None,\n", " \"activation\": \"relu\",\n", " \"delta\": 5,\n", " \"noise_factor\": 0.005\n", " }\n", " \n", " set_seed(hparams[\"seed\"])\n", " \n", " # Prepare data for MLP\n", " X_train_full = train_df[Config.MLP_FEATURES].values\n", " y_train_full = train_df[Config.LABEL_COLUMN].values\n", " \n", " # Split for validation\n", " X_train, X_val, y_train, y_val = train_test_split(\n", " X_train_full, y_train_full, test_size=0.2, shuffle=False, random_state=42\n", " )\n", " \n", " # Scale data\n", " scaler = StandardScaler()\n", " X_train = scaler.fit_transform(X_train)\n", " X_val = scaler.transform(X_val)\n", " X_test = scaler.transform(test_df[Config.MLP_FEATURES].values)\n", " \n", " # Create dataloaders\n", " train_loader = get_dataloaders(X_train, y_train, hparams, device, shuffle=True)\n", " val_loader = get_dataloaders(X_val, y_val, hparams, device, shuffle=False)\n", " test_loader = get_dataloaders(X_test, None, hparams, device, shuffle=False)\n", " \n", " # Initialize model\n", " model = MLP(\n", " layers=hparams[\"layers\"],\n", " dropout_rate=hparams[\"dropout_rate\"],\n", " activation=hparams[\"activation\"],\n", " last_activation=hparams[\"hidden_activation\"],\n", " ).to(device)\n", " \n", " criterion = nn.HuberLoss(delta=hparams[\"delta\"], reduction='sum')\n", " optimizer = optim.Adam(model.parameters(), lr=hparams[\"learning_rate\"], \n", " weight_decay=hparams[\"weight_decay\"])\n", " \n", " checkpointer = Checkpointer(path=\"best_mlp_model.pt\")\n", " \n", " # Training loop\n", " num_epochs = hparams[\"num_epochs\"]\n", " for epoch in range(num_epochs):\n", " model.train()\n", " running_loss = 0.0\n", "\n", " for inputs, targets in tqdm(train_loader, desc=f\"Epoch {epoch+1}/{num_epochs}\"):\n", " inputs, targets = inputs.to(device), targets.to(device)\n", " \n", " # Add noise for robustness\n", " inputs = inputs + torch.randn_like(inputs) * hparams[\"noise_factor\"]\n", " \n", " optimizer.zero_grad()\n", " outputs = model(inputs)\n", " loss = criterion(outputs, targets)\n", " \n", " loss.backward()\n", " optimizer.step()\n", " \n", " running_loss += loss.item() * inputs.size(0)\n", " \n", " running_loss = running_loss / len(train_loader.dataset)\n", " print(f\"Training Loss: {running_loss:.4f}\")\n", "\n", " # Validation phase\n", " model.eval()\n", " val_loss = 0.0\n", " preds = []\n", " trues = []\n", " with torch.no_grad():\n", " for inputs, targets in tqdm(val_loader, desc=\"Validation\"):\n", " inputs, targets = inputs.to(device), targets.to(device)\n", " outputs = model(inputs)\n", " loss = criterion(outputs, targets)\n", " val_loss += loss.item() * inputs.size(0)\n", " preds.append(outputs.cpu().numpy())\n", " trues.append(targets.cpu().numpy())\n", "\n", " val_loss /= len(val_loader.dataset)\n", " preds = np.concatenate(preds).flatten()\n", " trues = np.concatenate(trues).flatten()\n", " pearson_coef = pearsonr(preds, trues)[0]\n", " print(f\"Validation Pearson Coef: {pearson_coef:.4f} | Loss: {val_loss:.4f}\")\n", "\n", " checkpointer(pearson_coef, model)\n", " \n", " # Load best model and make predictions\n", " model = checkpointer.load(model)\n", " model.eval()\n", " predictions = []\n", " with torch.no_grad():\n", " for inputs in tqdm(test_loader, desc=\"Predicting\"):\n", " inputs = inputs[0].to(device)\n", " outputs = model(inputs)\n", " predictions.append(outputs.cpu().numpy())\n", "\n", " predictions = np.concatenate(predictions).flatten()\n", " \n", " return predictions\n", "\n", "# =========================\n", "# Ensemble & Submission Functions\n", "# =========================\n", "def create_xgboost_submission(train_df, oof_preds, test_preds, submission_df, strategy=\"reduce\"):\n", " learner_name = 'xgb'\n", " \n", " # Weights for 10 slices\n", " weights = np.array([\n", " 1.0, # full_data\n", " 1.0, # last_90pct\n", " 1.0, # last_85pct\n", " 1.0, # last_80pct\n", " 0.25, # oldest_25pct\n", " 0.9, # full_data_outlier_adj\n", " 0.9, # last_90pct_outlier_adj\n", " 0.9, # last_85pct_outlier_adj\n", " 0.9, # last_80pct_outlier_adj\n", " 0.2 # oldest_25pct_outlier_adj\n", " ])\n", " \n", " # Normalize weights\n", " weights = weights / weights.sum()\n", "\n", " oof_weighted = pd.DataFrame(oof_preds[learner_name]).values @ weights\n", " test_weighted = pd.DataFrame(test_preds[learner_name]).values @ weights\n", " score_weighted = pearsonr(train_df[Config.LABEL_COLUMN], oof_weighted)[0]\n", " print(f\"\\n{learner_name.upper()} Weighted Ensemble Pearson: {score_weighted:.4f}\")\n", "\n", " # Print individual slice scores and weights for analysis\n", " print(\"\\nIndividual slice OOF scores and weights:\")\n", " slice_names = list(oof_preds[learner_name].keys())\n", " for i, slice_name in enumerate(slice_names):\n", " score = pearsonr(train_df[Config.LABEL_COLUMN], oof_preds[learner_name][slice_name])[0]\n", " print(f\" {slice_name}: {score:.4f} (weight: {weights[i]:.3f})\")\n", "\n", " # Save XGBoost submission\n", " xgb_submission = submission_df.copy()\n", " xgb_submission[\"prediction\"] = test_weighted\n", " xgb_submission.to_csv(f\"submission_xgboost_{strategy}.csv\", index=False)\n", " print(f\"\\nSaved: submission_xgboost_{strategy}.csv\")\n", " \n", " return test_weighted\n", "\n", "def create_ensemble_submission(xgb_predictions, mlp_predictions, submission_df, \n", " xgb_weight=0.9, mlp_weight=0.1, suffix=\"\"):\n", " # Ensemble predictions\n", " ensemble_predictions = (xgb_weight * xgb_predictions + \n", " mlp_weight * mlp_predictions)\n", " \n", " # Save ensemble submission\n", " ensemble_submission = submission_df.copy()\n", " ensemble_submission[\"prediction\"] = ensemble_predictions\n", " filename = f\"submission_ensemble{suffix}.csv\"\n", " ensemble_submission.to_csv(filename, index=False)\n", " print(f\"\\nSaved: {filename} (XGBoost: {xgb_weight*100}%, MLP: {mlp_weight*100}%)\")\n", " \n", " return ensemble_predictions\n", "\n", "# =========================\n", "# Main Execution\n", "# =========================\n", "if __name__ == \"__main__\":\n", " # Load data\n", " train_df, test_df, submission_df = load_data()\n", " \n", " # Analyze outliers\n", " outlier_indices = analyze_outliers(train_df)\n", " \n", " # Train XGBoost with outlier comparison\n", " print(\"\\n=== Training XGBoost Models with Outlier Strategy Comparison ===\")\n", " best_oof_preds, best_test_preds, model_slices, strategy_results, best_strategy = \\\n", " train_xgboost_with_outlier_comparison(train_df, test_df)\n", " \n", " # Create XGBoost submission with best strategy\n", " xgb_predictions = create_xgboost_submission(\n", " train_df, best_oof_preds, best_test_preds, submission_df, strategy=best_strategy\n", " )\n", " \n", " # Train MLP model\n", " mlp_predictions = train_mlp(train_df, test_df)\n", " \n", " # Save MLP submission\n", " mlp_submission = submission_df.copy()\n", " mlp_submission[\"prediction\"] = mlp_predictions\n", " mlp_submission.to_csv(\"submission_mlp.csv\", index=False)\n", " print(\"\\nSaved: submission_mlp.csv\")\n", " \n", " # Create ensemble submission\n", " ensemble_predictions = create_ensemble_submission(\n", " xgb_predictions, mlp_predictions, submission_df,\n", " xgb_weight=0.9, mlp_weight=0.1, suffix=f\"_{best_strategy}\"\n", " )\n", " \n", " # Print final summary\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"FINAL SUMMARY\")\n", " print(\"=\"*60)\n", " print(f\"\\nBest outlier strategy: {best_strategy.upper()}\")\n", " print(f\"Best XGBoost CV score: {strategy_results[best_strategy]['ensemble_score']:.4f}\")\n", " \n", " print(\"\\nStrategy comparison (XGBoost ensemble scores):\")\n", " for strategy in Config.OUTLIER_STRATEGIES:\n", " score = strategy_results[strategy][\"ensemble_score\"]\n", " print(f\" {strategy}: {score:.4f}\")\n", " \n", " print(\"\\nCreated submission files:\")\n", " print(f\"1. submission_xgboost_{best_strategy}.csv - XGBoost with {best_strategy} strategy\")\n", " print(f\"2. submission_mlp.csv - MLP only\")\n", " print(f\"3. submission_ensemble_{best_strategy}.csv - 90% XGBoost + 10% MLP\")\n", " \n", " # Show sample predictions\n", " print(\"\\nSample predictions (first 10 rows):\")\n", " comparison_df = pd.DataFrame({\n", " 'ID': submission_df['ID'][:10],\n", " 'XGBoost': xgb_predictions[:10],\n", " 'MLP': mlp_predictions[:10],\n", " 'Ensemble': ensemble_predictions[:10]\n", " })\n", " print(comparison_df)\n", " \n", " # Provide recommendations\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"RECOMMENDATIONS\")\n", " print(\"=\"*60)\n", " \n", " reduce_score = strategy_results[\"reduce\"][\"ensemble_score\"]\n", " remove_score = strategy_results[\"remove\"][\"ensemble_score\"]\n", " double_score = strategy_results[\"double\"][\"ensemble_score\"]\n", " none_score = strategy_results[\"none\"][\"ensemble_score\"]\n", " \n", " print(\"\\n1. Outlier Handling Impact:\")\n", " if best_strategy == \"reduce\":\n", " print(\" ✓ Current approach (reduce weights) is optimal\")\n", " elif best_strategy == \"remove\":\n", " print(\" ! Removing outliers completely performs better\")\n", " print(\" → This suggests outliers are noise rather than informative extremes\")\n", " elif best_strategy == \"double\":\n", " print(\" ! Doubling outlier weights performs better\")\n", " print(\" → This suggests outliers contain valuable signal for extreme movements\")\n", " else:\n", " print(\" ! No outlier adjustment performs better\")\n", " print(\" → This suggests the model can handle outliers naturally\")\n", " \n", " print(\"\\n2. Overfitting Risk Assessment:\")\n", " if remove_score > reduce_score and remove_score > double_score:\n", " print(\" ⚠ Removing outliers improves CV but may increase overfitting risk\")\n", " print(\" → Consider using reduce strategy for better generalization\")\n", " elif double_score > reduce_score:\n", " print(\" ✓ Emphasizing outliers improves performance\")\n", " print(\" → Model benefits from learning extreme patterns\")\n", " \n", " print(\"\\n3. Next Steps:\")\n", " print(\" • Test different outlier fractions (0.05%, 0.2%, 0.5%)\")\n", " print(\" • Try adaptive outlier detection per time slice\")\n", " print(\" • Consider feature-specific outlier handling\")\n", " print(\" • Monitor LB score vs CV score for overfitting signs\")\n", " \n", " # Additional insights based on outlier analysis\n", " if len(outlier_indices) > 0:\n", " print(f\"\\n4. Outlier Insights:\")\n", " print(f\" • Detected {len(outlier_indices)} outliers ({len(outlier_indices)/len(train_df)*100:.2f}% of data)\")\n", " print(\" • Consider creating synthetic outliers if 'double' strategy works well\")\n", " print(\" • Analyze time distribution of outliers for market regime insights\")" ] } ], "metadata": { "kaggle": { "accelerator": "none", "dataSources": [ { "databundleVersionId": 11418275, "sourceId": 96164, "sourceType": "competition" } ], "isGpuEnabled": false, "isInternetEnabled": true, "language": "python", "sourceType": "notebook" }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.11" }, "papermill": { "default_parameters": {}, "duration": 36715.5898, "end_time": "2025-07-01T04:45:13.424631", "environment_variables": {}, "exception": null, "input_path": "__notebook__.ipynb", "output_path": "__notebook__.ipynb", "parameters": {}, "start_time": "2025-06-30T18:33:17.834831", "version": "2.6.0" } }, "nbformat": 4, "nbformat_minor": 5 }