File size: 10,042 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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 | """
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()
|