{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":96164,"databundleVersionId":11418275,"sourceType":"competition"}],"dockerImageVersionId":31040,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import random\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom torch.utils.data import Dataset, DataLoader\nimport torch\nimport torch.nn as nn\nfrom tqdm import tqdm","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-22T12:22:35.461085Z","iopub.execute_input":"2025-05-22T12:22:35.462224Z","iopub.status.idle":"2025-05-22T12:22:35.468045Z","shell.execute_reply.started":"2025-05-22T12:22:35.462137Z","shell.execute_reply":"2025-05-22T12:22:35.466881Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"torch.manual_seed(28)\ntorch.cuda.manual_seed(28)\nnp.random.seed(28)\nrandom.seed(28)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-22T12:22:37.190423Z","iopub.execute_input":"2025-05-22T12:22:37.190809Z","iopub.status.idle":"2025-05-22T12:22:37.203556Z","shell.execute_reply.started":"2025-05-22T12:22:37.190779Z","shell.execute_reply":"2025-05-22T12:22:37.202280Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train = pd.read_parquet('/kaggle/input/drw-crypto-market-prediction/train.parquet')\ntest = pd.read_parquet('/kaggle/input/drw-crypto-market-prediction/test.parquet')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-22T12:22:38.408853Z","iopub.execute_input":"2025-05-22T12:22:38.409257Z","iopub.status.idle":"2025-05-22T12:23:53.124688Z","shell.execute_reply.started":"2025-05-22T12:22:38.409230Z","shell.execute_reply":"2025-05-22T12:23:53.123748Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"features = [col for col in train.columns if col.startswith('X_')] + ['bid_qty', 'ask_qty', 'buy_qty', 'sell_qty', 'volume']\nlabel_col = 'label'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-22T12:23:53.126444Z","iopub.execute_input":"2025-05-22T12:23:53.126756Z","iopub.status.idle":"2025-05-22T12:23:53.132703Z","shell.execute_reply.started":"2025-05-22T12:23:53.126731Z","shell.execute_reply":"2025-05-22T12:23:53.131773Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"scaler = StandardScaler()\ntrain[features] = scaler.fit_transform(train[features])\ntest[features] = scaler.transform(test[features])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-22T12:23:53.133599Z","iopub.execute_input":"2025-05-22T12:23:53.133932Z","iopub.status.idle":"2025-05-22T12:23:53.316280Z","shell.execute_reply.started":"2025-05-22T12:23:53.133908Z","shell.execute_reply":"2025-05-22T12:23:53.315265Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"SEQ_LEN = 60  \n\nclass CryptoDataset(Dataset):\n    def __init__(self, df, seq_len, is_train=True):\n        self.features = df[features].values\n        self.labels = df[label_col].values if is_train else None\n        self.seq_len = seq_len\n        self.is_train = is_train\n\n    def __len__(self):\n        return len(self.features) - self.seq_len\n\n    def __getitem__(self, idx):\n        x = self.features[idx:idx+self.seq_len]\n        if self.is_train:\n            y = self.labels[idx + self.seq_len]\n            return torch.tensor(x, dtype=torch.float32), torch.tensor(y, dtype=torch.float32)\n        return torch.tensor(x, dtype=torch.float32)\n\ntrain_df, val_df = train_test_split(train, test_size=0.1, shuffle=False)\ntrain_dataset = CryptoDataset(train_df, SEQ_LEN, is_train=True)\nval_dataset = CryptoDataset(val_df, SEQ_LEN, is_train=True)\n\ntrain_loader = DataLoader(train_dataset, batch_size=256, shuffle=True)\nval_loader = DataLoader(val_dataset, batch_size=256, shuffle=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-22T12:23:53.318104Z","iopub.execute_input":"2025-05-22T12:23:53.318740Z","iopub.status.idle":"2025-05-22T12:23:58.193107Z","shell.execute_reply.started":"2025-05-22T12:23:53.318710Z","shell.execute_reply":"2025-05-22T12:23:58.192092Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\n\nclass Chomp1d(nn.Module):\n    def __init__(self, chomp_size):\n        super().__init__()\n        self.chomp_size = chomp_size\n\n    def forward(self, x):\n        return x[:, :, :-self.chomp_size]\n\nclass TemporalBlock(nn.Module):\n    def __init__(self, in_channels, out_channels, kernel_size, stride, dilation, padding, dropout):\n        super().__init__()\n        self.conv1 = nn.Conv1d(in_channels, out_channels, kernel_size,\n                               stride=stride, padding=padding, dilation=dilation)\n        self.chomp1 = Chomp1d(padding)\n        self.relu1 = nn.ReLU()\n        self.dropout1 = nn.Dropout(dropout)\n\n        self.conv2 = nn.Conv1d(out_channels, out_channels, kernel_size,\n                               stride=stride, padding=padding, dilation=dilation)\n        self.chomp2 = Chomp1d(padding)\n        self.relu2 = nn.ReLU()\n        self.dropout2 = nn.Dropout(dropout)\n\n        self.net = nn.Sequential(\n            self.conv1, self.chomp1, self.relu1, self.dropout1,\n            self.conv2, self.chomp2, self.relu2, self.dropout2\n        )\n        self.downsample = nn.Conv1d(in_channels, out_channels, 1) if in_channels != out_channels else None\n        self.relu = nn.ReLU()\n\n    def forward(self, x):\n        out = self.net(x)\n        res = x if self.downsample is None else self.downsample(x)\n        return self.relu(out + res)\n\nclass TCN(nn.Module):\n    def __init__(self, input_size, num_channels, kernel_size=2, dropout=0.2):\n        super().__init__()\n        layers = []\n        num_levels = len(num_channels)\n        for i in range(num_levels):\n            dilation_size = 2 ** i\n            in_channels = input_size if i == 0 else num_channels[i - 1]\n            out_channels = num_channels[i]\n            layers += [TemporalBlock(in_channels, out_channels, kernel_size, stride=1,\n                                     dilation=dilation_size, padding=(kernel_size - 1) * dilation_size,\n                                     dropout=dropout)]\n        self.network = nn.Sequential(*layers)\n\n    def forward(self, x):\n        return self.network(x)\n\n# 最終回帰モデル\nclass TCNRegressor(nn.Module):\n    def __init__(self, input_size, hidden_size=64, num_levels=3):\n        super().__init__()\n        self.tcn = TCN(input_size=input_size, num_channels=[hidden_size] * num_levels, kernel_size=3, dropout=0.2)\n        self.linear = nn.Linear(hidden_size, 1)\n\n    def forward(self, x):\n        x = x.transpose(1, 2)  # (B, T, F) -> (B, F, T)\n        y = self.tcn(x)        # (B, hidden_size, T)\n        out = self.linear(y[:, :, -1])  # 最後の時刻の出力を使う\n        return out.squeeze(-1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-22T12:23:58.194246Z","iopub.execute_input":"2025-05-22T12:23:58.194615Z","iopub.status.idle":"2025-05-22T12:23:58.210215Z","shell.execute_reply.started":"2025-05-22T12:23:58.194581Z","shell.execute_reply":"2025-05-22T12:23:58.208876Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def train_model(model, train_loader, val_loader, criterion, optimizer, scheduler, device, epochs=10, patience=5):\n    class EarlyStopping:\n        def __init__(self, patience=patience, delta=1e-4):\n            self.patience = patience\n            self.counter = 0\n            self.best_loss = None\n            self.early_stop = False\n            self.delta = delta\n            self.best_model_state = None\n\n        def __call__(self, val_loss, model):\n            if self.best_loss is None or val_loss < self.best_loss - self.delta:\n                self.best_loss = val_loss\n                self.counter = 0\n                self.best_model_state = model.state_dict()\n            else:\n                self.counter += 1\n                if self.counter >= self.patience:\n                    self.early_stop = True\n\n    def evaluate(model, dataloader, device):\n        model.eval()\n        losses = []\n        all_preds = []\n        all_targets = []\n        with torch.no_grad():\n            for x_batch, y_batch in dataloader:\n                x_batch, y_batch = x_batch.to(device), y_batch.to(device)\n                preds = model(x_batch)\n                loss = criterion(preds, y_batch)\n                losses.append(loss.item())\n                all_preds.extend(preds.cpu().numpy())\n                all_targets.extend(y_batch.cpu().numpy())\n        avg_loss = np.mean(losses)\n        try:\n            from scipy.stats import pearsonr\n            corr = pearsonr(all_preds, all_targets)[0]\n        except:\n            corr = 0.0\n        return avg_loss, corr\n\n    early_stopping = EarlyStopping()\n    \n    history = {\n        \"train_loss\": [],\n        \"val_loss\": [],\n        \"val_corr\": [],\n        \"lr\": []\n    }\n    \n    for epoch in range(epochs):\n        model.train()\n        total_loss = 0\n        loop = tqdm(train_loader, desc=f\"Epoch {epoch+1}/{epochs}\")\n        for x_batch, y_batch in loop:\n            x_batch, y_batch = x_batch.to(device), y_batch.to(device)\n\n            optimizer.zero_grad()\n            preds = model(x_batch)\n            loss = criterion(preds, y_batch)\n            loss.backward()\n            optimizer.step()\n\n            total_loss += loss.item()\n            loop.set_postfix(loss=loss.item())\n        \n        train_loss = total_loss / len(train_loader)\n        val_loss, val_corr = evaluate(model, val_loader, device)\n        scheduler.step(val_loss)\n\n        history[\"train_loss\"].append(train_loss)\n        history[\"val_loss\"].append(val_loss)\n        history[\"val_corr\"].append(val_corr)\n        history[\"lr\"].append(optimizer.param_groups[0]['lr'])\n\n        print(f\"Epoch {epoch+1} | Train Loss: {train_loss:.5f} | Val Loss: {val_loss:.5f} | Val Corr: {val_corr:.4f} | LR: {history['lr'][-1]:.6f}\")\n\n        early_stopping(val_loss, model)\n        #if early_stopping.early_stop:\n        #    print(\"Early stopping triggered.\")\n        #    break\n\n    model.load_state_dict(early_stopping.best_model_state)\n\n    fig, ax1 = plt.subplots(figsize=(10,6))\n    ax1.set_xlabel('Epoch')\n    ax1.set_ylabel('Loss', color='tab:blue')\n    ax1.plot(history[\"train_loss\"], label='Train Loss', color='tab:blue', linestyle='-')\n    ax1.plot(history[\"val_loss\"], label='Val Loss', color='tab:blue', linestyle='--')\n    ax1.tick_params(axis='y', labelcolor='tab:blue')\n    ax1.legend(loc='upper left')\n\n    ax2 = ax1.twinx()  \n    ax2.set_ylabel('Learning Rate / Val Corr', color='tab:orange')\n    ax2.plot(history[\"lr\"], label='Learning Rate', color='tab:orange', linestyle='-.')\n    ax2.plot(history[\"val_corr\"], label='Val Corr', color='tab:green', linestyle=':')\n    ax2.tick_params(axis='y', labelcolor='tab:orange')\n    ax2.legend(loc='upper right')\n\n    plt.title('Training Metrics and Learning Rate')\n    plt.show()\n\n    return model, history","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-22T12:23:58.211246Z","iopub.execute_input":"2025-05-22T12:23:58.211657Z","iopub.status.idle":"2025-05-22T12:23:58.243439Z","shell.execute_reply.started":"2025-05-22T12:23:58.211618Z","shell.execute_reply":"2025-05-22T12:23:58.242314Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel = TCNRegressor(input_size=len(features)).to(device)\n\ncriterion = nn.MSELoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\nscheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', patience=2, factor=0.5, verbose=True)\n\ntrained_model, history = train_model(model, train_loader, val_loader, criterion, optimizer, scheduler, device, epochs=50, patience=3)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-22T12:23:58.244695Z","iopub.execute_input":"2025-05-22T12:23:58.245071Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_dataset = CryptoDataset(test, SEQ_LEN, is_train=False)\ntest_loader = DataLoader(test_dataset, batch_size=256, shuffle=False)\n\nmodel.eval()\npreds = []\n\nwith torch.no_grad():\n    for x_batch in tqdm(test_loader, desc=\"Predicting\"):\n        x_batch = x_batch.to(device)\n        outputs = model(x_batch)\n        preds.extend(outputs.cpu().numpy())\n\nsample_submission = pd.read_csv('/kaggle/input/drw-crypto-market-prediction/sample_submission.csv')\nsample_submission['prediction'] = [0]*SEQ_LEN + preds  \nsample_submission.to_csv('submission.csv', index=False)\nprint(sample_submission.tail())","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}