""" predict.py ========== Loads the trained Random Forest pipeline ('lifestyle_model.pkl') and performs inference 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 os import sys import joblib import 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()