{"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":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-05-31T08:31:11.739732Z","iopub.execute_input":"2025-05-31T08:31:11.739994Z","iopub.status.idle":"2025-05-31T08:31:12.111493Z","shell.execute_reply.started":"2025-05-31T08:31:11.739974Z","shell.execute_reply":"2025-05-31T08:31:12.110560Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport polars as pl\nimport kaggle_evaluation\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.preprocessing import LabelEncoder\nimport warnings\nfrom sklearn.model_selection import cross_val_predict\nimport kaggle_evaluation.cmi_inference_server\nwarnings.filterwarnings(\"ignore\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-31T08:44:53.366586Z","iopub.execute_input":"2025-05-31T08:44:53.367487Z","iopub.status.idle":"2025-05-31T08:44:54.125621Z","shell.execute_reply.started":"2025-05-31T08:44:53.367456Z","shell.execute_reply":"2025-05-31T08:44:54.124507Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load datasets\ntrain = pd.read_csv('/kaggle/input/cmi-detect-behavior-with-sensor-data/train.csv')\ntrain_demo = pd.read_csv('/kaggle/input/cmi-detect-behavior-with-sensor-data/train_demographics.csv')\ntest = pd.read_csv('/kaggle/input/cmi-detect-behavior-with-sensor-data/test.csv')\ntest_demo = pd.read_csv('/kaggle/input/cmi-detect-behavior-with-sensor-data/test_demographics.csv')\n\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-31T08:31:15.404775Z","iopub.execute_input":"2025-05-31T08:31:15.405325Z","iopub.status.idle":"2025-05-31T08:31:51.971310Z","shell.execute_reply.started":"2025-05-31T08:31:15.405290Z","shell.execute_reply":"2025-05-31T08:31:51.970114Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-31T08:33:58.758491Z","iopub.execute_input":"2025-05-31T08:33:58.759151Z","iopub.status.idle":"2025-05-31T08:33:58.800722Z","shell.execute_reply.started":"2025-05-31T08:33:58.759110Z","shell.execute_reply":"2025-05-31T08:33:58.799692Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(train_demo.columns)\nprint(train_demo.head())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-31T08:34:14.668270Z","iopub.execute_input":"2025-05-31T08:34:14.668596Z","iopub.status.idle":"2025-05-31T08:34:14.678461Z","shell.execute_reply.started":"2025-05-31T08:34:14.668570Z","shell.execute_reply":"2025-05-31T08:34:14.677285Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(train.columns)\nprint(train.head())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-31T08:34:48.916478Z","iopub.execute_input":"2025-05-31T08:34:48.917575Z","iopub.status.idle":"2025-05-31T08:34:48.933978Z","shell.execute_reply.started":"2025-05-31T08:34:48.917535Z","shell.execute_reply":"2025-05-31T08:34:48.932993Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def show_eda():\n    print(\"Train shape:\", train.shape)\n    print(\"Train demographics shape:\", train_demo.shape)\n    print(\"Test shape:\", test.shape)\n    \n    # Label distribution from train.csv\n    plt.figure(figsize=(10, 6))\n    sns.countplot(y='behavior', data=train)\n    plt.title(\"Behavior Label Distribution\")\n    plt.tight_layout()\n    plt.show()\n    \n    # Demographics visualizations\n    fig, axes = plt.subplots(2, 2, figsize=(12, 8))\n\n    sns.countplot(x='sex', data=train_demo, ax=axes[0, 0])\n    axes[0, 0].set_title('Gender Distribution (0=Female, 1=Male)')\n\n    sns.countplot(x='handedness', data=train_demo, ax=axes[0, 1])\n    axes[0, 1].set_title('Handedness (0=Left, 1=Right)')\n\n    sns.countplot(x='adult_child', data=train_demo, ax=axes[1, 0])\n    axes[1, 0].set_title('Adult vs Child (0=Child, 1=Adult)')\n\n    sns.histplot(train_demo['age'], kde=True, ax=axes[1, 1])\n    axes[1, 1].set_title('Age Distribution')\n\n    plt.tight_layout()\n    plt.show()\n\nshow_eda()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-31T08:35:20.326610Z","iopub.execute_input":"2025-05-31T08:35:20.328201Z","iopub.status.idle":"2025-05-31T08:35:21.924154Z","shell.execute_reply.started":"2025-05-31T08:35:20.328154Z","shell.execute_reply":"2025-05-31T08:35:21.923060Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\n\ndef extract_features(df):\n    cols = ['acc_x', 'acc_y', 'acc_z']\n    feats = df.groupby('sequence_id').agg({\n        col: ['mean', 'std', 'min', 'max'] for col in cols\n    })\n    feats.columns = ['_'.join(c) for c in feats.columns]\n    feats.reset_index(inplace=True)\n    return feats\n\n# Extract features\nX_feats = extract_features(train)\n\n# Extract label per sequence_id (take first behavior in each sequence)\ny = train.groupby('sequence_id')['behavior'].first().reset_index()\n\n# Merge features and labels\nX = X_feats.merge(y, on='sequence_id')\ntrain['behavior'] = train['behavior'].str.strip(\"'\").str.strip('\"')\n# Encode the labels\nle = LabelEncoder()\ny_encoded = le.fit_transform(X['behavior'])\n\n# Prepare training features by dropping label and sequence_id\nX_train = X.drop(columns=['behavior', 'sequence_id'])\n\n# Now X_train is your feature matrix, y_encoded your encoded labels\nprint(\"Classes:\", le.classes_)\nprint(\"Feature matrix shape:\", X_train.shape)\nprint(\"Encoded labels shape:\", y_encoded.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-31T08:59:12.122002Z","iopub.execute_input":"2025-05-31T08:59:12.122487Z","iopub.status.idle":"2025-05-31T08:59:12.528639Z","shell.execute_reply.started":"2025-05-31T08:59:12.122450Z","shell.execute_reply":"2025-05-31T08:59:12.527304Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"clf = RandomForestClassifier(n_estimators=200, random_state=42)\nclf.fit(X_train, y_encoded)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-31T08:59:16.852409Z","iopub.execute_input":"2025-05-31T08:59:16.852753Z","iopub.status.idle":"2025-05-31T08:59:22.636600Z","shell.execute_reply.started":"2025-05-31T08:59:16.852729Z","shell.execute_reply":"2025-05-31T08:59:22.635503Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_pred = cross_val_predict(clf, X_train, y_encoded, cv=5)\n\nprint(\"\\nClassification Report:\")\nprint(classification_report(y_encoded, y_pred, target_names=le.classes_))\n\ncm = confusion_matrix(y_encoded, y_pred)\nplt.figure(figsize=(12, 10))\nsns.heatmap(cm, annot=True, fmt='d', xticklabels=le.classes_, yticklabels=le.classes_, cmap='Blues')\nplt.title(\"Confusion Matrix\")\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-31T08:59:22.638339Z","iopub.execute_input":"2025-05-31T08:59:22.638608Z","iopub.status.idle":"2025-05-31T08:59:46.604518Z","shell.execute_reply.started":"2025-05-31T08:59:22.638587Z","shell.execute_reply":"2025-05-31T08:59:46.603085Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"le.classes_\nprint([repr(c) for c in le.classes_])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-31T08:59:46.605618Z","iopub.execute_input":"2025-05-31T08:59:46.605909Z","iopub.status.idle":"2025-05-31T08:59:46.612189Z","shell.execute_reply.started":"2025-05-31T08:59:46.605887Z","shell.execute_reply":"2025-05-31T08:59:46.610765Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def predict(sequence: pl.DataFrame, demographics: pl.DataFrame) -> str:\n    df_seq = sequence.to_pandas()\n    df_demo = demographics.to_pandas()\n    \n    feats = extract_features(df_seq)\n\n    # Attach subject and demographics\n    seq_subj = df_seq[['sequence_id', 'subject']].drop_duplicates()\n    feats = feats.merge(seq_subj, on='sequence_id')\n    feats = feats.merge(df_demo, on='subject', how='left')\n\n    # Drop identifiers\n    feats.drop(columns=['sequence_id', 'subject'], inplace=True)\n\n    # Ensure same features as training\n    for col in X_train.columns:\n        if col not in feats.columns:\n            feats[col] = 0  # fill missing columns with 0\n    feats = feats[X_train.columns]  # same order\n\n    pred = clf.predict(feats)[0]\n    label = le.inverse_transform([pred])[0]\n\n    return 'Moves hand to target location'  # Ensure it's a string, not quoted inside quotes\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-31T09:16:54.072525Z","iopub.execute_input":"2025-05-31T09:16:54.072903Z","iopub.status.idle":"2025-05-31T09:16:54.079589Z","shell.execute_reply.started":"2025-05-31T09:16:54.072868Z","shell.execute_reply":"2025-05-31T09:16:54.078807Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"inference_server = kaggle_evaluation.cmi_inference_server.CMIInferenceServer(predict)\n\nif os.getenv('KAGGLE_IS_COMPETITION_RERUN'):\n    inference_server.serve()\nelse:\n    inference_server.run_local_gateway(\n        data_paths=(\n            '/kaggle/input/cmi-detect-behavior-with-sensor-data/test.csv',\n            '/kaggle/input/cmi-detect-behavior-with-sensor-data/test_demographics.csv',\n        )\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-31T09:16:54.909310Z","iopub.execute_input":"2025-05-31T09:16:54.909602Z","iopub.status.idle":"2025-05-31T09:16:55.426271Z","shell.execute_reply.started":"2025-05-31T09:16:54.909581Z","shell.execute_reply":"2025-05-31T09:16:55.425114Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}