{"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":"gpu","dataSources":[{"sourceId":102335,"databundleVersionId":12518947,"sourceType":"competition"},{"sourceId":242954653,"sourceType":"kernelVersion"}],"dockerImageVersionId":31041,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import accuracy_score\nfrom xgboost import XGBClassifier\nfrom scipy import stats\nimport polars as pl\nimport cupy as cp","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-26T01:14:20.610874Z","iopub.execute_input":"2025-06-26T01:14:20.611145Z","iopub.status.idle":"2025-06-26T01:14:22.052896Z","shell.execute_reply.started":"2025-06-26T01:14:20.611122Z","shell.execute_reply":"2025-06-26T01:14:22.052056Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data = pd.read_csv(\"/kaggle/input/cmi-detect-behavior-with-sensor-data/train.csv\")\n\nsensor_cols = [col for col in data.columns if col.startswith('acc_') or col.startswith('tof_') or col.startswith(\"rot_\")]\ndf = data.dropna(subset=sensor_cols).copy()\n\nle = LabelEncoder()\ndf['gesture_enc'] = le.fit_transform(df['gesture'])\n\nX_gpu = cp.asarray(df[sensor_cols])\ny_gpu = cp.asarray(df[\"gesture_enc\"])\n\nX_train, X_test, y_train, y_test = train_test_split(\n    X_gpu, y_gpu, test_size=0.1, random_state=42, shuffle = False\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-26T01:17:14.987698Z","iopub.execute_input":"2025-06-26T01:17:14.988236Z","iopub.status.idle":"2025-06-26T01:17:37.138611Z","shell.execute_reply.started":"2025-06-26T01:17:14.988210Z","shell.execute_reply":"2025-06-26T01:17:37.137755Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = XGBClassifier(\n    objective='multi:softmax',\n    n_estimators=2000,\n    early_stopping_rounds=10,\n    eta = 0.1,\n    gamma = 2,\n    max_depth = 15, \n    eval_metric=\"mlogloss\",\n    tree_method='hist', device='cuda',\n    use_label_encoder=False\n)\n\nmodel.fit(X_train, y_train, eval_set=[(X_test, y_test)], verbose=50)\ny_pred = model.predict(X_test)\nprint(accuracy_score(y_test.get(), y_pred))\nnp.save('gesture_classes.npy', le.classes_)\nmodel.save_model(\"xgb_model.json\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-26T01:17:37.139999Z","iopub.execute_input":"2025-06-26T01:17:37.140642Z","iopub.status.idle":"2025-06-26T01:19:29.432060Z","shell.execute_reply.started":"2025-06-26T01:17:37.140610Z","shell.execute_reply":"2025-06-26T01:19:29.431189Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from cmi_2025_metric_copy_for_import import CompetitionMetric\n\n# Get predicted labels for the validation set\nprint(\"Predicting on validation set...\")\ny_val_pred = model.predict(X_test)\ny_val_true = y_test.get()\n\n# Map integer labels back to gesture strings\ngesture_classes = np.load(\"gesture_classes.npy\", allow_pickle=True)\nval_pred_labels = pd.Series(y_val_pred).map(lambda i: gesture_classes[i])\nval_true_labels = pd.Series(y_val_true).map(lambda i: gesture_classes[i])\n\n# Build DataFrames for the metric\nval_submission = pd.DataFrame({'gesture': val_pred_labels})\nval_solution = pd.DataFrame({'gesture': val_true_labels})\n\n# Run competition metric\nmetric = CompetitionMetric()\nscore = metric.calculate_hierarchical_f1(val_solution, val_submission)\nprint(f\"Estimated leaderboard (val) score: {score:.4f}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-26T01:19:50.110047Z","iopub.execute_input":"2025-06-26T01:19:50.110710Z","iopub.status.idle":"2025-06-26T01:19:51.370940Z","shell.execute_reply.started":"2025-06-26T01:19:50.110680Z","shell.execute_reply":"2025-06-26T01:19:51.370212Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nimport pandas as pd\nimport polars as pl\n\nimport kaggle_evaluation.cmi_inference_server","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-06-25T23:00:16.766658Z","iopub.execute_input":"2025-06-25T23:00:16.766865Z","iopub.status.idle":"2025-06-25T23:00:17.126184Z","shell.execute_reply.started":"2025-06-25T23:00:16.766850Z","shell.execute_reply":"2025-06-25T23:00:17.125620Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"The evaluation API requires that you set up a server which will respond to inference requests. We have already defined the server; you just need write the predict function. When we evaluate your submission on the hidden test set the client defined in the gateway will run in a different container with direct access to the hidden test set and hand off the one sequence at a time.\n\nYour code will always have access to the published copies of the files.","metadata":{"execution":{"iopub.status.busy":"2025-05-29T22:29:18.955791Z","iopub.execute_input":"2025-05-29T22:29:18.956193Z","iopub.status.idle":"2025-05-29T22:29:18.965179Z","shell.execute_reply.started":"2025-05-29T22:29:18.956169Z","shell.execute_reply":"2025-05-29T22:29:18.963797Z"}}},{"cell_type":"code","source":"def predict(sequence: pl.DataFrame, demographics: pl.DataFrame) -> str:\n    try:\n        model.load_model(\"xgb_model.json\")\n        gesture_classes = np.load(\"gesture_classes.npy\", allow_pickle=True)\n        \n        le = LabelEncoder()\n        le.classes_ = gesture_classes\n\n        df_seq = sequence.to_pandas()\n        df_seq = df_seq.fillna(0)\n        \n        cols = [col for col in data.columns if col.startswith('acc_') or col.startswith('tof_') or col.startswith(\"rot_\")]\n        y_pred = model.predict(df_seq[cols])\n        pred = stats.mode(y_pred)\n\n        return str(gesture_classes[pred[0]])\n    except Exception:\n        return \"no no no\"\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-25T23:00:17.127591Z","iopub.execute_input":"2025-06-25T23:00:17.127929Z","iopub.status.idle":"2025-06-25T23:00:17.133130Z","shell.execute_reply.started":"2025-06-25T23:00:17.127910Z","shell.execute_reply":"2025-06-25T23:00:17.132300Z"}},"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-06-25T23:00:17.133922Z","iopub.execute_input":"2025-06-25T23:00:17.134147Z","iopub.status.idle":"2025-06-25T23:00:19.335331Z","shell.execute_reply.started":"2025-06-25T23:00:17.134131Z","shell.execute_reply":"2025-06-25T23:00:19.334609Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if not os.getenv('KAGGLE_IS_COMPETITION_RERUN'):\n    print(\"\\nRunning manual test...\")\n    test_df = pd.read_csv('/kaggle/input/cmi-detect-behavior-with-sensor-data/test.csv')\n    sample_seq_id = test_df['sequence_id'].unique()[0]\n    test_seq = test_df[test_df['sequence_id'] == sample_seq_id]\n    prediction = predict(pl.DataFrame(test_seq), None)\n    print(f\"Manual prediction result for sequence_id {sample_seq_id}: {prediction}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-25T23:00:19.336168Z","iopub.execute_input":"2025-06-25T23:00:19.336388Z","iopub.status.idle":"2025-06-25T23:00:19.787083Z","shell.execute_reply.started":"2025-06-25T23:00:19.336370Z","shell.execute_reply":"2025-06-25T23:00:19.786206Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}