{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","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,"isSourceIdPinned":false,"sourceType":"competition"},{"sourceId":12468499,"sourceType":"datasetVersion","datasetId":7866083}],"dockerImageVersionId":31089,"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},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import f1_score\n\n# 1. Load Data\ntrain = pd.read_csv('/kaggle/input/cmi-detect-behavior-with-sensor-data/train.csv')\ntest = pd.read_csv('/kaggle/input/cmi-detect-behavior-with-sensor-data/test.csv')\ntrain_demo = pd.read_csv('/kaggle/input/cmi-detect-behavior-with-sensor-data/train_demographics.csv')\ntest_demo = pd.read_csv('/kaggle/input/cmi-detect-behavior-with-sensor-data/test_demographics.csv')\n\n# 2. Merge Demographics\ntrain = train.merge(train_demo, on='subject', how='left')\ntest = test.merge(test_demo, on='subject', how='left')\n\n# 3. Aggregate Features for Each Sequence\n# We'll aggregate per sequence_id (basic statistics over time)\nsensor_cols = [col for col in train.columns if (\n    col.startswith('acc_') or col.startswith('rot_') or col.startswith('thm_') or col.startswith('tof_'))]\nagg_funcs = ['mean', 'std', 'min', 'max']\ntrain_agg = train.groupby('sequence_id')[sensor_cols].agg(agg_funcs)\ntrain_agg.columns = ['_'.join(col) for col in train_agg.columns]\ntrain_agg.reset_index(inplace=True)\ntrain_meta = train.groupby('sequence_id')[['gesture', 'sequence_type', 'subject', 'orientation']].first().reset_index()\ntrain_agg = train_agg.merge(train_meta, on='sequence_id', how='left')\n\ntest_agg = test.groupby('sequence_id')[sensor_cols].agg(agg_funcs)\ntest_agg.columns = ['_'.join(col) for col in test_agg.columns]\ntest_agg.reset_index(inplace=True)\ntest_meta = test.groupby('sequence_id')[['subject']].first().reset_index()\ntest_agg = test_agg.merge(test_meta, on='sequence_id', how='left')\n\n# Merge demographics for aggregated test/train\ntrain_agg = train_agg.merge(train_demo, on='subject', how='left')\ntest_agg = test_agg.merge(test_demo, on='subject', how='left')\n\n# 4. Encode Target and Features\ngesture_le = LabelEncoder()\ntrain_agg['gesture_enc'] = gesture_le.fit_transform(train_agg['gesture'])\n\n# 5. Train Classifier\nfeatures = [col for col in train_agg.columns if col not in [\n    'sequence_id', 'gesture', 'gesture_enc', 'sequence_type', 'subject', 'orientation']]\n\nX_train = train_agg[features].fillna(-1)  # Fill missing with -1 (could be improved)\ny_train = train_agg['gesture_enc']\nX_test = test_agg[features].fillna(-1)\n\nclf = RandomForestClassifier(n_estimators=200, max_depth=10, random_state=42)\nclf.fit(X_train, y_train)\n\n# 6. Predict\ntest_preds = clf.predict(X_test)\ntest_agg['gesture_pred'] = gesture_le.inverse_transform(test_preds)\n\n# 7. Create Submission\nsubmission = pd.DataFrame({\n    'sequence_id': test_agg['sequence_id'],\n    'gesture': test_agg['gesture_pred']\n})\nsubmission.to_csv('submission.csv', index=False)\nprint(submission.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-24T22:31:16.493242Z","iopub.execute_input":"2025-07-24T22:31:16.493577Z","iopub.status.idle":"2025-07-24T22:32:35.038239Z","shell.execute_reply.started":"2025-07-24T22:31:16.493546Z","shell.execute_reply":"2025-07-24T22:32:35.037290Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}