Upload 5 files
Browse filesFiles changed (5)
- README.md+209
- lifestyle_model.pklAdded+3
- predict.pyAdded+287
- requirements.txtAdded+4
- train_model.pyAdded+171
123---license: mit---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212---language:- enlicense: mitlibrary_name: scikit-learntags:- tabular-classification- random-forest- health- lifestyle- sleep-health- healthcaremetrics:- accuracy- precision- recall- f1model-index:- name: sleep-health-lifestyle-classifierresults:- task:type: tabular-classificationname: Tabular Classificationmetrics:- name: Accuracytype: accuracyvalue: 1.00- name: F1 Scoretype: f1value: 1.00---# Sleep Health & Lifestyle AI ClassifierA 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.Trained on the **Sleep Health and Lifestyle Dataset** and packaged for direct deployment and inference via Hugging Face Models.---## 🎯 Target Definition (`Is_Healthy`)The model classifies individuals into two lifestyle health categories:| Target Value | Class Label | Definition / Health Criteria || :---: | :---: | :--- || **`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) || **`0`** | **Unhealthy Lifestyle** | Fails to meet one or more healthy lifestyle criteria |---## 📊 Dataset & Feature InformationThe 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.### Input Features| Feature | Data Type | Description | Example Values || :--- | :---: | :--- | :---: || **`Gender`** | Categorical | Biological sex | `Male`, `Female` || **`Age`** | Numerical (int) | Age in years | `30`, `45` || **`Occupation`** | Categorical | Primary profession | `Doctor`, `Engineer`, `Nurse`, `Teacher` || **`Sleep Duration`** | Numerical (float) | Average sleep duration in hours | `7.8`, `6.1` || **`Quality of Sleep`** | Numerical (int) | Subjective sleep rating (scale 1–10) | `8`, `4` || **`Physical Activity Level`** | Numerical (int) | Daily exercise / activity in minutes | `75`, `30` || **`Stress Level`** | Numerical (int) | Self-reported stress (scale 1–10) | `4`, `8` || **`Heart Rate`** | Numerical (int) | Resting heart rate in beats per minute (bpm) | `68`, `85` || **`Daily Steps`** | Numerical (int) | Number of steps walked daily | `8500`, `3200` || **`Systolic_BP`** | Numerical (int) | Systolic blood pressure (mmHg) | `120`, `140` || **`Diastolic_BP`** | Numerical (int) | Diastolic blood pressure (mmHg) | `80`, `90` |---## 📈 Model Performance & EvaluationThe model was trained and evaluated using a **stratified 80/20 train-test split** (`random_state=42`) with class balancing:- **Accuracy Score**: `100.00%`- **Balanced Class Distribution**:- Unhealthy (`0`): 228 samples (61.0%)- Healthy (`1`): 146 samples (39.0%)### Classification Report (Holdout Test Set)| Class | Precision | Recall | F1-Score | Support || :--- | :---: | :---: | :---: | :---: || **`0` (Unhealthy)** | 1.00 | 1.00 | 1.00 | 46 || **`1` (Healthy)** | 1.00 | 1.00 | 1.00 | 29 || **Overall Accuracy** | — | — | **1.00** | **75** || **Macro Average** | 1.00 | 1.00 | 1.00 | 75 || **Weighted Average** | 1.00 | 1.00 | 1.00 | 75 |### Confusion Matrix```Predicted Unhealthy (0) Predicted Healthy (1)Actual Unhealthy (0) 46 0Actual Healthy (1) 0 29```---## 🚀 Quickstart & Usage### 1. RequirementsInstall required dependencies:```bashpip install -r requirements.txt```*(or install directly: `pip install scikit-learn pandas joblib numpy`)*### 2. Inference using `predict.py`Run the included test script to verify predictions on diverse sample profiles:```bashpython predict.py```### 3. Python Code SnippetLoad `lifestyle_model.pkl` and predict directly:```pythonimport joblibimport pandas as pd# Load the trained pipelinemodel = joblib.load("lifestyle_model.pkl")# Define input data (supports raw string categories)sample_data = pd.DataFrame([{"Gender": "Male","Age": 30,"Occupation": "Doctor","Sleep Duration": 7.8,"Quality of Sleep": 8,"Physical Activity Level": 75,"Stress Level": 4,"Heart Rate": 68,"Daily Steps": 8500,"Systolic_BP": 120,"Diastolic_BP": 80,},{"Gender": "Male","Age": 28,"Occupation": "Sales Representative","Sleep Duration": 5.9,"Quality of Sleep": 4,"Physical Activity Level": 30,"Stress Level": 8,"Heart Rate": 85,"Daily Steps": 3000,"Systolic_BP": 140,"Diastolic_BP": 90,}])# Predict class (0 = Unhealthy, 1 = Healthy)predictions = model.predict(sample_data)probabilities = model.predict_proba(sample_data)labels = {0: "Unhealthy Lifestyle", 1: "Healthy Lifestyle"}for i, pred in enumerate(predictions):print(f"Sample {i + 1}: {labels[pred]} (Confidence: {probabilities[i][pred] * 100:.1f}%)")```### 4. Downloading from Hugging Face HubIf hosting on Hugging Face Model Hub, download the model file directly with `huggingface_hub`:```pythonfrom huggingface_hub import hf_hub_downloadimport joblibmodel_path = hf_hub_download(repo_id="<YOUR_USERNAME>/<YOUR_MODEL_REPO>", filename="lifestyle_model.pkl")model = joblib.load(model_path)```---## 📦 Uploading to Hugging Face Model HubTo upload this model repository to the Hugging Face Model Hub (under **Models**):```bash# 1. Install Hugging Face Hub CLI and authenticatepip install huggingface_hubhuggingface-cli login# 2. Create the Model repository (under Models, NOT Spaces)# Example via CLI or create directly at https://huggingface.co/new# 3. Clone and copy files, or push directly via git:git clone https://huggingface.co/<YOUR_USERNAME>/sleep-lifestyle-classifiercd sleep-lifestyle-classifier# Copy lifestyle_model.pkl, README.md, requirements.txt, predict.py, and train_model.pygit add .git commit -m "Initial commit of Sleep Health & Lifestyle Classifier"git push```---## 📜 LicenseThis project is licensed under the MIT License.
123version https://git-lfs.github.com/spec/v1oid sha256:885ef43099ebd0a36efdba67e423c00cb49e9c5dff258df850ab01162745bd7dsize 151202123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287"""predict.py==========Loads the trained Random Forest pipeline ('lifestyle_model.pkl') and performsinference on user profiles to verify model predictions and confidence scores.
Supports:1. Automated evaluation on 3 realistic benchmark user profiles: - Clearly Healthy Lifestyle - Clearly Unhealthy Lifestyle (low sleep & high stress) - Borderline Case (near thresholds)2. Interactive manual testing from the terminal (custom input)."""
import osimport sysimport joblibimport pandas as pd
MODEL_PATH = "lifestyle_model.pkl"
LABEL_MAPPING = { 0: "Unhealthy Lifestyle", 1: "Healthy Lifestyle",}
def load_model(model_path: str = MODEL_PATH): """Loads and returns the saved joblib model pipeline.""" if not os.path.exists(model_path): raise FileNotFoundError( f"Model file '{model_path}' not found! Please run train_model.py first." ) return joblib.load(model_path)
def prepare_input(data): """Normalizes input data (dict, list of dicts, or DataFrame) into the expected schema.""" if isinstance(data, dict): df = pd.DataFrame([data]) elif isinstance(data, list): df = pd.DataFrame(data) elif isinstance(data, pd.DataFrame): df = data.copy() else: raise ValueError("Unsupported input format. Provide dict, list of dicts, or DataFrame.")
# Split 'Blood Pressure' (e.g. '120/80') if provided as a single string if "Blood Pressure" in df.columns: if "Systolic_BP" not in df.columns or "Diastolic_BP" not in df.columns: split_bp = df["Blood Pressure"].astype(str).str.split("/", expand=True) df["Systolic_BP"] = split_bp[0].astype(int) df["Diastolic_BP"] = split_bp[1].astype(int) df = df.drop(columns=["Blood Pressure"])
required_features = [ "Gender", "Age", "Occupation", "Sleep Duration", "Quality of Sleep", "Physical Activity Level", "Stress Level", "Heart Rate", "Daily Steps", "Systolic_BP", "Diastolic_BP", ]
missing = [f for f in required_features if f not in df.columns] if missing: raise ValueError(f"Input is missing required features: {missing}")
return df[required_features]
def predict(input_data, model=None): """ Runs inference on input data and returns detailed predictions. Parameters: input_data (dict, list[dict], or pd.DataFrame): Samples to classify. model: Optional pre-loaded model. If None, loads from MODEL_PATH. Returns: pd.DataFrame: Original inputs augmented with Prediction, Label, and Confidence. """ if model is None: model = load_model()
df_prepared = prepare_input(input_data) preds = model.predict(df_prepared) probs = model.predict_proba(df_prepared)
results = [] for i, pred in enumerate(preds): confidence = probs[i][pred] * 100 results.append({ "Prediction": int(pred), "Label": LABEL_MAPPING.get(int(pred), "Unknown"), "Confidence": f"{confidence:.2f}%", "Probability_Healthy": f"{probs[i][1]:.4f}", "Probability_Unhealthy": f"{probs[i][0]:.4f}", })
result_df = pd.concat([df_prepared.reset_index(drop=True), pd.DataFrame(results)], axis=1) return result_df
def print_prediction_card(profile_name: str, sample_dict: dict, res: pd.DataFrame): """Prints a structured summary card for a prediction.""" print("\n" + "-" * 70) print(f"Profile: {profile_name}") print("-" * 70) for k, v in sample_dict.items(): print(f" {k:<24}: {v}")
pred_class = int(res["Prediction"].iloc[0]) pred_label = res["Label"].iloc[0] confidence = res["Confidence"].iloc[0] prob_healthy = res["Probability_Healthy"].iloc[0] prob_unhealthy = res["Probability_Unhealthy"].iloc[0]
status_tag = "✅ HEALTHY" if pred_class == 1 else "⚠️ UNHEALTHY"
print("\nPrediction Result:") print(f" Classification Outcome : {status_tag} - {pred_label} (Class {pred_class})") print(f" Model Confidence : {confidence}") print(f" Probability [Healthy] : {prob_healthy} ({float(prob_healthy)*100:.1f}%)") print(f" Probability [Unhealthy] : {prob_unhealthy} ({float(prob_unhealthy)*100:.1f}%)")
def run_benchmark_profiles(model): """Runs prediction on 3 predefined realistic test profiles.""" sample_profiles = [ { "Profile": "1. Clearly Healthy Lifestyle (Optimal sleep, high activity, low stress)", "Gender": "Female", "Age": 34, "Occupation": "Engineer", "Sleep Duration": 7.8, "Quality of Sleep": 8, "Physical Activity Level": 75, "Stress Level": 4, "Heart Rate": 68, "Daily Steps": 8500, "Blood Pressure": "118/78", }, { "Profile": "2. Clearly Unhealthy Lifestyle (Low sleep & high stress)", "Gender": "Male", "Age": 29, "Occupation": "Sales Representative", "Sleep Duration": 5.8, "Quality of Sleep": 4, "Physical Activity Level": 30, "Stress Level": 8, "Heart Rate": 86, "Daily Steps": 3000, "Blood Pressure": "140/90", }, { "Profile": "3. Borderline Case (Sleep 6.9 hrs - just 6 min short of 7.0h threshold)", "Gender": "Male", "Age": 32, "Occupation": "Teacher", "Sleep Duration": 6.9, "Quality of Sleep": 7, "Physical Activity Level": 60, "Stress Level": 5, "Heart Rate": 72, "Daily Steps": 6000, "Blood Pressure": "125/82", }, ]
for sample in sample_profiles: profile_name = sample.pop("Profile") sample_copy = sample.copy() res = predict(sample, model=model) print_prediction_card(profile_name, sample_copy, res)
def prompt_input(prompt_text, default_val, val_type=str): """Utility to prompt user with a default fallback.""" try: user_val = input(f"{prompt_text} [{default_val}]: ").strip() if not user_val: return default_val return val_type(user_val) except (EOFError, KeyboardInterrupt): return default_val
def interactive_terminal_mode(model): """Allows manual custom input from the terminal.""" print("\n" + "=" * 70) print(" 🛠️ Manual Interactive Testing Mode ") print(" Enter custom lifestyle values (press Enter to accept default in brackets):") print("=" * 70)
while True: try: gender = prompt_input(" Gender (Male/Female)", "Male", str) age = prompt_input(" Age (years)", 30, int) occupation = prompt_input( " Occupation (e.g. Doctor, Engineer, Teacher, Nurse, Salesperson)", "Software Engineer", str, ) sleep_duration = prompt_input( " Sleep Duration (hours, e.g. 7.5)", 7.2, float ) quality_of_sleep = prompt_input( " Quality of Sleep (scale 1-10)", 7, int ) physical_activity = prompt_input( " Physical Activity Level (minutes/day)", 60, int ) stress_level = prompt_input(" Stress Level (scale 1-10)", 5, int) heart_rate = prompt_input(" Heart Rate (bpm)", 72, int) daily_steps = prompt_input(" Daily Steps", 7000, int) blood_pressure = prompt_input( " Blood Pressure (e.g. 120/80)", "120/80", str )
custom_sample = { "Gender": gender, "Age": age, "Occupation": occupation, "Sleep Duration": sleep_duration, "Quality of Sleep": quality_of_sleep, "Physical Activity Level": physical_activity, "Stress Level": stress_level, "Heart Rate": heart_rate, "Daily Steps": daily_steps, "Blood Pressure": blood_pressure, }
custom_copy = custom_sample.copy() res = predict(custom_sample, model=model) print_prediction_card("Custom User Profile", custom_copy, res)
again = input("\nWould you like to test another custom profile? (y/N): ").strip().lower() if again not in ("y", "yes"): print("\nExiting manual interactive mode.") break except (EOFError, KeyboardInterrupt): print("\nExiting manual interactive mode.") break
def main(): print("=" * 70) print(" Sleep Health & Lifestyle AI Classifier - Inference Verification ") print("=" * 70)
model = load_model(MODEL_PATH) print(f"Loaded model successfully from: {MODEL_PATH}")
# 1. Run Benchmark Profiles (Healthy, Unhealthy, Borderline) run_benchmark_profiles(model)
print("\n" + "=" * 70) print(" Benchmark profile verification completed!") print("=" * 70)
# 2. Check if manual interactive input is requested or running in interactive terminal interactive_flag = any(arg in sys.argv for arg in ["--interactive", "-i", "--custom"]) if interactive_flag: interactive_terminal_mode(model) elif sys.stdin.isatty(): try: choice = input("\nWould you like to enter a custom profile to test manually? (y/N): ").strip().lower() if choice in ("y", "yes"): interactive_terminal_mode(model) except (EOFError, KeyboardInterrupt): pass else: print("\n💡 Manual Testing Tip:") print("To enter your own custom values interactively in the terminal, run:") print(" python predict.py --interactive")
if __name__ == "__main__": main()1234scikit-learn>=1.4.0pandas>=2.0.0joblib>=1.3.0numpy>=1.24.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171"""train_model.py==============Trains a Random Forest Classifier to predict healthy vs unhealthy lifestyle statususing the Sleep Health and Lifestyle dataset.Saves the trained pipeline model as lifestyle_model.pkl."""
import osimport joblibimport pandas as pdimport numpy as npfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.compose import ColumnTransformerfrom sklearn.preprocessing import OrdinalEncoderfrom sklearn.pipeline import Pipelinefrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix
DATASET_PATH = "Sleep_health_and_lifestyle_dataset.csv"MODEL_PATH = "lifestyle_model.pkl"
def load_and_preprocess_data(dataset_path: str): """Loads the dataset, engineer features and target variable.""" if not os.path.exists(dataset_path): raise FileNotFoundError(f"Dataset not found at {dataset_path}")
print(f"Loading dataset from: {dataset_path} ...") df = pd.read_csv(dataset_path) print(f"Dataset shape: {df.shape}")
# 1. Define Binary Target Variable 'Is_Healthy' # Healthy (1) if: # - Sleep Duration >= 7.0 hours (recommended minimum for adults) # - Quality of Sleep >= 7 (on 1-10 scale) # - Physical Activity Level >= 60 (minutes/day) # - Stress Level <= 5 (low to moderate stress) # Otherwise Unhealthy (0) df["Is_Healthy"] = ( (df["Sleep Duration"] >= 7.0) & (df["Quality of Sleep"] >= 7) & (df["Physical Activity Level"] >= 60) & (df["Stress Level"] <= 5) ).astype(int)
target_counts = df["Is_Healthy"].value_counts().to_dict() print(f"Target distribution: 0 (Unhealthy): {target_counts.get(0, 0)}, 1 (Healthy): {target_counts.get(1, 0)}")
# 2. Preprocess Blood Pressure into numeric Systolic_BP and Diastolic_BP df[["Systolic_BP", "Diastolic_BP"]] = ( df["Blood Pressure"].str.split("/", expand=True).astype(int) )
# 3. Exclude BMI Category (to keep features clean and unconfounded) # Also drop Person ID (identifier) and Sleep Disorder (outcome diagnosis with NaNs) feature_cols = [ "Gender", "Age", "Occupation", "Sleep Duration", "Quality of Sleep", "Physical Activity Level", "Stress Level", "Heart Rate", "Daily Steps", "Systolic_BP", "Diastolic_BP", ]
X = df[feature_cols].copy() y = df["Is_Healthy"].copy()
return X, y, feature_cols
def build_pipeline(categorical_cols, numerical_cols): """Creates a Scikit-Learn Pipeline with preprocessor and RandomForestClassifier.""" preprocessor = ColumnTransformer( transformers=[ ( "cat", OrdinalEncoder( handle_unknown="use_encoded_value", unknown_value=-1 ), categorical_cols, ), ("num", "passthrough", numerical_cols), ] )
pipeline = Pipeline( steps=[ ("preprocessor", preprocessor), ( "classifier", RandomForestClassifier( n_estimators=100, max_depth=6, random_state=42, class_weight="balanced", ), ), ] ) return pipeline
def main(): print("=" * 60) print(" Sleep Health & Lifestyle AI Classifier - Training Pipeline ") print("=" * 60)
X, y, feature_cols = load_and_preprocess_data(DATASET_PATH)
categorical_cols = ["Gender", "Occupation"] numerical_cols = [col for col in feature_cols if col not in categorical_cols]
print(f"Categorical features: {categorical_cols}") print(f"Numerical features: {numerical_cols}")
# Train / Test Split for Evaluation X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y )
print(f"\nTraining set size: {len(X_train)} samples") print(f"Testing set size: {len(X_test)} samples")
# Evaluate Model eval_pipeline = build_pipeline(categorical_cols, numerical_cols) eval_pipeline.fit(X_train, y_train)
y_pred = eval_pipeline.predict(X_test) accuracy = accuracy_score(y_test, y_pred)
print("\n" + "=" * 60) print(" EVALUATION RESULTS (Holdout Test Set) ") print("=" * 60) print(f"Accuracy Score: {accuracy * 100:.2f}%\n")
print("Classification Report:") print( classification_report( y_test, y_pred, target_names=["Unhealthy (0)", "Healthy (1)"] ) )
print("Confusion Matrix:") print(confusion_matrix(y_test, y_pred))
# Train final model on full dataset for production deployment print("\n" + "=" * 60) print(" Training Final Model on Full Dataset for Deployment ") print("=" * 60) final_pipeline = build_pipeline(categorical_cols, numerical_cols) final_pipeline.fit(X, y)
# Save trained pipeline model joblib.dump(final_pipeline, MODEL_PATH) print(f"Successfully saved trained model to: {MODEL_PATH}")
# Verify model artifact can be reloaded loaded_model = joblib.load(MODEL_PATH) sample_pred = loaded_model.predict(X.iloc[:2]) print(f"Verification test prediction on first 2 samples: {sample_pred}") print("Model training and packaging completed successfully!")
if __name__ == "__main__": main()README.md+209
lifestyle_model.pklAdded+3
predict.pyAdded+287
requirements.txtAdded+4
train_model.pyAdded+171