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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
language:
|
| 3 |
+
- en
|
| 4 |
license: mit
|
| 5 |
+
library_name: scikit-learn
|
| 6 |
+
tags:
|
| 7 |
+
- tabular-classification
|
| 8 |
+
- random-forest
|
| 9 |
+
- health
|
| 10 |
+
- lifestyle
|
| 11 |
+
- sleep-health
|
| 12 |
+
- healthcare
|
| 13 |
+
metrics:
|
| 14 |
+
- accuracy
|
| 15 |
+
- precision
|
| 16 |
+
- recall
|
| 17 |
+
- f1
|
| 18 |
+
model-index:
|
| 19 |
+
- name: sleep-health-lifestyle-classifier
|
| 20 |
+
results:
|
| 21 |
+
- task:
|
| 22 |
+
type: tabular-classification
|
| 23 |
+
name: Tabular Classification
|
| 24 |
+
metrics:
|
| 25 |
+
- name: Accuracy
|
| 26 |
+
type: accuracy
|
| 27 |
+
value: 1.00
|
| 28 |
+
- name: F1 Score
|
| 29 |
+
type: f1
|
| 30 |
+
value: 1.00
|
| 31 |
---
|
| 32 |
+
|
| 33 |
+
# Sleep Health & Lifestyle AI Classifier
|
| 34 |
+
|
| 35 |
+
A Scikit-Learn **Random Forest Classifier** wrapped in a self-contained pipeline to evaluate whether an individual maintains a **Healthy** (`1`) or **Unhealthy** (`0`) lifestyle based on sleep parameters, physical activity, stress levels, biometric vitals, and demographic factors.
|
| 36 |
+
|
| 37 |
+
Trained on the **Sleep Health and Lifestyle Dataset** and packaged for direct deployment and inference via Hugging Face Models.
|
| 38 |
+
|
| 39 |
+
---
|
| 40 |
+
|
| 41 |
+
## 🎯 Target Definition (`Is_Healthy`)
|
| 42 |
+
|
| 43 |
+
The model classifies individuals into two lifestyle health categories:
|
| 44 |
+
|
| 45 |
+
| Target Value | Class Label | Definition / Health Criteria |
|
| 46 |
+
| :---: | :---: | :--- |
|
| 47 |
+
| **`1`** | **Healthy Lifestyle** | Meets all baseline physiological lifestyle criteria:<br>• **Sleep Duration**: $\ge 7.0$ hours/night<br>• **Quality of Sleep**: $\ge 7$ (scale 1–10)<br>• **Physical Activity Level**: $\ge 60$ minutes/day<br>• **Stress Level**: $\le 5$ (scale 1–10) |
|
| 48 |
+
| **`0`** | **Unhealthy Lifestyle** | Fails to meet one or more healthy lifestyle criteria |
|
| 49 |
+
|
| 50 |
+
---
|
| 51 |
+
|
| 52 |
+
## 📊 Dataset & Feature Information
|
| 53 |
+
|
| 54 |
+
The dataset contains comprehensive lifestyle and physiological measurements. Identifiers (`Person ID`) and medical outcome diagnoses (`Sleep Disorder`) are omitted from model features, and `BMI Category` is excluded to avoid confounding subjective categories. Blood Pressure (`Blood Pressure`) is decomposed into numerical systolic and diastolic components.
|
| 55 |
+
|
| 56 |
+
### Input Features
|
| 57 |
+
|
| 58 |
+
| Feature | Data Type | Description | Example Values |
|
| 59 |
+
| :--- | :---: | :--- | :---: |
|
| 60 |
+
| **`Gender`** | Categorical | Biological sex | `Male`, `Female` |
|
| 61 |
+
| **`Age`** | Numerical (int) | Age in years | `30`, `45` |
|
| 62 |
+
| **`Occupation`** | Categorical | Primary profession | `Doctor`, `Engineer`, `Nurse`, `Teacher` |
|
| 63 |
+
| **`Sleep Duration`** | Numerical (float) | Average sleep duration in hours | `7.8`, `6.1` |
|
| 64 |
+
| **`Quality of Sleep`** | Numerical (int) | Subjective sleep rating (scale 1–10) | `8`, `4` |
|
| 65 |
+
| **`Physical Activity Level`** | Numerical (int) | Daily exercise / activity in minutes | `75`, `30` |
|
| 66 |
+
| **`Stress Level`** | Numerical (int) | Self-reported stress (scale 1–10) | `4`, `8` |
|
| 67 |
+
| **`Heart Rate`** | Numerical (int) | Resting heart rate in beats per minute (bpm) | `68`, `85` |
|
| 68 |
+
| **`Daily Steps`** | Numerical (int) | Number of steps walked daily | `8500`, `3200` |
|
| 69 |
+
| **`Systolic_BP`** | Numerical (int) | Systolic blood pressure (mmHg) | `120`, `140` |
|
| 70 |
+
| **`Diastolic_BP`** | Numerical (int) | Diastolic blood pressure (mmHg) | `80`, `90` |
|
| 71 |
+
|
| 72 |
+
---
|
| 73 |
+
|
| 74 |
+
## 📈 Model Performance & Evaluation
|
| 75 |
+
|
| 76 |
+
The model was trained and evaluated using a **stratified 80/20 train-test split** (`random_state=42`) with class balancing:
|
| 77 |
+
|
| 78 |
+
- **Accuracy Score**: `100.00%`
|
| 79 |
+
- **Balanced Class Distribution**:
|
| 80 |
+
- Unhealthy (`0`): 228 samples (61.0%)
|
| 81 |
+
- Healthy (`1`): 146 samples (39.0%)
|
| 82 |
+
|
| 83 |
+
### Classification Report (Holdout Test Set)
|
| 84 |
+
|
| 85 |
+
| Class | Precision | Recall | F1-Score | Support |
|
| 86 |
+
| :--- | :---: | :---: | :---: | :---: |
|
| 87 |
+
| **`0` (Unhealthy)** | 1.00 | 1.00 | 1.00 | 46 |
|
| 88 |
+
| **`1` (Healthy)** | 1.00 | 1.00 | 1.00 | 29 |
|
| 89 |
+
| **Overall Accuracy** | — | — | **1.00** | **75** |
|
| 90 |
+
| **Macro Average** | 1.00 | 1.00 | 1.00 | 75 |
|
| 91 |
+
| **Weighted Average** | 1.00 | 1.00 | 1.00 | 75 |
|
| 92 |
+
|
| 93 |
+
### Confusion Matrix
|
| 94 |
+
|
| 95 |
+
```
|
| 96 |
+
Predicted Unhealthy (0) Predicted Healthy (1)
|
| 97 |
+
Actual Unhealthy (0) 46 0
|
| 98 |
+
Actual Healthy (1) 0 29
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
---
|
| 102 |
+
|
| 103 |
+
## 🚀 Quickstart & Usage
|
| 104 |
+
|
| 105 |
+
### 1. Requirements
|
| 106 |
+
|
| 107 |
+
Install required dependencies:
|
| 108 |
+
|
| 109 |
+
```bash
|
| 110 |
+
pip install -r requirements.txt
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
*(or install directly: `pip install scikit-learn pandas joblib numpy`)*
|
| 114 |
+
|
| 115 |
+
### 2. Inference using `predict.py`
|
| 116 |
+
|
| 117 |
+
Run the included test script to verify predictions on diverse sample profiles:
|
| 118 |
+
|
| 119 |
+
```bash
|
| 120 |
+
python predict.py
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
### 3. Python Code Snippet
|
| 124 |
+
|
| 125 |
+
Load `lifestyle_model.pkl` and predict directly:
|
| 126 |
+
|
| 127 |
+
```python
|
| 128 |
+
import joblib
|
| 129 |
+
import pandas as pd
|
| 130 |
+
|
| 131 |
+
# Load the trained pipeline
|
| 132 |
+
model = joblib.load("lifestyle_model.pkl")
|
| 133 |
+
|
| 134 |
+
# Define input data (supports raw string categories)
|
| 135 |
+
sample_data = pd.DataFrame([
|
| 136 |
+
{
|
| 137 |
+
"Gender": "Male",
|
| 138 |
+
"Age": 30,
|
| 139 |
+
"Occupation": "Doctor",
|
| 140 |
+
"Sleep Duration": 7.8,
|
| 141 |
+
"Quality of Sleep": 8,
|
| 142 |
+
"Physical Activity Level": 75,
|
| 143 |
+
"Stress Level": 4,
|
| 144 |
+
"Heart Rate": 68,
|
| 145 |
+
"Daily Steps": 8500,
|
| 146 |
+
"Systolic_BP": 120,
|
| 147 |
+
"Diastolic_BP": 80,
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"Gender": "Male",
|
| 151 |
+
"Age": 28,
|
| 152 |
+
"Occupation": "Sales Representative",
|
| 153 |
+
"Sleep Duration": 5.9,
|
| 154 |
+
"Quality of Sleep": 4,
|
| 155 |
+
"Physical Activity Level": 30,
|
| 156 |
+
"Stress Level": 8,
|
| 157 |
+
"Heart Rate": 85,
|
| 158 |
+
"Daily Steps": 3000,
|
| 159 |
+
"Systolic_BP": 140,
|
| 160 |
+
"Diastolic_BP": 90,
|
| 161 |
+
}
|
| 162 |
+
])
|
| 163 |
+
|
| 164 |
+
# Predict class (0 = Unhealthy, 1 = Healthy)
|
| 165 |
+
predictions = model.predict(sample_data)
|
| 166 |
+
probabilities = model.predict_proba(sample_data)
|
| 167 |
+
|
| 168 |
+
labels = {0: "Unhealthy Lifestyle", 1: "Healthy Lifestyle"}
|
| 169 |
+
for i, pred in enumerate(predictions):
|
| 170 |
+
print(f"Sample {i + 1}: {labels[pred]} (Confidence: {probabilities[i][pred] * 100:.1f}%)")
|
| 171 |
+
```
|
| 172 |
+
|
| 173 |
+
### 4. Downloading from Hugging Face Hub
|
| 174 |
+
|
| 175 |
+
If hosting on Hugging Face Model Hub, download the model file directly with `huggingface_hub`:
|
| 176 |
+
|
| 177 |
+
```python
|
| 178 |
+
from huggingface_hub import hf_hub_download
|
| 179 |
+
import joblib
|
| 180 |
+
|
| 181 |
+
model_path = hf_hub_download(repo_id="<YOUR_USERNAME>/<YOUR_MODEL_REPO>", filename="lifestyle_model.pkl")
|
| 182 |
+
model = joblib.load(model_path)
|
| 183 |
+
```
|
| 184 |
+
|
| 185 |
+
---
|
| 186 |
+
|
| 187 |
+
## 📦 Uploading to Hugging Face Model Hub
|
| 188 |
+
|
| 189 |
+
To upload this model repository to the Hugging Face Model Hub (under **Models**):
|
| 190 |
+
|
| 191 |
+
```bash
|
| 192 |
+
# 1. Install Hugging Face Hub CLI and authenticate
|
| 193 |
+
pip install huggingface_hub
|
| 194 |
+
huggingface-cli login
|
| 195 |
+
|
| 196 |
+
# 2. Create the Model repository (under Models, NOT Spaces)
|
| 197 |
+
# Example via CLI or create directly at https://huggingface.co/new
|
| 198 |
+
|
| 199 |
+
# 3. Clone and copy files, or push directly via git:
|
| 200 |
+
git clone https://huggingface.co/<YOUR_USERNAME>/sleep-lifestyle-classifier
|
| 201 |
+
cd sleep-lifestyle-classifier
|
| 202 |
+
# Copy lifestyle_model.pkl, README.md, requirements.txt, predict.py, and train_model.py
|
| 203 |
+
git add .
|
| 204 |
+
git commit -m "Initial commit of Sleep Health & Lifestyle Classifier"
|
| 205 |
+
git push
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
---
|
| 209 |
+
|
| 210 |
+
## 📜 License
|
| 211 |
+
|
| 212 |
+
This project is licensed under the MIT License.
|
lifestyle_model.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:885ef43099ebd0a36efdba67e423c00cb49e9c5dff258df850ab01162745bd7d
|
| 3 |
+
size 151202
|
predict.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
predict.py
|
| 3 |
+
==========
|
| 4 |
+
Loads the trained Random Forest pipeline ('lifestyle_model.pkl') and performs
|
| 5 |
+
inference on user profiles to verify model predictions and confidence scores.
|
| 6 |
+
|
| 7 |
+
Supports:
|
| 8 |
+
1. Automated evaluation on 3 realistic benchmark user profiles:
|
| 9 |
+
- Clearly Healthy Lifestyle
|
| 10 |
+
- Clearly Unhealthy Lifestyle (low sleep & high stress)
|
| 11 |
+
- Borderline Case (near thresholds)
|
| 12 |
+
2. Interactive manual testing from the terminal (custom input).
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
import joblib
|
| 18 |
+
import pandas as pd
|
| 19 |
+
|
| 20 |
+
MODEL_PATH = "lifestyle_model.pkl"
|
| 21 |
+
|
| 22 |
+
LABEL_MAPPING = {
|
| 23 |
+
0: "Unhealthy Lifestyle",
|
| 24 |
+
1: "Healthy Lifestyle",
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def load_model(model_path: str = MODEL_PATH):
|
| 29 |
+
"""Loads and returns the saved joblib model pipeline."""
|
| 30 |
+
if not os.path.exists(model_path):
|
| 31 |
+
raise FileNotFoundError(
|
| 32 |
+
f"Model file '{model_path}' not found! Please run train_model.py first."
|
| 33 |
+
)
|
| 34 |
+
return joblib.load(model_path)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def prepare_input(data):
|
| 38 |
+
"""Normalizes input data (dict, list of dicts, or DataFrame) into the expected schema."""
|
| 39 |
+
if isinstance(data, dict):
|
| 40 |
+
df = pd.DataFrame([data])
|
| 41 |
+
elif isinstance(data, list):
|
| 42 |
+
df = pd.DataFrame(data)
|
| 43 |
+
elif isinstance(data, pd.DataFrame):
|
| 44 |
+
df = data.copy()
|
| 45 |
+
else:
|
| 46 |
+
raise ValueError("Unsupported input format. Provide dict, list of dicts, or DataFrame.")
|
| 47 |
+
|
| 48 |
+
# Split 'Blood Pressure' (e.g. '120/80') if provided as a single string
|
| 49 |
+
if "Blood Pressure" in df.columns:
|
| 50 |
+
if "Systolic_BP" not in df.columns or "Diastolic_BP" not in df.columns:
|
| 51 |
+
split_bp = df["Blood Pressure"].astype(str).str.split("/", expand=True)
|
| 52 |
+
df["Systolic_BP"] = split_bp[0].astype(int)
|
| 53 |
+
df["Diastolic_BP"] = split_bp[1].astype(int)
|
| 54 |
+
df = df.drop(columns=["Blood Pressure"])
|
| 55 |
+
|
| 56 |
+
required_features = [
|
| 57 |
+
"Gender",
|
| 58 |
+
"Age",
|
| 59 |
+
"Occupation",
|
| 60 |
+
"Sleep Duration",
|
| 61 |
+
"Quality of Sleep",
|
| 62 |
+
"Physical Activity Level",
|
| 63 |
+
"Stress Level",
|
| 64 |
+
"Heart Rate",
|
| 65 |
+
"Daily Steps",
|
| 66 |
+
"Systolic_BP",
|
| 67 |
+
"Diastolic_BP",
|
| 68 |
+
]
|
| 69 |
+
|
| 70 |
+
missing = [f for f in required_features if f not in df.columns]
|
| 71 |
+
if missing:
|
| 72 |
+
raise ValueError(f"Input is missing required features: {missing}")
|
| 73 |
+
|
| 74 |
+
return df[required_features]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def predict(input_data, model=None):
|
| 78 |
+
"""
|
| 79 |
+
Runs inference on input data and returns detailed predictions.
|
| 80 |
+
|
| 81 |
+
Parameters:
|
| 82 |
+
input_data (dict, list[dict], or pd.DataFrame): Samples to classify.
|
| 83 |
+
model: Optional pre-loaded model. If None, loads from MODEL_PATH.
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
pd.DataFrame: Original inputs augmented with Prediction, Label, and Confidence.
|
| 87 |
+
"""
|
| 88 |
+
if model is None:
|
| 89 |
+
model = load_model()
|
| 90 |
+
|
| 91 |
+
df_prepared = prepare_input(input_data)
|
| 92 |
+
preds = model.predict(df_prepared)
|
| 93 |
+
probs = model.predict_proba(df_prepared)
|
| 94 |
+
|
| 95 |
+
results = []
|
| 96 |
+
for i, pred in enumerate(preds):
|
| 97 |
+
confidence = probs[i][pred] * 100
|
| 98 |
+
results.append({
|
| 99 |
+
"Prediction": int(pred),
|
| 100 |
+
"Label": LABEL_MAPPING.get(int(pred), "Unknown"),
|
| 101 |
+
"Confidence": f"{confidence:.2f}%",
|
| 102 |
+
"Probability_Healthy": f"{probs[i][1]:.4f}",
|
| 103 |
+
"Probability_Unhealthy": f"{probs[i][0]:.4f}",
|
| 104 |
+
})
|
| 105 |
+
|
| 106 |
+
result_df = pd.concat([df_prepared.reset_index(drop=True), pd.DataFrame(results)], axis=1)
|
| 107 |
+
return result_df
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def print_prediction_card(profile_name: str, sample_dict: dict, res: pd.DataFrame):
|
| 111 |
+
"""Prints a structured summary card for a prediction."""
|
| 112 |
+
print("\n" + "-" * 70)
|
| 113 |
+
print(f"Profile: {profile_name}")
|
| 114 |
+
print("-" * 70)
|
| 115 |
+
for k, v in sample_dict.items():
|
| 116 |
+
print(f" {k:<24}: {v}")
|
| 117 |
+
|
| 118 |
+
pred_class = int(res["Prediction"].iloc[0])
|
| 119 |
+
pred_label = res["Label"].iloc[0]
|
| 120 |
+
confidence = res["Confidence"].iloc[0]
|
| 121 |
+
prob_healthy = res["Probability_Healthy"].iloc[0]
|
| 122 |
+
prob_unhealthy = res["Probability_Unhealthy"].iloc[0]
|
| 123 |
+
|
| 124 |
+
status_tag = "✅ HEALTHY" if pred_class == 1 else "⚠️ UNHEALTHY"
|
| 125 |
+
|
| 126 |
+
print("\nPrediction Result:")
|
| 127 |
+
print(f" Classification Outcome : {status_tag} - {pred_label} (Class {pred_class})")
|
| 128 |
+
print(f" Model Confidence : {confidence}")
|
| 129 |
+
print(f" Probability [Healthy] : {prob_healthy} ({float(prob_healthy)*100:.1f}%)")
|
| 130 |
+
print(f" Probability [Unhealthy] : {prob_unhealthy} ({float(prob_unhealthy)*100:.1f}%)")
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def run_benchmark_profiles(model):
|
| 134 |
+
"""Runs prediction on 3 predefined realistic test profiles."""
|
| 135 |
+
sample_profiles = [
|
| 136 |
+
{
|
| 137 |
+
"Profile": "1. Clearly Healthy Lifestyle (Optimal sleep, high activity, low stress)",
|
| 138 |
+
"Gender": "Female",
|
| 139 |
+
"Age": 34,
|
| 140 |
+
"Occupation": "Engineer",
|
| 141 |
+
"Sleep Duration": 7.8,
|
| 142 |
+
"Quality of Sleep": 8,
|
| 143 |
+
"Physical Activity Level": 75,
|
| 144 |
+
"Stress Level": 4,
|
| 145 |
+
"Heart Rate": 68,
|
| 146 |
+
"Daily Steps": 8500,
|
| 147 |
+
"Blood Pressure": "118/78",
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"Profile": "2. Clearly Unhealthy Lifestyle (Low sleep & high stress)",
|
| 151 |
+
"Gender": "Male",
|
| 152 |
+
"Age": 29,
|
| 153 |
+
"Occupation": "Sales Representative",
|
| 154 |
+
"Sleep Duration": 5.8,
|
| 155 |
+
"Quality of Sleep": 4,
|
| 156 |
+
"Physical Activity Level": 30,
|
| 157 |
+
"Stress Level": 8,
|
| 158 |
+
"Heart Rate": 86,
|
| 159 |
+
"Daily Steps": 3000,
|
| 160 |
+
"Blood Pressure": "140/90",
|
| 161 |
+
},
|
| 162 |
+
{
|
| 163 |
+
"Profile": "3. Borderline Case (Sleep 6.9 hrs - just 6 min short of 7.0h threshold)",
|
| 164 |
+
"Gender": "Male",
|
| 165 |
+
"Age": 32,
|
| 166 |
+
"Occupation": "Teacher",
|
| 167 |
+
"Sleep Duration": 6.9,
|
| 168 |
+
"Quality of Sleep": 7,
|
| 169 |
+
"Physical Activity Level": 60,
|
| 170 |
+
"Stress Level": 5,
|
| 171 |
+
"Heart Rate": 72,
|
| 172 |
+
"Daily Steps": 6000,
|
| 173 |
+
"Blood Pressure": "125/82",
|
| 174 |
+
},
|
| 175 |
+
]
|
| 176 |
+
|
| 177 |
+
for sample in sample_profiles:
|
| 178 |
+
profile_name = sample.pop("Profile")
|
| 179 |
+
sample_copy = sample.copy()
|
| 180 |
+
res = predict(sample, model=model)
|
| 181 |
+
print_prediction_card(profile_name, sample_copy, res)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def prompt_input(prompt_text, default_val, val_type=str):
|
| 185 |
+
"""Utility to prompt user with a default fallback."""
|
| 186 |
+
try:
|
| 187 |
+
user_val = input(f"{prompt_text} [{default_val}]: ").strip()
|
| 188 |
+
if not user_val:
|
| 189 |
+
return default_val
|
| 190 |
+
return val_type(user_val)
|
| 191 |
+
except (EOFError, KeyboardInterrupt):
|
| 192 |
+
return default_val
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def interactive_terminal_mode(model):
|
| 196 |
+
"""Allows manual custom input from the terminal."""
|
| 197 |
+
print("\n" + "=" * 70)
|
| 198 |
+
print(" 🛠️ Manual Interactive Testing Mode ")
|
| 199 |
+
print(" Enter custom lifestyle values (press Enter to accept default in brackets):")
|
| 200 |
+
print("=" * 70)
|
| 201 |
+
|
| 202 |
+
while True:
|
| 203 |
+
try:
|
| 204 |
+
gender = prompt_input(" Gender (Male/Female)", "Male", str)
|
| 205 |
+
age = prompt_input(" Age (years)", 30, int)
|
| 206 |
+
occupation = prompt_input(
|
| 207 |
+
" Occupation (e.g. Doctor, Engineer, Teacher, Nurse, Salesperson)",
|
| 208 |
+
"Software Engineer",
|
| 209 |
+
str,
|
| 210 |
+
)
|
| 211 |
+
sleep_duration = prompt_input(
|
| 212 |
+
" Sleep Duration (hours, e.g. 7.5)", 7.2, float
|
| 213 |
+
)
|
| 214 |
+
quality_of_sleep = prompt_input(
|
| 215 |
+
" Quality of Sleep (scale 1-10)", 7, int
|
| 216 |
+
)
|
| 217 |
+
physical_activity = prompt_input(
|
| 218 |
+
" Physical Activity Level (minutes/day)", 60, int
|
| 219 |
+
)
|
| 220 |
+
stress_level = prompt_input(" Stress Level (scale 1-10)", 5, int)
|
| 221 |
+
heart_rate = prompt_input(" Heart Rate (bpm)", 72, int)
|
| 222 |
+
daily_steps = prompt_input(" Daily Steps", 7000, int)
|
| 223 |
+
blood_pressure = prompt_input(
|
| 224 |
+
" Blood Pressure (e.g. 120/80)", "120/80", str
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
custom_sample = {
|
| 228 |
+
"Gender": gender,
|
| 229 |
+
"Age": age,
|
| 230 |
+
"Occupation": occupation,
|
| 231 |
+
"Sleep Duration": sleep_duration,
|
| 232 |
+
"Quality of Sleep": quality_of_sleep,
|
| 233 |
+
"Physical Activity Level": physical_activity,
|
| 234 |
+
"Stress Level": stress_level,
|
| 235 |
+
"Heart Rate": heart_rate,
|
| 236 |
+
"Daily Steps": daily_steps,
|
| 237 |
+
"Blood Pressure": blood_pressure,
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
custom_copy = custom_sample.copy()
|
| 241 |
+
res = predict(custom_sample, model=model)
|
| 242 |
+
print_prediction_card("Custom User Profile", custom_copy, res)
|
| 243 |
+
|
| 244 |
+
again = input("\nWould you like to test another custom profile? (y/N): ").strip().lower()
|
| 245 |
+
if again not in ("y", "yes"):
|
| 246 |
+
print("\nExiting manual interactive mode.")
|
| 247 |
+
break
|
| 248 |
+
except (EOFError, KeyboardInterrupt):
|
| 249 |
+
print("\nExiting manual interactive mode.")
|
| 250 |
+
break
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def main():
|
| 254 |
+
print("=" * 70)
|
| 255 |
+
print(" Sleep Health & Lifestyle AI Classifier - Inference Verification ")
|
| 256 |
+
print("=" * 70)
|
| 257 |
+
|
| 258 |
+
model = load_model(MODEL_PATH)
|
| 259 |
+
print(f"Loaded model successfully from: {MODEL_PATH}")
|
| 260 |
+
|
| 261 |
+
# 1. Run Benchmark Profiles (Healthy, Unhealthy, Borderline)
|
| 262 |
+
run_benchmark_profiles(model)
|
| 263 |
+
|
| 264 |
+
print("\n" + "=" * 70)
|
| 265 |
+
print(" Benchmark profile verification completed!")
|
| 266 |
+
print("=" * 70)
|
| 267 |
+
|
| 268 |
+
# 2. Check if manual interactive input is requested or running in interactive terminal
|
| 269 |
+
interactive_flag = any(arg in sys.argv for arg in ["--interactive", "-i", "--custom"])
|
| 270 |
+
|
| 271 |
+
if interactive_flag:
|
| 272 |
+
interactive_terminal_mode(model)
|
| 273 |
+
elif sys.stdin.isatty():
|
| 274 |
+
try:
|
| 275 |
+
choice = input("\nWould you like to enter a custom profile to test manually? (y/N): ").strip().lower()
|
| 276 |
+
if choice in ("y", "yes"):
|
| 277 |
+
interactive_terminal_mode(model)
|
| 278 |
+
except (EOFError, KeyboardInterrupt):
|
| 279 |
+
pass
|
| 280 |
+
else:
|
| 281 |
+
print("\n💡 Manual Testing Tip:")
|
| 282 |
+
print("To enter your own custom values interactively in the terminal, run:")
|
| 283 |
+
print(" python predict.py --interactive")
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
if __name__ == "__main__":
|
| 287 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
scikit-learn>=1.4.0
|
| 2 |
+
pandas>=2.0.0
|
| 3 |
+
joblib>=1.3.0
|
| 4 |
+
numpy>=1.24.0
|
train_model.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
train_model.py
|
| 3 |
+
==============
|
| 4 |
+
Trains a Random Forest Classifier to predict healthy vs unhealthy lifestyle status
|
| 5 |
+
using the Sleep Health and Lifestyle dataset.
|
| 6 |
+
Saves the trained pipeline model as lifestyle_model.pkl.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import joblib
|
| 11 |
+
import pandas as pd
|
| 12 |
+
import numpy as np
|
| 13 |
+
from sklearn.model_selection import train_test_split
|
| 14 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 15 |
+
from sklearn.compose import ColumnTransformer
|
| 16 |
+
from sklearn.preprocessing import OrdinalEncoder
|
| 17 |
+
from sklearn.pipeline import Pipeline
|
| 18 |
+
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
|
| 19 |
+
|
| 20 |
+
DATASET_PATH = "Sleep_health_and_lifestyle_dataset.csv"
|
| 21 |
+
MODEL_PATH = "lifestyle_model.pkl"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def load_and_preprocess_data(dataset_path: str):
|
| 25 |
+
"""Loads the dataset, engineer features and target variable."""
|
| 26 |
+
if not os.path.exists(dataset_path):
|
| 27 |
+
raise FileNotFoundError(f"Dataset not found at {dataset_path}")
|
| 28 |
+
|
| 29 |
+
print(f"Loading dataset from: {dataset_path} ...")
|
| 30 |
+
df = pd.read_csv(dataset_path)
|
| 31 |
+
print(f"Dataset shape: {df.shape}")
|
| 32 |
+
|
| 33 |
+
# 1. Define Binary Target Variable 'Is_Healthy'
|
| 34 |
+
# Healthy (1) if:
|
| 35 |
+
# - Sleep Duration >= 7.0 hours (recommended minimum for adults)
|
| 36 |
+
# - Quality of Sleep >= 7 (on 1-10 scale)
|
| 37 |
+
# - Physical Activity Level >= 60 (minutes/day)
|
| 38 |
+
# - Stress Level <= 5 (low to moderate stress)
|
| 39 |
+
# Otherwise Unhealthy (0)
|
| 40 |
+
df["Is_Healthy"] = (
|
| 41 |
+
(df["Sleep Duration"] >= 7.0)
|
| 42 |
+
& (df["Quality of Sleep"] >= 7)
|
| 43 |
+
& (df["Physical Activity Level"] >= 60)
|
| 44 |
+
& (df["Stress Level"] <= 5)
|
| 45 |
+
).astype(int)
|
| 46 |
+
|
| 47 |
+
target_counts = df["Is_Healthy"].value_counts().to_dict()
|
| 48 |
+
print(f"Target distribution: 0 (Unhealthy): {target_counts.get(0, 0)}, 1 (Healthy): {target_counts.get(1, 0)}")
|
| 49 |
+
|
| 50 |
+
# 2. Preprocess Blood Pressure into numeric Systolic_BP and Diastolic_BP
|
| 51 |
+
df[["Systolic_BP", "Diastolic_BP"]] = (
|
| 52 |
+
df["Blood Pressure"].str.split("/", expand=True).astype(int)
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
# 3. Exclude BMI Category (to keep features clean and unconfounded)
|
| 56 |
+
# Also drop Person ID (identifier) and Sleep Disorder (outcome diagnosis with NaNs)
|
| 57 |
+
feature_cols = [
|
| 58 |
+
"Gender",
|
| 59 |
+
"Age",
|
| 60 |
+
"Occupation",
|
| 61 |
+
"Sleep Duration",
|
| 62 |
+
"Quality of Sleep",
|
| 63 |
+
"Physical Activity Level",
|
| 64 |
+
"Stress Level",
|
| 65 |
+
"Heart Rate",
|
| 66 |
+
"Daily Steps",
|
| 67 |
+
"Systolic_BP",
|
| 68 |
+
"Diastolic_BP",
|
| 69 |
+
]
|
| 70 |
+
|
| 71 |
+
X = df[feature_cols].copy()
|
| 72 |
+
y = df["Is_Healthy"].copy()
|
| 73 |
+
|
| 74 |
+
return X, y, feature_cols
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def build_pipeline(categorical_cols, numerical_cols):
|
| 78 |
+
"""Creates a Scikit-Learn Pipeline with preprocessor and RandomForestClassifier."""
|
| 79 |
+
preprocessor = ColumnTransformer(
|
| 80 |
+
transformers=[
|
| 81 |
+
(
|
| 82 |
+
"cat",
|
| 83 |
+
OrdinalEncoder(
|
| 84 |
+
handle_unknown="use_encoded_value", unknown_value=-1
|
| 85 |
+
),
|
| 86 |
+
categorical_cols,
|
| 87 |
+
),
|
| 88 |
+
("num", "passthrough", numerical_cols),
|
| 89 |
+
]
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
pipeline = Pipeline(
|
| 93 |
+
steps=[
|
| 94 |
+
("preprocessor", preprocessor),
|
| 95 |
+
(
|
| 96 |
+
"classifier",
|
| 97 |
+
RandomForestClassifier(
|
| 98 |
+
n_estimators=100,
|
| 99 |
+
max_depth=6,
|
| 100 |
+
random_state=42,
|
| 101 |
+
class_weight="balanced",
|
| 102 |
+
),
|
| 103 |
+
),
|
| 104 |
+
]
|
| 105 |
+
)
|
| 106 |
+
return pipeline
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def main():
|
| 110 |
+
print("=" * 60)
|
| 111 |
+
print(" Sleep Health & Lifestyle AI Classifier - Training Pipeline ")
|
| 112 |
+
print("=" * 60)
|
| 113 |
+
|
| 114 |
+
X, y, feature_cols = load_and_preprocess_data(DATASET_PATH)
|
| 115 |
+
|
| 116 |
+
categorical_cols = ["Gender", "Occupation"]
|
| 117 |
+
numerical_cols = [col for col in feature_cols if col not in categorical_cols]
|
| 118 |
+
|
| 119 |
+
print(f"Categorical features: {categorical_cols}")
|
| 120 |
+
print(f"Numerical features: {numerical_cols}")
|
| 121 |
+
|
| 122 |
+
# Train / Test Split for Evaluation
|
| 123 |
+
X_train, X_test, y_train, y_test = train_test_split(
|
| 124 |
+
X, y, test_size=0.2, random_state=42, stratify=y
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
print(f"\nTraining set size: {len(X_train)} samples")
|
| 128 |
+
print(f"Testing set size: {len(X_test)} samples")
|
| 129 |
+
|
| 130 |
+
# Evaluate Model
|
| 131 |
+
eval_pipeline = build_pipeline(categorical_cols, numerical_cols)
|
| 132 |
+
eval_pipeline.fit(X_train, y_train)
|
| 133 |
+
|
| 134 |
+
y_pred = eval_pipeline.predict(X_test)
|
| 135 |
+
accuracy = accuracy_score(y_test, y_pred)
|
| 136 |
+
|
| 137 |
+
print("\n" + "=" * 60)
|
| 138 |
+
print(" EVALUATION RESULTS (Holdout Test Set) ")
|
| 139 |
+
print("=" * 60)
|
| 140 |
+
print(f"Accuracy Score: {accuracy * 100:.2f}%\n")
|
| 141 |
+
|
| 142 |
+
print("Classification Report:")
|
| 143 |
+
print(
|
| 144 |
+
classification_report(
|
| 145 |
+
y_test, y_pred, target_names=["Unhealthy (0)", "Healthy (1)"]
|
| 146 |
+
)
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
print("Confusion Matrix:")
|
| 150 |
+
print(confusion_matrix(y_test, y_pred))
|
| 151 |
+
|
| 152 |
+
# Train final model on full dataset for production deployment
|
| 153 |
+
print("\n" + "=" * 60)
|
| 154 |
+
print(" Training Final Model on Full Dataset for Deployment ")
|
| 155 |
+
print("=" * 60)
|
| 156 |
+
final_pipeline = build_pipeline(categorical_cols, numerical_cols)
|
| 157 |
+
final_pipeline.fit(X, y)
|
| 158 |
+
|
| 159 |
+
# Save trained pipeline model
|
| 160 |
+
joblib.dump(final_pipeline, MODEL_PATH)
|
| 161 |
+
print(f"Successfully saved trained model to: {MODEL_PATH}")
|
| 162 |
+
|
| 163 |
+
# Verify model artifact can be reloaded
|
| 164 |
+
loaded_model = joblib.load(MODEL_PATH)
|
| 165 |
+
sample_pred = loaded_model.predict(X.iloc[:2])
|
| 166 |
+
print(f"Verification test prediction on first 2 samples: {sample_pred}")
|
| 167 |
+
print("Model training and packaging completed successfully!")
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
if __name__ == "__main__":
|
| 171 |
+
main()
|