{"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"}},"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\n# import os\n# for 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","execution":{"iopub.status.busy":"2023-10-13T13:07:54.456333Z","iopub.execute_input":"2023-10-13T13:07:54.458080Z","iopub.status.idle":"2023-10-13T13:07:54.838727Z","shell.execute_reply.started":"2023-10-13T13:07:54.457990Z","shell.execute_reply":"2023-10-13T13:07:54.837695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport random\n\nimport dask\nimport dask.array as da\nimport dask.dataframe as dd","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:07:54.840448Z","iopub.execute_input":"2023-10-13T13:07:54.840878Z","iopub.status.idle":"2023-10-13T13:07:57.074359Z","shell.execute_reply.started":"2023-10-13T13:07:54.840847Z","shell.execute_reply":"2023-10-13T13:07:57.073330Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nimport polars as pl\ntrain_series = (pl.scan_parquet('/kaggle/input/child-mind-institute-detect-sleep-states/train_series.parquet')\n                .with_columns(\n                    (\n                        (pl.col(\"timestamp\").str.strptime(pl.Datetime, \"%Y-%m-%dT%H:%M:%S%Z\")),\n#                         (pl.col(\"timestamp\").str.strptime(pl.Datetime, \"%Y-%m-%dT%H:%M:%S%Z\").dt.year().alias(\"year\")),\n#                         (pl.col(\"timestamp\").str.strptime(pl.Datetime, \"%Y-%m-%dT%H:%M:%S%Z\").dt.month().alias(\"month\")),\n#                         (pl.col(\"timestamp\").str.strptime(pl.Datetime, \"%Y-%m-%dT%H:%M:%S%Z\").dt.day().alias(\"day\")),\n#                         (pl.col(\"timestamp\").str.strptime(pl.Datetime, \"%Y-%m-%dT%H:%M:%S%Z\").dt.hour().alias(\"hour\")),\n                    )\n                )\n                .collect()\n                .to_pandas()\n               )","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:07:57.076823Z","iopub.execute_input":"2023-10-13T13:07:57.077292Z","iopub.status.idle":"2023-10-13T13:08:49.878507Z","shell.execute_reply.started":"2023-10-13T13:07:57.077263Z","shell.execute_reply":"2023-10-13T13:08:49.877410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Memory reduction\nThe following function has been taken from the notebook \n<a \n   href=https://www.kaggle.com/code/renatoreggiani/feat-eng-ideas-60-memory-reduction-cmi>\n    🛠Feat Eng ideas & 60% memory reduction 🛠- CMI\n</a>","metadata":{}},{"cell_type":"code","source":"from pandas.api.types import is_datetime64_ns_dtype\nimport gc\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndef reduce_mem_usage(df):\n    \n    \"\"\" \n    Iterate through all numeric columns of a dataframe and modify the data type\n    to reduce memory usage.        \n    \"\"\"\n    \n    start_mem = df.memory_usage().sum() / 1024**2\n    print(f'Memory usage of dataframe is {start_mem:.2f} MB')\n    \n    for col in df.columns:\n        col_type = df[col].dtype\n\n        if col_type != object and not is_datetime64_ns_dtype(df[col]):\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float32)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n        \n\n    df['series_id'] = df['series_id'].astype('category')\n\n    end_mem = df.memory_usage().sum() / 1024**2\n    print(f'Memory usage after optimization is: {end_mem:.2f} MB')\n    decrease = 100 * (start_mem - end_mem) / start_mem\n    print(f'Decreased by {decrease:.2f}%')\n    \n    return df","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:08:49.881027Z","iopub.execute_input":"2023-10-13T13:08:49.881404Z","iopub.status.idle":"2023-10-13T13:08:49.893367Z","shell.execute_reply.started":"2023-10-13T13:08:49.881378Z","shell.execute_reply":"2023-10-13T13:08:49.892548Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_series = reduce_mem_usage(train_series)","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:08:49.894460Z","iopub.execute_input":"2023-10-13T13:08:49.894928Z","iopub.status.idle":"2023-10-13T13:09:02.355096Z","shell.execute_reply.started":"2023-10-13T13:08:49.894896Z","shell.execute_reply":"2023-10-13T13:09:02.354103Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_series.head()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:02.356532Z","iopub.execute_input":"2023-10-13T13:09:02.356941Z","iopub.status.idle":"2023-10-13T13:09:02.377056Z","shell.execute_reply.started":"2023-10-13T13:09:02.356905Z","shell.execute_reply":"2023-10-13T13:09:02.376161Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_events = (pl.scan_csv('/kaggle/input/child-mind-institute-detect-sleep-states/train_events.csv')\n                .with_columns(\n                    (\n                        (pl.col(\"timestamp\").str.strptime(pl.Datetime, \"%Y-%m-%dT%H:%M:%S%Z\")),\n                        (pl.col(\"timestamp\").str.strptime(pl.Datetime, \"%Y-%m-%dT%H:%M:%S%Z\").dt.year().alias(\"year\")),\n                        (pl.col(\"timestamp\").str.strptime(pl.Datetime, \"%Y-%m-%dT%H:%M:%S%Z\").dt.month().alias(\"month\")),\n                        (pl.col(\"timestamp\").str.strptime(pl.Datetime, \"%Y-%m-%dT%H:%M:%S%Z\").dt.day().alias(\"day\")),\n                        (pl.col(\"timestamp\").str.strptime(pl.Datetime, \"%Y-%m-%dT%H:%M:%S%Z\").dt.hour().alias(\"hour\")),\n                    )\n                )\n                .collect()\n                .to_pandas()\n               )","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:02.378475Z","iopub.execute_input":"2023-10-13T13:09:02.378796Z","iopub.status.idle":"2023-10-13T13:09:02.437746Z","shell.execute_reply.started":"2023-10-13T13:09:02.378769Z","shell.execute_reply":"2023-10-13T13:09:02.436718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_events.head()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:02.439178Z","iopub.execute_input":"2023-10-13T13:09:02.439695Z","iopub.status.idle":"2023-10-13T13:09:02.453828Z","shell.execute_reply.started":"2023-10-13T13:09:02.439641Z","shell.execute_reply":"2023-10-13T13:09:02.453088Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Preprocess the data","metadata":{}},{"cell_type":"markdown","source":"## Sort the datasets by the timestamp","metadata":{}},{"cell_type":"code","source":"train_series = train_series.sort_values('timestamp').reset_index(drop=True)\ntrain_series.head()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:02.455139Z","iopub.execute_input":"2023-10-13T13:09:02.455448Z","iopub.status.idle":"2023-10-13T13:09:24.557663Z","shell.execute_reply.started":"2023-10-13T13:09:02.455423Z","shell.execute_reply":"2023-10-13T13:09:24.556701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_events = train_events.sort_values('timestamp').reset_index(drop=True)\ntrain_events.head()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:24.559315Z","iopub.execute_input":"2023-10-13T13:09:24.559741Z","iopub.status.idle":"2023-10-13T13:09:24.581775Z","shell.execute_reply.started":"2023-10-13T13:09:24.559705Z","shell.execute_reply":"2023-10-13T13:09:24.580581Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Sleep hours distribution","metadata":{}},{"cell_type":"markdown","source":"Create the dataframe with the sleep hours as follow: <br>\n- Make the dfference between the rows of the timestamp columns\n- Extract the hour and day components from the difference\n- Encode the events and make the difference\n- Create a pandas dataframe named train_sleep \n\nSince there are missing values in the dataframe that can make the difference big, it is good to remove the rows with day > 0 (sssuming they have never slept for more than 24 hours) <br>\nAfter the difference, the events are equal to -1 and +1, corresponding to hours of sleep and hours of wakefulness, respectively. <br>\nFor our purpose, only the events = -1 will be kept.","metadata":{}},{"cell_type":"code","source":"### Difference between the rows of the timestamp column\ntrain_events_hours = train_events.timestamp.diff().dt.components['hours']   # Extract the hour component from the difference\ntrain_events_days  = train_events.timestamp.diff().dt.components['days']    # Extract the day component from the difference\ntrain_events_event = train_events.event.map({'onset':1, 'wakeup':0}).diff() # Encode the events and make the difference","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:24.586248Z","iopub.execute_input":"2023-10-13T13:09:24.586584Z","iopub.status.idle":"2023-10-13T13:09:24.798483Z","shell.execute_reply.started":"2023-10-13T13:09:24.586557Z","shell.execute_reply":"2023-10-13T13:09:24.797452Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"### Create the pandas dataframe\ntrain_sleep = pd.DataFrame([train_events.month, train_events.day, train_events_days, train_events_hours, train_events_event], \n                           index=['month', 'day', 'days_sleep', 'hours_sleep', 'event']).T.dropna()\ntrain_sleep = train_sleep[(train_sleep.days_sleep == 0) & (train_sleep.event == -1)].reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:24.799830Z","iopub.execute_input":"2023-10-13T13:09:24.800808Z","iopub.status.idle":"2023-10-13T13:09:24.903079Z","shell.execute_reply.started":"2023-10-13T13:09:24.800769Z","shell.execute_reply":"2023-10-13T13:09:24.902238Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_sleep.head()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:24.904260Z","iopub.execute_input":"2023-10-13T13:09:24.905395Z","iopub.status.idle":"2023-10-13T13:09:24.918916Z","shell.execute_reply.started":"2023-10-13T13:09:24.905356Z","shell.execute_reply":"2023-10-13T13:09:24.917893Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_sleep.describe()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:24.920124Z","iopub.execute_input":"2023-10-13T13:09:24.920777Z","iopub.status.idle":"2023-10-13T13:09:24.953145Z","shell.execute_reply.started":"2023-10-13T13:09:24.920741Z","shell.execute_reply":"2023-10-13T13:09:24.952070Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Interpolation of the timestamp","metadata":{}},{"cell_type":"code","source":"train_events.head(15)","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:24.954473Z","iopub.execute_input":"2023-10-13T13:09:24.954883Z","iopub.status.idle":"2023-10-13T13:09:24.976236Z","shell.execute_reply.started":"2023-10-13T13:09:24.954848Z","shell.execute_reply":"2023-10-13T13:09:24.975510Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_events['timestamp'] = train_events.timestamp.interpolate()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:24.977137Z","iopub.execute_input":"2023-10-13T13:09:24.977772Z","iopub.status.idle":"2023-10-13T13:09:24.983579Z","shell.execute_reply.started":"2023-10-13T13:09:24.977746Z","shell.execute_reply":"2023-10-13T13:09:24.982732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_events.head(15)","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:24.985157Z","iopub.execute_input":"2023-10-13T13:09:24.985767Z","iopub.status.idle":"2023-10-13T13:09:25.011295Z","shell.execute_reply.started":"2023-10-13T13:09:24.985730Z","shell.execute_reply":"2023-10-13T13:09:25.009812Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Merge the event and series datasets","metadata":{}},{"cell_type":"code","source":"train_series.shape","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:25.012745Z","iopub.execute_input":"2023-10-13T13:09:25.013421Z","iopub.status.idle":"2023-10-13T13:09:25.025840Z","shell.execute_reply.started":"2023-10-13T13:09:25.013382Z","shell.execute_reply":"2023-10-13T13:09:25.024604Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_events_tomerge = train_events[['timestamp', 'event']]\ntrain_events_tomerge.head()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:25.027254Z","iopub.execute_input":"2023-10-13T13:09:25.028112Z","iopub.status.idle":"2023-10-13T13:09:25.044204Z","shell.execute_reply.started":"2023-10-13T13:09:25.028074Z","shell.execute_reply":"2023-10-13T13:09:25.042971Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_events_tomerge.isna().sum()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:25.045998Z","iopub.execute_input":"2023-10-13T13:09:25.046432Z","iopub.status.idle":"2023-10-13T13:09:25.058550Z","shell.execute_reply.started":"2023-10-13T13:09:25.046394Z","shell.execute_reply":"2023-10-13T13:09:25.057469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_series_merged = train_series.merge(train_events_tomerge, how='left', on='timestamp')","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:25.059954Z","iopub.execute_input":"2023-10-13T13:09:25.060927Z","iopub.status.idle":"2023-10-13T13:09:49.683333Z","shell.execute_reply.started":"2023-10-13T13:09:25.060890Z","shell.execute_reply":"2023-10-13T13:09:49.682386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_series_merged.head()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:49.684397Z","iopub.execute_input":"2023-10-13T13:09:49.684688Z","iopub.status.idle":"2023-10-13T13:09:49.696863Z","shell.execute_reply.started":"2023-10-13T13:09:49.684665Z","shell.execute_reply":"2023-10-13T13:09:49.695842Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Fill the missing values in the event column","metadata":{}},{"cell_type":"markdown","source":"Using the method 'ffill', the missing values will be replace with the previous non-missing value","metadata":{}},{"cell_type":"code","source":"train_series_merged['event'] = train_series_merged.event.fillna(method='ffill')","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:49.698194Z","iopub.execute_input":"2023-10-13T13:09:49.698628Z","iopub.status.idle":"2023-10-13T13:09:59.052452Z","shell.execute_reply.started":"2023-10-13T13:09:49.698596Z","shell.execute_reply":"2023-10-13T13:09:59.051551Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Acting like this,the first rows with missing values are not replaced because there is no value before them. <br>\nChecking the train_events dataset, the first event is 'onset', that correspond to the beginning of sleep.  <br>\nFor this reason the event before 'onset' is 'wakeup'. <br>\nLet's fill the remaining rows with missing values with 'wakeup'. <br>","metadata":{}},{"cell_type":"code","source":"train_series_merged['event'] = train_series_merged.event.fillna('wakeup')","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:09:59.053847Z","iopub.execute_input":"2023-10-13T13:09:59.054717Z","iopub.status.idle":"2023-10-13T13:10:11.345572Z","shell.execute_reply.started":"2023-10-13T13:09:59.054678Z","shell.execute_reply":"2023-10-13T13:10:11.344595Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Check for missing values in the event column","metadata":{}},{"cell_type":"code","source":"train_series_merged.event.isna().sum()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:11.347018Z","iopub.execute_input":"2023-10-13T13:10:11.347294Z","iopub.status.idle":"2023-10-13T13:10:16.925776Z","shell.execute_reply.started":"2023-10-13T13:10:11.347272Z","shell.execute_reply":"2023-10-13T13:10:16.924697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Explore the data","metadata":{}},{"cell_type":"markdown","source":"## Data information","metadata":{}},{"cell_type":"code","source":"train_events.info()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:16.926851Z","iopub.execute_input":"2023-10-13T13:10:16.927211Z","iopub.status.idle":"2023-10-13T13:10:16.950270Z","shell.execute_reply.started":"2023-10-13T13:10:16.927181Z","shell.execute_reply":"2023-10-13T13:10:16.949489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Explore the train_events dataset","metadata":{}},{"cell_type":"code","source":"train_events.describe()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:16.951671Z","iopub.execute_input":"2023-10-13T13:10:16.952191Z","iopub.status.idle":"2023-10-13T13:10:16.990942Z","shell.execute_reply.started":"2023-10-13T13:10:16.952162Z","shell.execute_reply":"2023-10-13T13:10:16.989899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Number of unique identifiers for each series of accelerometer data:', len(train_events.series_id.unique()))","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:16.992461Z","iopub.execute_input":"2023-10-13T13:10:16.993059Z","iopub.status.idle":"2023-10-13T13:10:16.999281Z","shell.execute_reply.started":"2023-10-13T13:10:16.993019Z","shell.execute_reply":"2023-10-13T13:10:16.998353Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Hours distribution","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(10,4))\n# plt.subplot(121)\nplt.title('Hour distribution with onset and wakeup')\nsns.histplot(x=train_events.dropna().hour, hue=train_events.dropna().event, stat='density', bins=24, binrange=(-0.5, 23.5))\nsns.kdeplot(train_events.dropna().hour, bw_adjust=0.45)","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:17.000628Z","iopub.execute_input":"2023-10-13T13:10:17.001025Z","iopub.status.idle":"2023-10-13T13:10:17.611810Z","shell.execute_reply.started":"2023-10-13T13:10:17.000990Z","shell.execute_reply":"2023-10-13T13:10:17.610720Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(10,4))\nplt.title('Sleep hours distribution')\nsns.histplot(x=train_sleep.hours_sleep, stat='density', bins=19, binrange=(-0.5, 18.5))\nsns.kdeplot(train_sleep.hours_sleep, bw_adjust=2, color='red')","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:17.613019Z","iopub.execute_input":"2023-10-13T13:10:17.613777Z","iopub.status.idle":"2023-10-13T13:10:17.954487Z","shell.execute_reply.started":"2023-10-13T13:10:17.613747Z","shell.execute_reply":"2023-10-13T13:10:17.953414Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(15,3))\nplt.title('Average sleep hours per day')\nsns.barplot(x=train_sleep.groupby('day').hours_sleep.mean().index, y=train_sleep.groupby('day').hours_sleep.mean().values)","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:17.956187Z","iopub.execute_input":"2023-10-13T13:10:17.957107Z","iopub.status.idle":"2023-10-13T13:10:18.485956Z","shell.execute_reply.started":"2023-10-13T13:10:17.957068Z","shell.execute_reply":"2023-10-13T13:10:18.484903Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(10,3))\nplt.title('Average sleep hours per month')\nsns.barplot(x=train_sleep.groupby('month').hours_sleep.mean().index, y=train_sleep.groupby('month').hours_sleep.mean().values)","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:18.491746Z","iopub.execute_input":"2023-10-13T13:10:18.492716Z","iopub.status.idle":"2023-10-13T13:10:18.755347Z","shell.execute_reply.started":"2023-10-13T13:10:18.492675Z","shell.execute_reply":"2023-10-13T13:10:18.754237Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The average number of sleep hour is about 8 hours. There is no distinction between days and months. It could have been hypothesized that in the summer months and on weekends, the hours of sleep were greater. This is because, considering that in these days the parents, not working, would have been able to sleep more, the children's sleeping hours would have increased. This hypothesis is not visible in the data and is therefore rejected.","metadata":{}},{"cell_type":"markdown","source":"## Explore the train_series_merged dataset","metadata":{}},{"cell_type":"code","source":"train_series.info()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:18.757095Z","iopub.execute_input":"2023-10-13T13:10:18.757506Z","iopub.status.idle":"2023-10-13T13:10:18.770111Z","shell.execute_reply.started":"2023-10-13T13:10:18.757467Z","shell.execute_reply":"2023-10-13T13:10:18.769125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_series.isna().sum()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:18.772150Z","iopub.execute_input":"2023-10-13T13:10:18.773062Z","iopub.status.idle":"2023-10-13T13:10:19.746127Z","shell.execute_reply.started":"2023-10-13T13:10:18.772997Z","shell.execute_reply":"2023-10-13T13:10:19.745057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f'In the dataset there are {len(train_series.series_id.unique())} accelerometer series')","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:19.747286Z","iopub.execute_input":"2023-10-13T13:10:19.747569Z","iopub.status.idle":"2023-10-13T13:10:20.410722Z","shell.execute_reply.started":"2023-10-13T13:10:19.747545Z","shell.execute_reply":"2023-10-13T13:10:20.409624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(14,3))\nsns.barplot(x=train_series.groupby('series_id').anglez.mean(),\n            y=train_series.groupby('series_id').anglez.mean())\ng = plt.xticks(ticks=[])","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:20.413281Z","iopub.execute_input":"2023-10-13T13:10:20.414066Z","iopub.status.idle":"2023-10-13T13:10:24.485231Z","shell.execute_reply.started":"2023-10-13T13:10:20.414026Z","shell.execute_reply":"2023-10-13T13:10:24.484374Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Take 5 random series_id and explore them","metadata":{}},{"cell_type":"code","source":"series_id_selected = random.choices(train_series_merged.series_id.unique(), k=5)\nseries_id_selected","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:24.486458Z","iopub.execute_input":"2023-10-13T13:10:24.487409Z","iopub.status.idle":"2023-10-13T13:10:25.160352Z","shell.execute_reply.started":"2023-10-13T13:10:24.487369Z","shell.execute_reply":"2023-10-13T13:10:25.159421Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Extract a subset of the dataset with the selected series id","metadata":{}},{"cell_type":"code","source":"train_series_sub = train_series_merged[train_series_merged.series_id.isin(series_id_selected)].reset_index(drop=True)\ntrain_series_sub.shape","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:25.161618Z","iopub.execute_input":"2023-10-13T13:10:25.162014Z","iopub.status.idle":"2023-10-13T13:10:26.475807Z","shell.execute_reply.started":"2023-10-13T13:10:25.161978Z","shell.execute_reply":"2023-10-13T13:10:26.474767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Convert from datetime to timestamp","metadata":{}},{"cell_type":"code","source":"train_series_sub['timestamp_new'] = train_series_sub.timestamp.astype(int).div(10**9)","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:26.476961Z","iopub.execute_input":"2023-10-13T13:10:26.477249Z","iopub.status.idle":"2023-10-13T13:10:26.502700Z","shell.execute_reply.started":"2023-10-13T13:10:26.477224Z","shell.execute_reply":"2023-10-13T13:10:26.501711Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_series_sub.head()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:26.503989Z","iopub.execute_input":"2023-10-13T13:10:26.504347Z","iopub.status.idle":"2023-10-13T13:10:26.517987Z","shell.execute_reply.started":"2023-10-13T13:10:26.504322Z","shell.execute_reply":"2023-10-13T13:10:26.517199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nplt.figure(figsize=(12,3))\nsns.scatterplot(data=train_series_sub[train_series_sub.series_id == series_id_selected[0]],\n             x='timestamp', y='anglez', hue='event')","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:10:26.518876Z","iopub.execute_input":"2023-10-13T13:10:26.519170Z","iopub.status.idle":"2023-10-13T13:11:21.057825Z","shell.execute_reply.started":"2023-10-13T13:10:26.519145Z","shell.execute_reply":"2023-10-13T13:11:21.056753Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nplt.figure(figsize=(12,3))\nsns.scatterplot(data=train_series_sub[train_series_sub.series_id == series_id_selected[0]],\n             x='timestamp', y='enmo', hue='event')","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:15:02.644766Z","iopub.execute_input":"2023-10-13T13:15:02.647516Z","iopub.status.idle":"2023-10-13T13:15:35.087439Z","shell.execute_reply.started":"2023-10-13T13:15:02.647442Z","shell.execute_reply":"2023-10-13T13:15:35.086257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nplt.figure(figsize=(12,3))\nsns.scatterplot(x=train_series_sub[train_series_sub.series_id == series_id_selected[0]].timestamp,\n                y=train_series_sub[train_series_sub.series_id == series_id_selected[0]].anglez*train_series_sub[train_series_sub.series_id == series_id_selected[0]].enmo,\n                hue=train_series_sub[train_series_sub.series_id == series_id_selected[0]].event)","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:11:21.059213Z","iopub.execute_input":"2023-10-13T13:11:21.059890Z","iopub.status.idle":"2023-10-13T13:11:52.984175Z","shell.execute_reply.started":"2023-10-13T13:11:21.059852Z","shell.execute_reply":"2023-10-13T13:11:52.983076Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nfor ids in series_id_selected:\n    plt.figure(figsize=(12,3))\n    plt.title(f'z-angle distribution with events for {ids} id')\n    sns.histplot(data=train_series_sub[train_series_sub.series_id == ids],\n                 x=train_series_sub[train_series_sub.series_id == ids].anglez.abs(), hue='event', fill=True, bins=100, alpha=0.3)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:11:52.985832Z","iopub.execute_input":"2023-10-13T13:11:52.986937Z","iopub.status.idle":"2023-10-13T13:12:00.490840Z","shell.execute_reply.started":"2023-10-13T13:11:52.986873Z","shell.execute_reply":"2023-10-13T13:12:00.489822Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nfor ids in series_id_selected:\n    plt.figure(figsize=(12,3))\n    plt.title(f'z-angle distribution with events for {ids} id')\n    sns.histplot(data=train_series_sub[train_series_sub.series_id == ids],\n                 x='enmo', hue='event', fill=True, bins=100, alpha=0.3)\n    plt.yscale('log')\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:12:00.492313Z","iopub.execute_input":"2023-10-13T13:12:00.492735Z","iopub.status.idle":"2023-10-13T13:12:10.253558Z","shell.execute_reply.started":"2023-10-13T13:12:00.492699Z","shell.execute_reply":"2023-10-13T13:12:10.252491Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"From the z-angle distribution follows that: <br>\n- the wakeup probability decrases as the absolute value of the angle increases. \n- the onset probability is almost constant for all the angle values, except for a few peaks\n\nFrom the ENMO distribution both the event count decreases as the enmo encreases","metadata":{}},{"cell_type":"code","source":"%%time\nplt.figure(figsize=(12,3))\nplt.title('z-angle distribution with events')\nsns.histplot(data=train_series_sub[train_series_sub.series_id == series_id_selected[0]],\n             x=np.sin(train_series_sub[train_series_sub.series_id == series_id_selected[0]].anglez)*\\\n             (train_series_sub[train_series_sub.series_id == series_id_selected[0]].enmo), \n             hue='event', fill=True, bins=100, alpha=0.3)\nplt.yscale('log')","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:12:10.254975Z","iopub.execute_input":"2023-10-13T13:12:10.255897Z","iopub.status.idle":"2023-10-13T13:12:12.416071Z","shell.execute_reply.started":"2023-10-13T13:12:10.255857Z","shell.execute_reply":"2023-10-13T13:12:12.414921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"In the ENMO, all the zero values correspond to zero or negative values rounded to zero.","metadata":{}},{"cell_type":"code","source":"train_series_merged.memory_usage().sum() / 1024**2","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:12:12.417484Z","iopub.execute_input":"2023-10-13T13:12:12.417861Z","iopub.status.idle":"2023-10-13T13:12:12.425595Z","shell.execute_reply.started":"2023-10-13T13:12:12.417833Z","shell.execute_reply":"2023-10-13T13:12:12.424426Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Preprocess the test dataset","metadata":{}},{"cell_type":"code","source":"%%time\ntest_series = (pl.scan_parquet('/kaggle/input/child-mind-institute-detect-sleep-states/test_series.parquet')\n                .with_columns(\n                    (\n                        (pl.col(\"timestamp\").str.strptime(pl.Datetime, \"%Y-%m-%dT%H:%M:%S%Z\")),\n#                         (pl.col(\"timestamp\").str.strptime(pl.Datetime, \"%Y-%m-%dT%H:%M:%S%Z\").dt.year().alias(\"year\")),\n#                         (pl.col(\"timestamp\").str.strptime(pl.Datetime, \"%Y-%m-%dT%H:%M:%S%Z\").dt.month().alias(\"month\")),\n#                         (pl.col(\"timestamp\").str.strptime(pl.Datetime, \"%Y-%m-%dT%H:%M:%S%Z\").dt.day().alias(\"day\")),\n#                         (pl.col(\"timestamp\").str.strptime(pl.Datetime, \"%Y-%m-%dT%H:%M:%S%Z\").dt.hour().alias(\"hour\")),\n                    )\n                )\n                .collect()\n                .to_pandas()\n               )","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:12:12.427054Z","iopub.execute_input":"2023-10-13T13:12:12.427709Z","iopub.status.idle":"2023-10-13T13:12:12.451451Z","shell.execute_reply.started":"2023-10-13T13:12:12.427670Z","shell.execute_reply":"2023-10-13T13:12:12.450736Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_series = reduce_mem_usage(test_series)","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:12:12.452610Z","iopub.execute_input":"2023-10-13T13:12:12.453424Z","iopub.status.idle":"2023-10-13T13:12:12.463598Z","shell.execute_reply.started":"2023-10-13T13:12:12.453394Z","shell.execute_reply":"2023-10-13T13:12:12.462507Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Save the datasets","metadata":{}},{"cell_type":"code","source":"train_series_merged.to_parquet('/kaggle/working/train_series_preprocessed.parquet')\ntest_series.to_parquet('/kaggle/working/test_series_preprocessed.parquet')","metadata":{"execution":{"iopub.status.busy":"2023-10-13T13:12:12.464643Z","iopub.execute_input":"2023-10-13T13:12:12.465213Z","iopub.status.idle":"2023-10-13T13:12:38.079253Z","shell.execute_reply.started":"2023-10-13T13:12:12.465184Z","shell.execute_reply":"2023-10-13T13:12:38.078077Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Since the dataset is large, to avoid long times, the model will be made in the notebook <a href=https://www.kaggle.com/code/enricomanosperti/detect-sleep-states-preprocessing-and-eda> Detect Sleep States: Model</a> <br>\nThe saved dataset is <a href=https://www.kaggle.com/datasets/enricomanosperti/sleep-states-preprocessed-dataset> Sleep States Preprocessed Dataset</a>\n","metadata":{"execution":{"iopub.status.busy":"2023-09-28T17:17:29.009159Z","iopub.execute_input":"2023-09-28T17:17:29.009949Z","iopub.status.idle":"2023-09-28T17:17:29.022897Z","shell.execute_reply.started":"2023-09-28T17:17:29.009903Z","shell.execute_reply":"2023-09-28T17:17:29.021658Z"}}}]}