{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"### Random Forest multiclass classifier submission\n**Author: [Carl McBride Ellis](https://www.kaggle.com/carlmcbrideellis)** ([LinkedIn](https://www.linkedin.com/in/carl-mcbride-ellis/))\n\n\nWe shall be using the multiclass training data file (`Zzzs_train_multi.parquet`) from the reduced dataset [\"Zzzs: Lightweight training dataset + target\"](https://www.kaggle.com/datasets/carlmcbrideellis/zzzs-lightweight-training-dataset-target)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19"}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom itertools import groupby\nimport gc","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-09-14T09:07:23.837349Z","iopub.execute_input":"2023-09-14T09:07:23.837714Z","iopub.status.idle":"2023-09-14T09:07:24.199666Z","shell.execute_reply.started":"2023-09-14T09:07:23.837683Z","shell.execute_reply":"2023-09-14T09:07:24.197902Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# binary class data\n#train = pd.read_parquet(\"/kaggle/input/zzzs-lightweight-training-dataset-target/Zzzs_train.parquet\")\n\n# multiclass data\ntrain = pd.read_parquet(\"/kaggle/input/zzzs-lightweight-training-dataset-target/Zzzs_train_multi.parquet\")","metadata":{"execution":{"iopub.status.busy":"2023-09-14T09:07:24.202119Z","iopub.execute_input":"2023-09-14T09:07:24.202665Z","iopub.status.idle":"2023-09-14T09:07:34.082683Z","shell.execute_reply.started":"2023-09-14T09:07:24.202629Z","shell.execute_reply":"2023-09-14T09:07:34.081647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Feature engineering","metadata":{}},{"cell_type":"code","source":"def make_features(df):\n    # parse the timestamp and create an \"hour\" feature\n    df['timestamp'] = pd.to_datetime(df['timestamp']).apply(lambda t: t.tz_localize(None))\n    df[\"hour\"] = df[\"timestamp\"].dt.hour\n    \n    periods = 20\n    df[\"anglez\"] = abs(df[\"anglez\"])\n    df[\"anglez_diff\"] = df.groupby('series_id')['anglez'].diff(periods=periods).fillna(method=\"bfill\").astype('float16')\n    df[\"enmo_diff\"] = df.groupby('series_id')['enmo'].diff(periods=periods).fillna(method=\"bfill\").astype('float16')\n    df[\"anglez_rolling_mean\"] = df[\"anglez\"].rolling(periods,center=True).mean().fillna(method=\"bfill\").fillna(method=\"ffill\").astype('float16')\n    df[\"enmo_rolling_mean\"] = df[\"enmo\"].rolling(periods,center=True).mean().fillna(method=\"bfill\").fillna(method=\"ffill\").astype('float16')\n    df[\"anglez_rolling_max\"] = df[\"anglez\"].rolling(periods,center=True).max().fillna(method=\"bfill\").fillna(method=\"ffill\").astype('float16')\n    df[\"enmo_rolling_max\"] = df[\"enmo\"].rolling(periods,center=True).max().fillna(method=\"bfill\").fillna(method=\"ffill\").astype('float16')\n    df[\"anglez_rolling_std\"] = df[\"anglez\"].rolling(periods,center=True).std().fillna(method=\"bfill\").fillna(method=\"ffill\").astype('float16')\n    df[\"enmo_rolling_std\"] = df[\"enmo\"].rolling(periods,center=True).std().fillna(method=\"bfill\").fillna(method=\"ffill\").astype('float16')\n    df[\"anglez_diff_rolling_mean\"] = df[\"anglez_diff\"].rolling(periods,center=True).mean().fillna(method=\"bfill\").fillna(method=\"ffill\").astype('float16')\n    df[\"enmo_diff_rolling_mean\"] = df[\"enmo_diff\"].rolling(periods,center=True).mean().fillna(method=\"bfill\").fillna(method=\"ffill\").astype('float16')\n    df[\"anglez_diff_rolling_max\"] = df[\"anglez_diff\"].rolling(periods,center=True).max().fillna(method=\"bfill\").fillna(method=\"ffill\").astype('float16')\n    df[\"enmo_diff_rolling_max\"] = df[\"enmo_diff\"].rolling(periods,center=True).max().fillna(method=\"bfill\").fillna(method=\"ffill\").astype('float16')\n    \n    return df\n\nfeatures = [\"hour\",\n            \"anglez\",\n            \"anglez_rolling_mean\",\n            \"anglez_rolling_max\",\n            \"anglez_rolling_std\",\n            \"anglez_diff\",\n            \"anglez_diff_rolling_mean\",\n            \"anglez_diff_rolling_max\",\n            \"enmo\",\n            \"enmo_rolling_mean\",\n            \"enmo_rolling_max\",\n            \"enmo_rolling_std\",\n            \"enmo_diff\",\n            \"enmo_diff_rolling_mean\",\n            \"enmo_diff_rolling_max\",\n           ]","metadata":{"execution":{"iopub.status.busy":"2023-09-14T09:07:34.083715Z","iopub.execute_input":"2023-09-14T09:07:34.084100Z","iopub.status.idle":"2023-09-14T09:07:34.098285Z","shell.execute_reply.started":"2023-09-14T09:07:34.084063Z","shell.execute_reply":"2023-09-14T09:07:34.096815Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Training","metadata":{}},{"cell_type":"code","source":"train   = make_features(train)\n\nX_train = train[features]\ny_train = train[\"awake\"]\n\n# save some memory\ndel train\ngc.collect();","metadata":{"execution":{"iopub.status.busy":"2023-09-14T09:07:34.100967Z","iopub.execute_input":"2023-09-14T09:07:34.101254Z","iopub.status.idle":"2023-09-14T09:10:33.305672Z","shell.execute_reply.started":"2023-09-14T09:07:34.101232Z","shell.execute_reply":"2023-09-14T09:10:33.304492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nfrom sklearn.ensemble import RandomForestClassifier\nclassifier = RandomForestClassifier(n_estimators=50,\n                                    min_samples_leaf=300,\n                                    random_state=42,n_jobs=-1)\n\nclassifier.fit(X_train, y_train)\n\n# save some memory\ndel X_train, y_train\ngc.collect();","metadata":{"execution":{"iopub.status.busy":"2023-09-14T09:18:51.905681Z","iopub.execute_input":"2023-09-14T09:18:51.906110Z","iopub.status.idle":"2023-09-14T09:18:52.000218Z","shell.execute_reply.started":"2023-09-14T09:18:51.906081Z","shell.execute_reply":"2023-09-14T09:18:51.999257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Predictions","metadata":{}},{"cell_type":"code","source":"test  = pd.read_parquet(\"/kaggle/input/child-mind-institute-detect-sleep-states/test_series.parquet\")\n\ntest  = make_features(test)\n\nX_test = test[features]\n\ntest[\"not_awake\"] = classifier.predict_proba(X_test)[:,0]\ntest[\"awake\"]     = classifier.predict_proba(X_test)[:,1]","metadata":{"execution":{"iopub.status.busy":"2023-09-14T09:15:01.523295Z","iopub.execute_input":"2023-09-14T09:15:01.523620Z","iopub.status.idle":"2023-09-14T09:15:01.618403Z","shell.execute_reply.started":"2023-09-14T09:15:01.523590Z","shell.execute_reply":"2023-09-14T09:15:01.616780Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Processing","metadata":{}},{"cell_type":"code","source":"# smoothing the predictions\nsmoothing_length = 2*230\ntest[\"score\"]  = test[\"awake\"].rolling(smoothing_length,center=True).mean().fillna(method=\"bfill\").fillna(method=\"ffill\")\ntest[\"smooth\"] = test[\"not_awake\"].rolling(smoothing_length,center=True).mean().fillna(method=\"bfill\").fillna(method=\"ffill\")\n# re-binarize\ntest[\"smooth\"] = test[\"smooth\"].round()\n\n# https://stackoverflow.com/questions/73777727/how-to-mark-start-end-of-a-series-of-non-null-and-non-0-values-in-a-column-of-a\ndef get_event(df):\n    lstCV = zip(df.series_id, df.smooth)\n    lstPOI = []\n    for (c, v), g in groupby(lstCV, lambda cv: \n                            (cv[0], cv[1]!=0 and not pd.isnull(cv[1]))):\n        llg = sum(1 for item in g)\n        if v is False: \n            lstPOI.extend([0]*llg)\n        else: \n            lstPOI.extend(['onset']+(llg-2)*[0]+['wakeup'] if llg > 1 else [0])\n    return lstPOI\n\ntest[\"event\"] = get_event(test)","metadata":{"execution":{"iopub.status.busy":"2023-09-14T09:15:01.619894Z","iopub.execute_input":"2023-09-14T09:15:01.624779Z","iopub.status.idle":"2023-09-14T09:15:01.641234Z","shell.execute_reply.started":"2023-09-14T09:15:01.624731Z","shell.execute_reply":"2023-09-14T09:15:01.638592Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Write out a `submission.csv`","metadata":{}},{"cell_type":"code","source":"sample_submission = test.loc[test[\"event\"] != 0][[\"series_id\",\"step\",\"event\",\"score\"]].copy().reset_index(drop=True).reset_index(names=\"row_id\")\nsample_submission.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-09-14T09:15:01.643797Z","iopub.execute_input":"2023-09-14T09:15:01.645755Z","iopub.status.idle":"2023-09-14T09:15:01.667091Z","shell.execute_reply.started":"2023-09-14T09:15:01.645690Z","shell.execute_reply":"2023-09-14T09:15:01.665317Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Related reading\n* [K. Sundararajan *et al. \"Sleep classification from wrist-worn accelerometer data using Random Forests*\", Scientific Reports volume **11**, Article number: 24 (2021)](https://www.nature.com/articles/s41598-020-79217-x.pdf)\n* [K. Sundararajan *et al. \"Supplementary Information for Article: Sleep classification from wrist-worn accelerometer data using Random Forests*\"](https://static-content.springer.com/esm/art%3A10.1038%2Fs41598-020-79217-x/MediaObjects/41598_2020_79217_MOESM1_ESM.pdf)","metadata":{}}],"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}}