DasariHarshitha commited on
Commit
8e04d64
Β·
verified Β·
1 Parent(s): 6d49849

Upload 8 files

Browse files
AI%20for%20Sleep%20Detection%20EDA%20.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
app (1).py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pickle
3
+ import numpy as np
4
+ import pandas as pd
5
+ import matplotlib.pyplot as plt
6
+ import seaborn as sns
7
+
8
+ # ----------- Page Configuration ------------
9
+ st.set_page_config("Sleep State Detection", layout="wide")
10
+ st.title(" Sleep State Detection App")
11
+
12
+ # ----------- Navigation Sidebar ------------
13
+ page = st.sidebar.radio("πŸ“ Navigation", ["Overview", "EDA", "Predict"])
14
+
15
+ # ----------- Load Data & Model ------------
16
+ @st.cache_data
17
+ def load_data(filepath):
18
+ return pd.read_csv(filepath)
19
+
20
+ @st.cache_data
21
+ def load_model(filepath):
22
+ with open(filepath, "rb") as f:
23
+ return pickle.load(f)
24
+
25
+ # ----------- Histogram Plot Function ------------
26
+ def plot_histogram(df, column, color):
27
+ fig, ax = plt.subplots()
28
+ sns.histplot(df[column], bins=30, kde=True, color=color, ax=ax)
29
+ ax.set_title(f"Distribution of {column}")
30
+ st.pyplot(fig, use_container_width=True)
31
+ plt.close()
32
+
33
+ # ----------- Overview Page ------------
34
+ if page == "Overview":
35
+ st.header(" Project Overview")
36
+ st.markdown("This app detects **sleep onset** and **wake-up states** using `anglez` and `enmo` values from a wearable sensor.")
37
+
38
+ with st.expander(" Problem Statement"):
39
+ st.markdown("""
40
+ - Detect sleep and wake-up periods using wearable sensor data.
41
+ - Sleep is estimated from low-movement patterns.
42
+ """)
43
+
44
+ with st.expander(" Objective"):
45
+ st.markdown("""
46
+ - Classify sleep vs wake states
47
+ - Build an ML model that generalizes to real users
48
+ """)
49
+
50
+ with st.expander(" Constraints"):
51
+ st.markdown("""
52
+ - Missing or noisy data
53
+ - Ensure low false alarms
54
+ - Simple, real-time capable models
55
+ """)
56
+
57
+ # ----------- EDA Page ------------
58
+ elif page == "EDA":
59
+ st.header(" Exploratory Data Analysis")
60
+ df = load_data("cleaned_sleep_data.csv")
61
+
62
+ # ---- Multi-select Filter Sleep/Wake ----
63
+ st.markdown("### πŸ”Ž Filter by Sleep State")
64
+ state_options = st.multiselect("Select sleep states to display", ["Sleep", "Wake-Up"], default=["Sleep", "Wake-Up"])
65
+
66
+ if state_options:
67
+ filter_map = {"Sleep": 1, "Wake-Up": 0}
68
+ selected_values = [filter_map[opt] for opt in state_options]
69
+ df = df[df["sleep"].isin(selected_values)]
70
+
71
+ # ---- Histograms ----
72
+ col1, col2 = st.columns(2)
73
+ with col1:
74
+ st.subheader(" Anglez")
75
+ plot_histogram(df, "anglez", "#74b9ff")
76
+ st.markdown("- Distribution typical of rest posture")
77
+
78
+ with col2:
79
+ st.subheader(" ENMO")
80
+ plot_histogram(df, "enmo", "#81ecec")
81
+ st.markdown("- ENMO reflects movement intensity")
82
+
83
+ # ---- Pairplot ----
84
+ st.subheader(" Feature Relationships")
85
+ with st.spinner("Creating pairplot..."):
86
+ pairplot_fig = sns.pairplot(df, vars=['anglez', 'enmo'], hue='sleep', palette='coolwarm')
87
+ st.pyplot(pairplot_fig.fig, use_container_width=True)
88
+ plt.close()
89
+
90
+ # ---- Boxplots ----
91
+ st.subheader(" Boxplots")
92
+ fig, axs = plt.subplots(1, 2, figsize=(12, 5))
93
+ sns.boxplot(y=df["anglez"], ax=axs[0], color='#74b9ff')
94
+ axs[0].set_title("Boxplot: Anglez")
95
+ sns.boxplot(y=df["enmo"], ax=axs[1], color='#81ecec')
96
+ axs[1].set_title("Boxplot: ENMO")
97
+ st.pyplot(fig, use_container_width=True)
98
+ plt.close()
99
+
100
+ # ---- Correlation ----
101
+ st.subheader(" Correlation Heatmap")
102
+ fig, ax = plt.subplots()
103
+ sns.heatmap(df[["anglez", "enmo"]].corr(), annot=True, cmap="coolwarm", ax=ax)
104
+ st.pyplot(fig, use_container_width=True)
105
+ plt.close()
106
+
107
+ # ----------- Predict Page ------------
108
+ elif page == "Predict":
109
+ st.header(" Sleep Prediction")
110
+ model = load_model("new_sleep_model.pkl")
111
+
112
+ # ---- Sleep/Wake Filter Dropdown
113
+ st.markdown("### Select Sample Type")
114
+ state_choice = st.selectbox("Choose Sample Type", ["Custom Input", "Sleep Sample", "Wake-Up Sample"])
115
+
116
+ # ---- Default Values Based on Choice
117
+ if state_choice == "Sleep Sample":
118
+ default_anglez = -45.0
119
+ default_enmo = 0.01
120
+ elif state_choice == "Wake-Up Sample":
121
+ default_anglez = 20.0
122
+ default_enmo = 0.2
123
+ else:
124
+ default_anglez = 0.0
125
+ default_enmo = 0.0
126
+
127
+ # ---- Input Sliders
128
+ col1, col2 = st.columns(2)
129
+ with col1:
130
+ anglez = st.slider(" Anglez (-180Β° to 180Β°)", -180.0, 180.0, default_anglez)
131
+ with col2:
132
+ enmo = st.slider(" ENMO (0.0 to 1.0)", 0.0, 1.0, default_enmo)
133
+
134
+ # ---- Prediction
135
+ if st.button(" Predict Sleep State"):
136
+ input_vector = np.array([[anglez, enmo]])
137
+ prediction = model.predict(input_vector)[0]
138
+
139
+ if hasattr(model, "predict_proba"):
140
+ proba = model.predict_proba(input_vector)[0]
141
+ confidence = round(np.max(proba) * 100, 2)
142
+ st.metric(" Model Confidence", f"{confidence}%")
143
+
144
+ labels = {
145
+ 0: (" Wake-Up", "You're likely **awake** β€” motion and posture detected."),
146
+ 1: (" Sleep Onset", "Low motion detected β€” you may be **falling asleep**.")
147
+ }
148
+
149
+ label, message = labels.get(prediction, ("❓ Unknown", "⚠️ No clear state detected."))
150
+ st.success(f"** Predicted State:** {label}")
151
+ st.info(message)
152
+
153
+ # Display image based on prediction
154
+ if prediction == 1:
155
+ st.image(
156
+ "https://huggingface.co/spaces/Saidee156/AI_SLEEP_DETECTION/resolve/main/th%20(1).jpeg",
157
+ use_container_width=True,
158
+ )
159
+ st.markdown("""
160
+ ### Personalized Sleep Tips
161
+ **Tips to Fall Asleep Faster**
162
+ - Avoid screens 30 mins before bed
163
+ - Keep the room cool and dark
164
+ - Try deep breathing or meditation
165
+ - Stick to a regular sleep schedule
166
+ """)
167
+ else:
168
+ st.image(
169
+ "https://huggingface.co/spaces/Saidee156/AI_SLEEP_DETECTION/resolve/main/cute-little-boy-wake-up-in-morning-stretching-hands-on-bed-in-bedroom-vector.jpg",
170
+ use_container_width=True,
171
+ )
172
+ st.markdown("""
173
+ ### Tips to Wake Up Refreshed
174
+ - Get morning sunlight exposure
175
+ - Move or stretch your body
176
+ - Eat a light, energizing breakfast
177
+ - Cold water splash or shower helps
178
+ """)
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+
187
+
188
+
cleaned_sleep_data.csv ADDED
The diff for this file is too large to render. See raw diff
 
cute-little-boy-wake-up-in-morning-stretching-hands-on-bed-in-bedroom-vector.jpg ADDED
model.ipynb ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "50ddcbd1",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import pickle"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": 2,
16
+ "id": "9a90403c",
17
+ "metadata": {},
18
+ "outputs": [
19
+ {
20
+ "name": "stderr",
21
+ "output_type": "stream",
22
+ "text": [
23
+ "C:\\Users\\deekshi\\AppData\\Local\\Temp\\ipykernel_31352\\4176903524.py:2: UserWarning: [16:57:16] WARNING: C:\\actions-runner\\_work\\xgboost\\xgboost\\src\\data\\../common/error_msg.h:82: If you are loading a serialized model (like pickle in Python, RDS in R) or\n",
24
+ "configuration generated by an older version of XGBoost, please export the model by calling\n",
25
+ "`Booster.save_model` from that version first, then load it back in current version. See:\n",
26
+ "\n",
27
+ " https://xgboost.readthedocs.io/en/stable/tutorials/saving_model.html\n",
28
+ "\n",
29
+ "for more details about differences between saving model and serializing.\n",
30
+ "\n",
31
+ " model = pickle.load(f)\n"
32
+ ]
33
+ }
34
+ ],
35
+ "source": [
36
+ "with open(\"xgboost_sleep_model.pkl\",'rb') as f:\n",
37
+ " model = pickle.load(f)"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": 3,
43
+ "id": "eaabe4bf",
44
+ "metadata": {},
45
+ "outputs": [
46
+ {
47
+ "name": "stdout",
48
+ "output_type": "stream",
49
+ "text": [
50
+ "Requirement already satisfied: pandas in d:\\anaconda\\lib\\site-packages (2.2.2)\n",
51
+ "Requirement already satisfied: scikit-learn in d:\\anaconda\\lib\\site-packages (1.4.2)\n",
52
+ "Requirement already satisfied: xgboost in d:\\anaconda\\lib\\site-packages (3.0.0)\n",
53
+ "Requirement already satisfied: openpyxl in d:\\anaconda\\lib\\site-packages (3.1.2)\n",
54
+ "Requirement already satisfied: numpy>=1.26.0 in d:\\anaconda\\lib\\site-packages (from pandas) (1.26.4)\n",
55
+ "Requirement already satisfied: python-dateutil>=2.8.2 in d:\\anaconda\\lib\\site-packages (from pandas) (2.9.0.post0)\n",
56
+ "Requirement already satisfied: pytz>=2020.1 in d:\\anaconda\\lib\\site-packages (from pandas) (2024.1)\n",
57
+ "Requirement already satisfied: tzdata>=2022.7 in d:\\anaconda\\lib\\site-packages (from pandas) (2023.3)\n",
58
+ "Requirement already satisfied: scipy>=1.6.0 in d:\\anaconda\\lib\\site-packages (from scikit-learn) (1.13.1)\n",
59
+ "Requirement already satisfied: joblib>=1.2.0 in d:\\anaconda\\lib\\site-packages (from scikit-learn) (1.4.2)\n",
60
+ "Requirement already satisfied: threadpoolctl>=2.0.0 in d:\\anaconda\\lib\\site-packages (from scikit-learn) (2.2.0)\n",
61
+ "Requirement already satisfied: et-xmlfile in d:\\anaconda\\lib\\site-packages (from openpyxl) (1.1.0)\n",
62
+ "Requirement already satisfied: six>=1.5 in d:\\anaconda\\lib\\site-packages (from python-dateutil>=2.8.2->pandas) (1.16.0)\n",
63
+ "Note: you may need to restart the kernel to use updated packages.\n"
64
+ ]
65
+ }
66
+ ],
67
+ "source": [
68
+ "pip install pandas scikit-learn xgboost openpyxl\n"
69
+ ]
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "execution_count": 15,
74
+ "id": "ca8672ba",
75
+ "metadata": {},
76
+ "outputs": [
77
+ {
78
+ "name": "stdout",
79
+ "output_type": "stream",
80
+ "text": [
81
+ "βœ… Accuracy: 0.5952008346374543\n",
82
+ "πŸŽ‰ Model saved successfully as 'new_sleep_model.pkl'\n"
83
+ ]
84
+ }
85
+ ],
86
+ "source": [
87
+ "import pandas as pd\n",
88
+ "import xgboost as xgb\n",
89
+ "from sklearn.model_selection import train_test_split\n",
90
+ "from sklearn.metrics import accuracy_score\n",
91
+ "import pickle\n",
92
+ "\n",
93
+ "# βœ… Step 1: Load the cleaned CSV file\n",
94
+ "df = pd.read_csv(r\"D:\\Child_sleep_detect\\cleaned_sleep_data.csv\")\n",
95
+ "\n",
96
+ "# βœ… Step 2: Drop missing values\n",
97
+ "df.dropna(inplace=True)\n",
98
+ "\n",
99
+ "# βœ… Step 3: Define features and target\n",
100
+ "X = df[['anglez', 'enmo']]\n",
101
+ "\n",
102
+ "# βœ… Step 4: Manually encode 'sleep' column ('onset' = 0, 'wakeup' = 1)\n",
103
+ "y = df['sleep'].map({'onset': 0, 'wakeup': 1})\n",
104
+ "\n",
105
+ "# βœ… Step 5: Train-test split\n",
106
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
107
+ "\n",
108
+ "# βœ… Step 6: Train XGBoost classifier\n",
109
+ "model = xgb.XGBClassifier()\n",
110
+ "model.fit(X_train, y_train)\n",
111
+ "\n",
112
+ "# βœ… Step 7: Evaluate the model\n",
113
+ "y_pred = model.predict(X_test)\n",
114
+ "acc = accuracy_score(y_test, y_pred)\n",
115
+ "print(\"βœ… Accuracy:\", acc)\n",
116
+ "\n",
117
+ "# βœ… Step 8: Save the model\n",
118
+ "with open(\"new_sleep_model.pkl\", \"wb\") as f:\n",
119
+ " pickle.dump(model, f)\n",
120
+ "\n",
121
+ "print(\"πŸŽ‰ Model saved successfully as 'new_sleep_model.pkl'\")\n",
122
+ "\n"
123
+ ]
124
+ },
125
+ {
126
+ "cell_type": "code",
127
+ "execution_count": 16,
128
+ "id": "7c079ac3",
129
+ "metadata": {},
130
+ "outputs": [
131
+ {
132
+ "data": {
133
+ "text/plain": [
134
+ "0 0\n",
135
+ "1 1\n",
136
+ "2 0\n",
137
+ "3 1\n",
138
+ "4 0\n",
139
+ " ..\n",
140
+ "9580 1\n",
141
+ "9581 0\n",
142
+ "9582 1\n",
143
+ "9583 0\n",
144
+ "9584 1\n",
145
+ "Name: sleep, Length: 9585, dtype: int64"
146
+ ]
147
+ },
148
+ "execution_count": 16,
149
+ "metadata": {},
150
+ "output_type": "execute_result"
151
+ }
152
+ ],
153
+ "source": [
154
+ "y"
155
+ ]
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "execution_count": null,
160
+ "id": "18a6341f",
161
+ "metadata": {},
162
+ "outputs": [],
163
+ "source": []
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "execution_count": null,
168
+ "id": "badf06a5",
169
+ "metadata": {},
170
+ "outputs": [],
171
+ "source": [
172
+ "\n"
173
+ ]
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "execution_count": null,
178
+ "id": "a4376d7c",
179
+ "metadata": {},
180
+ "outputs": [],
181
+ "source": [
182
+ "\n"
183
+ ]
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "execution_count": null,
188
+ "id": "1752fabb",
189
+ "metadata": {},
190
+ "outputs": [],
191
+ "source": []
192
+ },
193
+ {
194
+ "cell_type": "code",
195
+ "execution_count": null,
196
+ "id": "77d9b049",
197
+ "metadata": {},
198
+ "outputs": [],
199
+ "source": []
200
+ },
201
+ {
202
+ "cell_type": "code",
203
+ "execution_count": null,
204
+ "id": "7104aff0",
205
+ "metadata": {},
206
+ "outputs": [],
207
+ "source": []
208
+ },
209
+ {
210
+ "cell_type": "code",
211
+ "execution_count": null,
212
+ "id": "91b3c488",
213
+ "metadata": {},
214
+ "outputs": [],
215
+ "source": []
216
+ },
217
+ {
218
+ "cell_type": "code",
219
+ "execution_count": null,
220
+ "id": "11a7572f",
221
+ "metadata": {},
222
+ "outputs": [],
223
+ "source": [
224
+ "\n"
225
+ ]
226
+ },
227
+ {
228
+ "cell_type": "code",
229
+ "execution_count": null,
230
+ "id": "dfe336dd",
231
+ "metadata": {},
232
+ "outputs": [],
233
+ "source": []
234
+ },
235
+ {
236
+ "cell_type": "code",
237
+ "execution_count": null,
238
+ "id": "b680af21",
239
+ "metadata": {},
240
+ "outputs": [],
241
+ "source": []
242
+ }
243
+ ],
244
+ "metadata": {
245
+ "kernelspec": {
246
+ "display_name": "base",
247
+ "language": "python",
248
+ "name": "python3"
249
+ },
250
+ "language_info": {
251
+ "codemirror_mode": {
252
+ "name": "ipython",
253
+ "version": 3
254
+ },
255
+ "file_extension": ".py",
256
+ "mimetype": "text/x-python",
257
+ "name": "python",
258
+ "nbconvert_exporter": "python",
259
+ "pygments_lexer": "ipython3",
260
+ "version": "3.12.4"
261
+ }
262
+ },
263
+ "nbformat": 4,
264
+ "nbformat_minor": 5
265
+ }
new_sleep_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2c5b88b36ce5376216cd51d57645dd901121345dde0ed426ec1744d10f54368c
3
+ size 301334
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ pandas
3
+ numpy
4
+ scikit-learn
5
+ xgboost
6
+ matplotlib
7
+ seaborn
th%20%281%29.jpeg ADDED