{"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":"markdown","source":"<div style=\"background-color:#1877F2; padding:20px; text-align:center; font-size:24px; color:white;\">\n    💤😴 Detect Sleep States 😴💤\n</div>","metadata":{}},{"cell_type":"markdown","source":"# <span style=\"color:#1877F2\">Import libraries📲</span>","metadata":{}},{"cell_type":"code","source":"!pip install -q tensorflow_decision_forests==1.4.0\n!pip install -q seaborn","metadata":{"execution":{"iopub.status.busy":"2023-09-16T15:09:29.632347Z","iopub.execute_input":"2023-09-16T15:09:29.634733Z","iopub.status.idle":"2023-09-16T15:10:00.489630Z","shell.execute_reply.started":"2023-09-16T15:09:29.634667Z","shell.execute_reply":"2023-09-16T15:10:00.487506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nimport tensorflow_decision_forests as tfdf\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\nimport math\nimport warnings\nwarnings.filterwarnings(\"ignore\")\ncustom_palette = blue_palette = [\n    \"#0000FF\",  # Deep Blue\n    \"#87CEEB\",  # Sky Blue\n    \"#007BA7\",  # Cerulean Blue\n    \"#000080\",  # Navy Blue\n    \"#4169E1\",  # Royal Blue\n    \"#008080\",  # Teal Blue\n    \"#40E0D0\",  # Turquoise\n    \"#89CFF0\",  # Baby Blue\n    \"#CCCCFF\",  # Periwinkle\n    \"#6A5ACD\"   # Slate Blue\n]\nsns.set_palette(custom_palette)\nsns.set(style=\"whitegrid\", font_scale=1.2, palette=custom_palette)\npd.set_option('display.float_format', lambda x: '{:.3f}'.format(x)) #Limiting floats output to 3 decimal points\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2023-09-16T15:10:00.492640Z","iopub.execute_input":"2023-09-16T15:10:00.493173Z","iopub.status.idle":"2023-09-16T15:10:00.514621Z","shell.execute_reply.started":"2023-09-16T15:10:00.493123Z","shell.execute_reply":"2023-09-16T15:10:00.512070Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span style=\"color:#1877F2\">Show files🗂️</span>","metadata":{}},{"cell_type":"code","source":"# show files\n!ls -l '../input/child-mind-institute-detect-sleep-states'","metadata":{"execution":{"iopub.status.busy":"2023-09-16T15:10:00.517038Z","iopub.execute_input":"2023-09-16T15:10:00.517990Z","iopub.status.idle":"2023-09-16T15:10:01.730488Z","shell.execute_reply.started":"2023-09-16T15:10:00.517946Z","shell.execute_reply":"2023-09-16T15:10:01.728694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span style=\"color:#1877F2\">Read the dataset📖🤓</span>","metadata":{}},{"cell_type":"code","source":"# read parquet data\ndf = pd.read_csv('/kaggle/input/child-mind-institute-detect-sleep-states/train_events.csv')","metadata":{"execution":{"iopub.status.busy":"2023-09-16T15:10:01.734044Z","iopub.execute_input":"2023-09-16T15:10:01.734884Z","iopub.status.idle":"2023-09-16T15:10:01.781994Z","shell.execute_reply.started":"2023-09-16T15:10:01.734834Z","shell.execute_reply":"2023-09-16T15:10:01.780498Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span style=\"color:#1877F2\">Analyze Data🧐</span>","metadata":{}},{"cell_type":"markdown","source":"## <span style=\"color:#1877F2\">Event Occurrence Over Time","metadata":{}},{"cell_type":"code","source":"# Convert timestamp to datetime with UTC\ndf['timestamp'] = pd.to_datetime(df['timestamp'], utc=True)\n\n# Create a time series plot of events over time\nplt.figure(figsize=(12, 6))\nsns.lineplot(\n    data=df,\n    x='timestamp',\n    y=df.groupby('event').cumcount() + 1,\n    hue='event',\n    style='event',\n    markers=True\n)\n\nplt.xlabel('Timestamp', fontsize=14)\nplt.ylabel('Count', fontsize=14)\nplt.title('Event Occurrence Over Time', fontsize=16)\nplt.xticks(fontsize=12)\nplt.yticks(fontsize=12)\nplt.legend(title='Event Type', fontsize=12)\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-09-16T15:10:01.784140Z","iopub.execute_input":"2023-09-16T15:10:01.784568Z","iopub.status.idle":"2023-09-16T15:10:17.323026Z","shell.execute_reply.started":"2023-09-16T15:10:01.784532Z","shell.execute_reply":"2023-09-16T15:10:17.321408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## <span style=\"color:#1877F2\">Distribution of Nights and Steps","metadata":{}},{"cell_type":"code","source":"fig, axes = plt.subplots(1, 2, figsize=(16, 6))\n\nsns.histplot(data=df, x='night', bins=20, kde=True, color='skyblue', ax=axes[0])\naxes[0].set_xlabel('Night', fontsize=14)\naxes[0].set_ylabel('Frequency', fontsize=14)\naxes[0].set_title('Distribution of Nights', fontsize=16)\naxes[0].tick_params(axis='both', labelsize=12)\naxes[0].grid(axis='y', linestyle='--', alpha=0.7)\n\nsns.histplot(data=df, x='step', bins=20, kde=True, color='skyblue', ax=axes[1])\naxes[1].set_xlabel('Step', fontsize=14)\naxes[1].set_ylabel('Frequency', fontsize=14)\naxes[1].set_title('Distribution of Steps', fontsize=16)\naxes[1].tick_params(axis='both', labelsize=12)\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-16T15:10:17.324503Z","iopub.execute_input":"2023-09-16T15:10:17.325002Z","iopub.status.idle":"2023-09-16T15:10:18.719922Z","shell.execute_reply.started":"2023-09-16T15:10:17.324968Z","shell.execute_reply":"2023-09-16T15:10:18.718838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## <span style=\"color:#1877F2\">Event Type Distribution","metadata":{}},{"cell_type":"code","source":"event_counts = df['event'].value_counts()\n\nplt.figure()\nsns.barplot(x=event_counts.index, y=event_counts.values, palette=\"Blues_d\")\nplt.xlabel('Event Type', fontsize=14)\nplt.ylabel('Count', fontsize=14)\nplt.title('Distribution of Event Types', fontsize=16)\nplt.xticks(fontsize=12, rotation=45)  # Rotate x-axis labels for better readability\nplt.yticks(fontsize=12)\n\n# Add counts on top of the bars\nfor i, count in enumerate(event_counts.values):\n    plt.text(i, count + 20, str(count), ha='center', fontsize=12, color='black')\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-16T15:10:18.721076Z","iopub.execute_input":"2023-09-16T15:10:18.721405Z","iopub.status.idle":"2023-09-16T15:10:19.038662Z","shell.execute_reply.started":"2023-09-16T15:10:18.721365Z","shell.execute_reply":"2023-09-16T15:10:19.036830Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import gc\ngc.collect()\n\ndel event_counts\ndel df\ndel custom_palette","metadata":{"execution":{"iopub.status.busy":"2023-09-16T15:10:19.040736Z","iopub.execute_input":"2023-09-16T15:10:19.041422Z","iopub.status.idle":"2023-09-16T15:10:19.525436Z","shell.execute_reply.started":"2023-09-16T15:10:19.041375Z","shell.execute_reply":"2023-09-16T15:10:19.523883Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## <span style=\"color:#1877F2\"> Load Test & Train🏋️","metadata":{}},{"cell_type":"code","source":"train = pd.read_parquet(\"/kaggle/input/detect-sleep-statets-with-step-col/train.parquet\")\ntest = pd.read_parquet(\"/kaggle/input/detect-sleep-statets-with-step-col/test.parquet\")","metadata":{"execution":{"iopub.status.busy":"2023-09-16T15:10:19.527725Z","iopub.execute_input":"2023-09-16T15:10:19.528664Z","iopub.status.idle":"2023-09-16T15:10:39.585406Z","shell.execute_reply.started":"2023-09-16T15:10:19.528620Z","shell.execute_reply":"2023-09-16T15:10:39.583996Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## <span style=\"color:#1877F2\"> TensorFlow Decision Forests🌳","metadata":{}},{"cell_type":"markdown","source":" <span style=\"color:#1877F2\"> Note:Given the substantial volume of data, even with the utilization of TPUs, it remains challenging to allocate sufficient memory.","metadata":{}},{"cell_type":"code","source":"def split_dataset(dataset, test_ratio=0.30):\n  test_indices = np.random.rand(len(dataset)) < test_ratio\n  return dataset[~test_indices], dataset[test_indices]\n\n\ntrain_ds_pd, valid_ds_pd = split_dataset(train)\nprint(\"{} examples in training, {} examples in testing.\".format(\n    len(train_ds_pd), len(valid_ds_pd)))","metadata":{"execution":{"iopub.status.busy":"2023-09-16T15:10:39.589435Z","iopub.execute_input":"2023-09-16T15:10:39.589871Z","iopub.status.idle":"2023-09-16T15:10:57.134853Z","shell.execute_reply.started":"2023-09-16T15:10:39.589831Z","shell.execute_reply":"2023-09-16T15:10:57.131364Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label = 'event'\ntrain_ds = tfdf.keras.pd_dataframe_to_tf_dataset(train_ds_pd, label=label, task = tfdf.keras.Task.CLASSIFICATION)\nvalid_ds = tfdf.keras.pd_dataframe_to_tf_dataset(valid_ds_pd, label=label, task = tfdf.keras.Task.CLASSIFICATION)","metadata":{"execution":{"iopub.status.busy":"2023-09-16T15:10:57.137459Z","iopub.execute_input":"2023-09-16T15:10:57.137842Z","iopub.status.idle":"2023-09-16T15:12:51.412726Z","shell.execute_reply.started":"2023-09-16T15:10:57.137810Z","shell.execute_reply":"2023-09-16T15:12:51.410602Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tfdf.keras.get_all_models()","metadata":{"execution":{"iopub.status.busy":"2023-09-16T15:12:51.415529Z","iopub.execute_input":"2023-09-16T15:12:51.416114Z","iopub.status.idle":"2023-09-16T15:12:51.428259Z","shell.execute_reply.started":"2023-09-16T15:12:51.416063Z","shell.execute_reply":"2023-09-16T15:12:51.427049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rf = tfdf.keras.RandomForestModel()\nrf.compile(metrics=[\"precision\"])","metadata":{"execution":{"iopub.status.busy":"2023-09-16T15:12:51.429674Z","iopub.execute_input":"2023-09-16T15:12:51.430073Z","iopub.status.idle":"2023-09-16T15:12:51.592095Z","shell.execute_reply.started":"2023-09-16T15:12:51.430043Z","shell.execute_reply":"2023-09-16T15:12:51.590925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rf.fit(x=train_ds)","metadata":{"execution":{"iopub.status.busy":"2023-09-16T15:12:51.593912Z","iopub.execute_input":"2023-09-16T15:12:51.594634Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tfdf.model_plotter.plot_model_in_colab(rf, tree_idx=0, max_depth=1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ds = tfdf.keras.pd_dataframe_to_tf_dataset(\n    test,\n    task = tfdf.keras.Task.CLASSIFICATION)\n\n\ntest_ds = tfdf.keras.pd_dataframe_to_tf_dataset(\n    test,\n    task = tfdf.keras.Task.CLASSIFICATION)\n\npreds = rf.predict(test_ds)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"importance_metrics = [\"SUM_SCORE\", \"INV_MEAN_MIN_DEPTH\", \"NUM_NODES\", \"NUM_AS_ROOT\"]\ninspector = rf.make_inspector()\ninspector.evaluation()\nimportances = inspector.variable_importances()\n# Define the number of top variables to visualize\ntop_variables_count = 4\n\n# Create a 2x2 grid of subplots with improved styling\nfig, axes = plt.subplots(2, 2, figsize=(14, 10))\nfig.suptitle(\"Variable Importances for Different Metrics\", fontsize=16)\n\n# Iterate through importance metrics and plot in subplots\nfor i, importance_metric in enumerate(importance_metrics):\n    # Extract the feature names and importance values for the current metric\n    variable_importances = importances[importance_metric]\n    \n    # Sort by importance values and select the top 12 variables\n    variable_importances.sort(key=lambda x: x[1], reverse=True)\n    top_variable_importances = variable_importances[:top_variables_count]\n    \n    feature_names = [vi[0].name for vi in top_variable_importances]\n    feature_importances = [vi[1] for vi in top_variable_importances]\n    \n    # Determine the row and column for the current subplot\n    row = i // 2\n    col = i % 2\n\n    # Create a bar chart for the current metric in the specified subplot with improved styling\n    axes[row, col].barh(feature_names, feature_importances)\n    axes[row, col].invert_yaxis()\n    axes[row, col].set_xlabel(\"Importance Score\")\n    axes[row, col].set_title(f\"Top {top_variables_count} Variables for {importance_metric}\", fontsize=12)\n\n    # Add labels to the bars\n    for idx, importance in enumerate(feature_importances):\n        axes[row, col].text(importance, idx, f\"{importance:.4f}\", va='center', fontsize=10, color='black')\n\nplt.tight_layout(pad=3.0)\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    result_df = test.copy()  # Copy the test DataFrame\n    result_df['Score'] = preds\n    result_df.to_parquet(\"Score.parquet\",index=False)\nexcept Exception as e:\n    print(\"Error saving\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_submission_df = pd.read_csv('/kaggle/input/child-mind-institute-detect-sleep-states/sample_submission.csv')\nsample_submission_df['Score'] = rf.predict(test_ds)\nsample_submission_df.to_csv('/kaggle/working/submission.csv', index=False)\nsample_submission_df.head()","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":" <div style=\"border:#283618 2px solid ; background-color: #FEFAE0; padding: 20px;\">\n<font face=\"Pacifico\" color=\"#606C38\" size=\"5\"><b>If you find value in this notebook, I would greatly appreciate it if you could consider giving it a like, following me for more updates, and sharing it with others who might also benefit from it.</b></font>\n\n<font face=\"Pacifico\" color=\"#DDA15E\" size=\"4\"><i>Your support means a lot to me and helps me continue sharing insights and knowledge within the Kaggle community.</i></font>\n\n    \n<font face=\"Pacifico\" color=\"#BC6C25\" size=\"4\"><b>Thank you!</b></font>\n</div>","metadata":{}}]}