{"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\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","execution":{"iopub.status.busy":"2023-10-16T14:01:38.009086Z","iopub.execute_input":"2023-10-16T14:01:38.009445Z","iopub.status.idle":"2023-10-16T14:01:38.539089Z","shell.execute_reply.started":"2023-10-16T14:01:38.009416Z","shell.execute_reply":"2023-10-16T14:01:38.538160Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\nimport polars as pl\nfrom datetime import datetime","metadata":{"execution":{"iopub.status.busy":"2023-10-16T14:01:38.540387Z","iopub.execute_input":"2023-10-16T14:01:38.541567Z","iopub.status.idle":"2023-10-16T14:01:39.969536Z","shell.execute_reply.started":"2023-10-16T14:01:38.541524Z","shell.execute_reply":"2023-10-16T14:01:39.968603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Preprocessing","metadata":{}},{"cell_type":"code","source":"dt_transforms = [\n      pl.col('timestamp').str.to_datetime(), \n    (pl.col('timestamp').str.to_datetime().dt.date()).alias('date'), \n    pl.col('timestamp').str.to_datetime().dt.time().alias('time')\n    ]","metadata":{"execution":{"iopub.status.busy":"2023-10-16T14:01:39.970532Z","iopub.execute_input":"2023-10-16T14:01:39.971505Z","iopub.status.idle":"2023-10-16T14:01:39.987299Z","shell.execute_reply.started":"2023-10-16T14:01:39.971476Z","shell.execute_reply":"2023-10-16T14:01:39.986152Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_series = (pl.scan_parquet('/kaggle/input/child-mind-institute-detect-sleep-states/train_series.parquet')\n                .with_columns(\n    (dt_transforms)\n    )\n                .collect()\n                .to_pandas()\n               )   ","metadata":{"execution":{"iopub.status.busy":"2023-10-16T14:01:39.989747Z","iopub.execute_input":"2023-10-16T14:01:39.990235Z","iopub.status.idle":"2023-10-16T14:03:29.056943Z","shell.execute_reply.started":"2023-10-16T14:01:39.990067Z","shell.execute_reply":"2023-10-16T14:03:29.055386Z"},"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                    (dt_transforms)\n                    )\n                .collect()\n                .to_pandas()\n               )","metadata":{"execution":{"iopub.status.busy":"2023-10-16T14:03:29.058924Z","iopub.execute_input":"2023-10-16T14:03:29.059357Z","iopub.status.idle":"2023-10-16T14:03:29.107087Z","shell.execute_reply.started":"2023-10-16T14:03:29.059314Z","shell.execute_reply":"2023-10-16T14:03:29.105970Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# EDA","metadata":{}},{"cell_type":"code","source":"train_series","metadata":{"execution":{"iopub.status.busy":"2023-10-16T14:03:29.108562Z","iopub.execute_input":"2023-10-16T14:03:29.108911Z","iopub.status.idle":"2023-10-16T14:03:29.139079Z","shell.execute_reply.started":"2023-10-16T14:03:29.108881Z","shell.execute_reply":"2023-10-16T14:03:29.138279Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plt.figure(figsize=(10, 6))\n# ax = sns.distplot(train_series.anglez)\n# plt.title('Distribution of anglez values in train_series')\n# plt.show()","metadata":{"execution":{"iopub.status.busy":"2023-10-16T14:03:29.140262Z","iopub.execute_input":"2023-10-16T14:03:29.140762Z","iopub.status.idle":"2023-10-16T14:03:29.143894Z","shell.execute_reply.started":"2023-10-16T14:03:29.140725Z","shell.execute_reply":"2023-10-16T14:03:29.143142Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plt.figure(figsize=(10, 6))\n# ax = sns.distplot(train_series.enmo)\n# plt.title('Distribution of ENMO values in train_series')\n# plt.show()","metadata":{"execution":{"iopub.status.busy":"2023-10-16T14:03:29.144953Z","iopub.execute_input":"2023-10-16T14:03:29.145383Z","iopub.status.idle":"2023-10-16T14:03:29.158030Z","shell.execute_reply.started":"2023-10-16T14:03:29.145357Z","shell.execute_reply":"2023-10-16T14:03:29.157193Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_events","metadata":{"execution":{"iopub.status.busy":"2023-10-16T14:03:29.159156Z","iopub.execute_input":"2023-10-16T14:03:29.159631Z","iopub.status.idle":"2023-10-16T14:03:29.190443Z","shell.execute_reply.started":"2023-10-16T14:03:29.159602Z","shell.execute_reply":"2023-10-16T14:03:29.189607Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Merging train_series and train_events dataframes","metadata":{}},{"cell_type":"code","source":"merged_data = pd.merge(train_series, train_events, on=['series_id', 'date', 'time'], how='inner')","metadata":{"execution":{"iopub.status.busy":"2023-10-16T14:03:29.192941Z","iopub.execute_input":"2023-10-16T14:03:29.193295Z","iopub.status.idle":"2023-10-16T14:05:01.439906Z","shell.execute_reply.started":"2023-10-16T14:03:29.193265Z","shell.execute_reply":"2023-10-16T14:05:01.438732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"merged_data=merged_data.drop(['timestamp_x','timestamp_y','step_y'],axis=1)","metadata":{"execution":{"iopub.status.busy":"2023-10-16T14:05:01.441255Z","iopub.execute_input":"2023-10-16T14:05:01.442037Z","iopub.status.idle":"2023-10-16T14:05:01.448116Z","shell.execute_reply.started":"2023-10-16T14:05:01.442008Z","shell.execute_reply":"2023-10-16T14:05:01.447126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"merged_data","metadata":{"execution":{"iopub.status.busy":"2023-10-16T14:05:01.449390Z","iopub.execute_input":"2023-10-16T14:05:01.449786Z","iopub.status.idle":"2023-10-16T14:05:01.473007Z","shell.execute_reply.started":"2023-10-16T14:05:01.449749Z","shell.execute_reply":"2023-10-16T14:05:01.471882Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Spliting Time into hour, minute and seconds","metadata":{}},{"cell_type":"code","source":"merged_data['hour'] = pd.to_datetime(merged_data['time'], format='%H:%M:%S').dt.hour\nmerged_data['minute'] = pd.to_datetime(merged_data['time'], format='%H:%M:%S').dt.minute\nmerged_data['second'] = pd.to_datetime(merged_data['time'], format='%H:%M:%S').dt.second","metadata":{"execution":{"iopub.status.busy":"2023-10-16T14:05:01.474152Z","iopub.execute_input":"2023-10-16T14:05:01.474795Z","iopub.status.idle":"2023-10-16T14:05:01.507121Z","shell.execute_reply.started":"2023-10-16T14:05:01.474768Z","shell.execute_reply":"2023-10-16T14:05:01.506034Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Applying LSTM Model on the Merged data","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder\nfrom keras.models import Sequential\nfrom keras.layers import LSTM, Dense\nfrom keras.utils import to_categorical\n\ndata = merged_data\n\nlabel_encoder = LabelEncoder()\ndata['event'] = label_encoder.fit_transform(data['event'])\nnum_classes = len(label_encoder.classes_)\n\nX = data[['step_x', 'anglez', 'enmo', 'night', 'hour', 'minute', 'second']].values\ny = to_categorical(data['event'], num_classes=num_classes)\n\nscaler = StandardScaler()\nX = scaler.fit_transform(X)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\nX_train = X_train.reshape(X_train.shape[0], 1, X_train.shape[1])\nX_test = X_test.reshape(X_test.shape[0], 1, X_test.shape[1])\n\nmodel = Sequential()\n\nmodel.add(LSTM(64, input_shape=(X_train.shape[1], X_train.shape[2])))\nmodel.add(Dense(num_classes, activation='softmax'))\n\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\nmodel.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=32)\n\nloss, accuracy = model.evaluate(X_test, y_test)\nprint(f'Test Loss: {loss}, Test Accuracy: {accuracy}')\n","metadata":{"execution":{"iopub.status.busy":"2023-10-16T14:05:01.508489Z","iopub.execute_input":"2023-10-16T14:05:01.508820Z","iopub.status.idle":"2023-10-16T14:05:20.262071Z","shell.execute_reply.started":"2023-10-16T14:05:01.508793Z","shell.execute_reply":"2023-10-16T14:05:20.260884Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}}]}