{"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":102335,"databundleVersionId":12518947,"sourceType":"competition"}],"dockerImageVersionId":31040,"isInternetEnabled":false,"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-07-06T20:51:19.726404Z","iopub.execute_input":"2025-07-06T20:51:19.726708Z","iopub.status.idle":"2025-07-06T20:51:19.736215Z","shell.execute_reply.started":"2025-07-06T20:51:19.726686Z","shell.execute_reply":"2025-07-06T20:51:19.735083Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#  Imports\nimport pandas as pd\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# 🛠 Config\npd.set_option('display.max_columns', 100)\nsns.set(style=\"whitegrid\")\n\n#  File paths\nBASE_DIR = '/kaggle/input/cmi-detect-behavior-with-sensor-data'\n\ntrain = pd.read_csv(f'{BASE_DIR}/train.csv')\ntest = pd.read_csv(f'{BASE_DIR}/test.csv')\ntrain_demo = pd.read_csv(f'{BASE_DIR}/train_demographics.csv')\ntest_demo = pd.read_csv(f'{BASE_DIR}/test_demographics.csv')\n\n# 🔍 Preview\nprint(\"Train shape:\", train.shape)\nprint(\"Test shape:\", test.shape)\nprint(\"Train Demographics:\", train_demo.shape)\nprint(\"Test Demographics:\", test_demo.shape)\n\ndisplay(train.head())\ndisplay(train_demo.head())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-06T20:51:19.738173Z","iopub.execute_input":"2025-07-06T20:51:19.738663Z","iopub.status.idle":"2025-07-06T20:51:44.527640Z","shell.execute_reply.started":"2025-07-06T20:51:19.738632Z","shell.execute_reply":"2025-07-06T20:51:44.525602Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**EDA & Feature Engineering**","metadata":{}},{"cell_type":"code","source":"\nseqs = train['sequence_id'].unique()\nprint(\"Unique sequences:\", len(seqs))\n\n# Evisualize acc_x of one sequence\nsample_seq = train[train['sequence_id'] == seqs[0]]\nsample_seq[['acc_x', 'acc_y', 'acc_z']].plot(figsize=(12, 4), title='Acceleration over time')\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-06T20:51:44.532393Z","iopub.execute_input":"2025-07-06T20:51:44.532793Z","iopub.status.idle":"2025-07-06T20:51:45.315723Z","shell.execute_reply.started":"2025-07-06T20:51:44.532759Z","shell.execute_reply":"2025-07-06T20:51:45.313461Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Feature Extraction (per sequence)**","metadata":{}},{"cell_type":"code","source":"\ndef extract_features(df):\n    feats = []\n    for seq_id, seq_df in df.groupby('sequence_id'):\n        feat = {'sequence_id': seq_id, 'subject': seq_df['subject'].iloc[0]}\n        \n        # IMU features\n        for col in ['acc_x', 'acc_y', 'acc_z', 'rot_w', 'rot_x', 'rot_y', 'rot_z']:\n            feat[f'{col}_mean'] = seq_df[col].mean()\n            feat[f'{col}_std'] = seq_df[col].std()\n            feat[f'{col}_min'] = seq_df[col].min()\n            feat[f'{col}_max'] = seq_df[col].max()\n        \n        feats.append(feat)\n    \n    return pd.DataFrame(feats)\n\ntrain_feats = extract_features(train)\ntest_feats = extract_features(test)\n\n# Merge with demographics\ntrain_feats = train_feats.merge(train_demo, on='subject', how='left')\ntest_feats = test_feats.merge(test_demo, on='subject', how='left')\n\n# Merge label\ntarget_df = train[['sequence_id', 'gesture']].drop_duplicates()\ntrain_feats = train_feats.merge(target_df, on='sequence_id', how='left')\n\ndisplay(train_feats.head())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-06T20:51:45.316992Z","iopub.execute_input":"2025-07-06T20:51:45.317386Z","iopub.status.idle":"2025-07-06T20:51:54.719323Z","shell.execute_reply.started":"2025-07-06T20:51:45.317355Z","shell.execute_reply":"2025-07-06T20:51:54.718073Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom lightgbm import LGBMClassifier\n\n# Preprocessing\nX = train_feats.drop(columns=['sequence_id', 'subject', 'gesture'])\ny = train_feats['gesture']\n\n# train/test split\nX_train, X_val, y_train, y_val = train_test_split(X, y, stratify=y, test_size=0.2, random_state=42)\n\n#  Train model\nclf = LGBMClassifier()\nclf.fit(X_train, y_train)\n\n#  Evaluate\ny_pred = clf.predict(X_val)\nprint(classification_report(y_val, y_pred))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-06T20:51:54.721748Z","iopub.execute_input":"2025-07-06T20:51:54.722120Z","iopub.status.idle":"2025-07-06T20:52:01.773246Z","shell.execute_reply.started":"2025-07-06T20:51:54.722082Z","shell.execute_reply":"2025-07-06T20:52:01.772115Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Submission ","metadata":{}},{"cell_type":"code","source":"\nX_test = test_feats.drop(columns=['sequence_id', 'subject'])\n\n\nX_test = X_test[X_train.columns]\n\n# Predict\ntest_feats['gesture'] = clf.predict(X_test)\n\n# Only keep required columns\nsubmission = test_feats[['sequence_id', 'gesture']]\n\n# Save as parquet file for Kaggle submission\nsubmission.to_parquet(\"submission.parquet\", index=False)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-06T20:52:07.895399Z","iopub.execute_input":"2025-07-06T20:52:07.895747Z","iopub.status.idle":"2025-07-06T20:52:07.909427Z","shell.execute_reply.started":"2025-07-06T20:52:07.895724Z","shell.execute_reply":"2025-07-06T20:52:07.908278Z"}},"outputs":[],"execution_count":null}]}