Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- AI for Sleep Detection EDA.ipynb +0 -0
- app.py +178 -0
AI for Sleep Detection EDA.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
app.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
""")
|