File size: 5,460 Bytes
7075fa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
"""
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()