Download train_model.py from varshagoswami01/sleep-lifecycle-predictor: direct link, hf CLI and curl.
- Browser
- Download file 5.46 kB
-
https://huggingface.co/varshagoswami01/sleep-lifecycle-predictor/resolve/main/train_model.py
- Command line
-
hf download hf://varshagoswami01/sleep-lifecycle-predictor/train_model.py
-
curl -L -o train_model.py https://huggingface.co/varshagoswami01/sleep-lifecycle-predictor/resolve/main/train_model.py
5.46 kB
| """ | |
| train_model.py | |
| ============== | |
| Trains a Random Forest Classifier to predict healthy vs unhealthy lifestyle status | |
| using the Sleep Health and Lifestyle dataset. | |
| Saves the trained pipeline model as lifestyle_model.pkl. | |
| """ | |
| import os | |
| import joblib | |
| import pandas as pd | |
| import numpy as np | |
| from sklearn.model_selection import train_test_split | |
| from sklearn.ensemble import RandomForestClassifier | |
| from sklearn.compose import ColumnTransformer | |
| from sklearn.preprocessing import OrdinalEncoder | |
| from sklearn.pipeline import Pipeline | |
| from 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() | |