{"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-06-05T02:14:46.233866Z","iopub.execute_input":"2025-06-05T02:14:46.234178Z","iopub.status.idle":"2025-06-05T02:14:46.247157Z","shell.execute_reply.started":"2025-06-05T02:14:46.234155Z","shell.execute_reply":"2025-06-05T02:14:46.246102Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import f1_score\nimport lightgbm as lgb\nimport xgboost as xgb\nimport catboost as cb\nimport warnings\nwarnings.filterwarnings(\"ignore\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T02:14:46.248678Z","iopub.execute_input":"2025-06-05T02:14:46.249001Z","iopub.status.idle":"2025-06-05T02:14:46.276849Z","shell.execute_reply.started":"2025-06-05T02:14:46.248977Z","shell.execute_reply":"2025-06-05T02:14:46.275874Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df = pd.read_csv(\"/kaggle/input/cmi-detect-behavior-with-sensor-data/train.csv\")\ntest_df = 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\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T02:14:46.278105Z","iopub.execute_input":"2025-06-05T02:14:46.278412Z","iopub.status.idle":"2025-06-05T02:15:12.584592Z","shell.execute_reply.started":"2025-06-05T02:14:46.278378Z","shell.execute_reply":"2025-06-05T02:15:12.583404Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Merge demographic data","metadata":{}},{"cell_type":"code","source":"\ntrain_df = train_df.merge(train_demo, on=\"subject\", how=\"left\")\ntest_df = test_df.merge(test_demo, on=\"subject\", how=\"left\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T02:15:26.694062Z","iopub.execute_input":"2025-06-05T02:15:26.694408Z","iopub.status.idle":"2025-06-05T02:15:30.973879Z","shell.execute_reply.started":"2025-06-05T02:15:26.694386Z","shell.execute_reply":"2025-06-05T02:15:30.972453Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df.info()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T02:16:12.689492Z","iopub.execute_input":"2025-06-05T02:16:12.689947Z","iopub.status.idle":"2025-06-05T02:16:12.737173Z","shell.execute_reply.started":"2025-06-05T02:16:12.689905Z","shell.execute_reply":"2025-06-05T02:16:12.735982Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_df.info()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T02:16:43.871692Z","iopub.execute_input":"2025-06-05T02:16:43.872014Z","iopub.status.idle":"2025-06-05T02:16:43.890969Z","shell.execute_reply.started":"2025-06-05T02:16:43.87199Z","shell.execute_reply":"2025-06-05T02:16:43.889924Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def extract_features(df, drop_cols=None):\n    if drop_cols:\n        df = df.drop(columns=drop_cols)\n    numeric_df = df.select_dtypes(include=[np.number])\n    grouped = df.groupby(\"sequence_id\")\n    agg_funcs = ['mean', 'std', 'min', 'max']\n    features = []\n    for func in agg_funcs:\n        f = grouped[numeric_df.columns].agg(func)\n        f.columns = [f\"{col}_{func}\" for col in f.columns]\n        features.append(f)\n    final_df = pd.concat(features, axis=1).reset_index()\n    return final_df\n\ndrop_cols = [\"gesture\", \"sequence_type\", \"orientation\", \"behavior\"]\ntrain_features = extract_features(train_df, drop_cols=drop_cols)\ntest_features = extract_features(test_df)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T02:21:26.379057Z","iopub.execute_input":"2025-06-05T02:21:26.379385Z","iopub.status.idle":"2025-06-05T02:21:38.845729Z","shell.execute_reply.started":"2025-06-05T02:21:26.379358Z","shell.execute_reply":"2025-06-05T02:21:38.844578Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Add target labels to train\ntargets = train_df.groupby(\"sequence_id\")[\"gesture\"].first().reset_index()\ntrain_features = train_features.merge(targets, on=\"sequence_id\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T02:22:05.886048Z","iopub.execute_input":"2025-06-05T02:22:05.886409Z","iopub.status.idle":"2025-06-05T02:22:06.014376Z","shell.execute_reply.started":"2025-06-05T02:22:05.886382Z","shell.execute_reply":"2025-06-05T02:22:06.013479Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Encode gesture labels\nle = LabelEncoder()\ntrain_features[\"gesture_encoded\"] = le.fit_transform(train_features[\"gesture\"])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T02:22:21.8836Z","iopub.execute_input":"2025-06-05T02:22:21.88391Z","iopub.status.idle":"2025-06-05T02:22:21.893159Z","shell.execute_reply.started":"2025-06-05T02:22:21.88389Z","shell.execute_reply":"2025-06-05T02:22:21.892104Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Store for inference\ngesture_map = dict(zip(le.classes_, le.transform(le.classes_)))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T02:22:37.915561Z","iopub.execute_input":"2025-06-05T02:22:37.915898Z","iopub.status.idle":"2025-06-05T02:22:37.921504Z","shell.execute_reply.started":"2025-06-05T02:22:37.915875Z","shell.execute_reply":"2025-06-05T02:22:37.920455Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X = train_features.drop(columns=[\"sequence_id\", \"gesture\", \"gesture_encoded\"])\ny = train_features[\"gesture_encoded\"]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T02:22:53.92857Z","iopub.execute_input":"2025-06-05T02:22:53.928923Z","iopub.status.idle":"2025-06-05T02:22:53.964807Z","shell.execute_reply.started":"2025-06-05T02:22:53.9289Z","shell.execute_reply":"2025-06-05T02:22:53.963181Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import StratifiedKFold\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T02:25:34.110409Z","iopub.execute_input":"2025-06-05T02:25:34.112326Z","iopub.status.idle":"2025-06-05T02:25:34.118548Z","shell.execute_reply.started":"2025-06-05T02:25:34.112255Z","shell.execute_reply":"2025-06-05T02:25:34.11741Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import StratifiedKFold\n\nX = train_features.drop(columns=[\"sequence_id\", \"gesture\", \"gesture_encoded\"])\ny = train_features[\"gesture_encoded\"]\nX_test = test_features.drop(columns=[\"sequence_id\"])\n\nskf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\npreds = np.zeros((len(X_test), len(le.classes_)))\n\nfor fold, (train_idx, val_idx) in enumerate(skf.split(X, y)):\n    print(f\"Training fold {fold}...\")\n    X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n    y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n\n    model = lgb.LGBMClassifier(n_estimators=1000, learning_rate=0.03, random_state=42)\n    model.fit(\n        X_train, y_train,\n        eval_set=[(X_val, y_val)],\n        callbacks=[lgb.early_stopping(stopping_rounds=100)],\n        verbose=100\n    )\n\n    preds += model.predict_proba(X_test) / skf.n_splits\n\n# Final prediction\nfinal_preds = le.inverse_transform(np.argmax(preds, axis=1))\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T02:25:37.447196Z","iopub.execute_input":"2025-06-05T02:25:37.448235Z","iopub.status.idle":"2025-06-05T02:25:37.529856Z","shell.execute_reply.started":"2025-06-05T02:25:37.448188Z","shell.execute_reply":"2025-06-05T02:25:37.527916Z"}},"outputs":[],"execution_count":null}]}