{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":102335,"databundleVersionId":12518947,"sourceType":"competition"}],"dockerImageVersionId":31234,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","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\nimport numpy as np # linear algebra\nimport 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\nimport os\nfor 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-12-17T16:34:10.140847Z","iopub.execute_input":"2025-12-17T16:34:10.143809Z","iopub.status.idle":"2025-12-17T16:34:10.164297Z","shell.execute_reply.started":"2025-12-17T16:34:10.143659Z","shell.execute_reply":"2025-12-17T16:34:10.162453Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\n\nclass ToFAutoencoder(nn.Module):\n    def __init__(self, input_dim, latent_dim=8, hidden_dim=128):\n        super().__init__()\n\n        # Encoder\n        self.encoder = nn.Sequential(\n            nn.Linear(input_dim, hidden_dim),\n            nn.ReLU(),\n\n            nn.Linear(hidden_dim, hidden_dim // 2),\n            nn.ReLU(),\n\n            nn.Linear(hidden_dim // 2, latent_dim)\n        )\n\n        # Decoder\n        self.decoder = nn.Sequential(\n            nn.Linear(latent_dim, hidden_dim // 2),\n            nn.ReLU(),\n\n            nn.Linear(hidden_dim // 2, hidden_dim),\n            nn.ReLU(),\n\n            nn.Linear(hidden_dim, input_dim),\n            nn.Tanh()\n        )\n\n    def forward(self, x):\n        latent = self.encoder(x)\n        reconstruction = self.decoder(latent)\n        return reconstruction, latent\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-17T16:34:10.166545Z","iopub.execute_input":"2025-12-17T16:34:10.166980Z","iopub.status.idle":"2025-12-17T16:34:10.189103Z","shell.execute_reply.started":"2025-12-17T16:34:10.166938Z","shell.execute_reply":"2025-12-17T16:34:10.187981Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\n\nDATA_DIR = \"/kaggle/input/cmi-detect-behavior-with-sensor-data\"\ntrain_df = pd.read_csv(f\"{DATA_DIR}/train.csv\")\ntof_cols = [c for c in train_df.columns if c.startswith(\"tof\")]\ntof_data = train_df[tof_cols]\n\nX = tof_data.values.astype(np.float32)\n\n# Optionally normalize\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX = scaler.fit_transform(X)\nX = np.nan_to_num(X, nan=0.0, posinf=0.0, neginf=0.0)\n\n# Convert to PyTorch tensor\nX_tensor = torch.from_numpy(X)\n\nfrom torch.utils.data import TensorDataset, DataLoader\n\ndataset = TensorDataset(X_tensor)\nloader = DataLoader(dataset, batch_size=128, shuffle=True)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-17T16:34:10.190991Z","iopub.execute_input":"2025-12-17T16:34:10.191355Z","iopub.status.idle":"2025-12-17T16:34:43.631172Z","shell.execute_reply.started":"2025-12-17T16:34:10.191324Z","shell.execute_reply":"2025-12-17T16:34:43.629799Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nmodel = ToFAutoencoder(input_dim=X.shape[1], latent_dim=8).to(device)\n\ncriterion = nn.MSELoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=1e-5)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-17T16:34:43.632833Z","iopub.execute_input":"2025-12-17T16:34:43.633622Z","iopub.status.idle":"2025-12-17T16:34:43.648314Z","shell.execute_reply.started":"2025-12-17T16:34:43.633587Z","shell.execute_reply":"2025-12-17T16:34:43.646812Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"EPOCHS = 30\n\nfor epoch in range(EPOCHS):\n    model.train()\n    total_loss = 0\n\n    for batch in loader:\n        x = batch[0].to(device)\n\n        reconstruction, latent = model(x)\n\n        loss = criterion(reconstruction, x)\n\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n        \n        if torch.isnan(loss):\n            print(\"NaN detected in loss!\")\n            print(\"Batch min:\", x.min().item())\n            print(\"Batch max:\", x.max().item())\n            print(\"Reconstruction min:\", reconstruction.min().item())\n            print(\"Reconstruction max:\", reconstruction.max().item())\n            break\n\n        total_loss += loss.item()\n\n    print(f\"Epoch {epoch+1}/{EPOCHS}, Loss: {total_loss / len(loader):.6f}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-17T16:34:43.650567Z","iopub.execute_input":"2025-12-17T16:34:43.651093Z","iopub.status.idle":"2025-12-17T16:46:41.310053Z","shell.execute_reply.started":"2025-12-17T16:34:43.650925Z","shell.execute_reply":"2025-12-17T16:46:41.308965Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.eval()\nwith torch.no_grad():\n    reconstruction, latent = model(X_tensor.to(device))\n\nlatent = latent.cpu().numpy()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-17T16:46:41.311891Z","iopub.execute_input":"2025-12-17T16:46:41.312968Z","iopub.status.idle":"2025-12-17T16:46:44.765560Z","shell.execute_reply.started":"2025-12-17T16:46:41.312915Z","shell.execute_reply":"2025-12-17T16:46:44.764438Z"}},"outputs":[],"execution_count":null}]}