IMPORTANT DISCLAIMER: This project is an empirical predictive analytics and Machine Learning research prototype designed to explore statistical relationships between self-reported digital habits, lifestyle factors, and an estimated wellness signal. It does NOT diagnose mental illnesses, provide psychiatric assessments, or replace licensed medical care.
Modern students balance intensive digital engagement, academic workload, and lifestyle demands. Understanding the quantitative relationship between digital screen time, sleep duration, physical activity, and subjective well-being is critical for behavioral wellness analytics.
This project upgrades a baseline research prototype into a production-ready, end-to-end Machine Learning Engineering system. It provides:
- A clean, leakage-free Scikit-learn preprocessing and feature engineering pipeline.
- Automated multi-model benchmarking across 5 regression architectures.
- Hyperparameter tuning (
RandomizedSearchCV) yielding an R² of 0.8775 (RMSE = 0.4676). - Local and global model explainability attributing protective and strain factors.
- A high-performance, modular FastAPI REST service supporting single and batch inference (
/predict,/batch-predict,/explain,/health,/model-info). - A responsive, dark-minimalist web dashboard with live feature impact waterfall charts and session prediction history.
- Full containerization via Docker and Docker Compose, automated pytest test suite, and GitHub Actions CI/CD.
flowchart TD
A[Raw Survey Dataset: 5,000 Records] --> B[Data Cleaning & Deduplication]
B --> C[Stratified 80/20 Train-Test Split]
C --> D[CountryGrouper: Top 10 + Other]
D --> E[LifestyleFeatureEngineer: Behavioral Ratios]
E --> F[ColumnTransformer: Log1p, StandardScaler, OrdinalEncoder, OneHotEncoder]
F --> G[5-Model Benchmark & 5-Fold Cross-Validation]
G --> H[Hyperparameter Tuning: RandomizedSearchCV]
H --> I[Winning Model: Tuned Random Forest R²=0.8775]
I --> J[Artifact Serialization: models/latest/model.joblib + metadata.json]
J --> K[FastAPI Production Service: app/main.py]
K --> L1[POST /predict]
K --> L2[POST /batch-predict]
K --> L3[POST /explain]
K --> L4[GET /health & /model-info]
K --> M[Interactive Web Dashboard: static/]
The underlying dataset comprises 5,000 student records across 12 behavioral and demographic features.
| Feature Name | Formulation | Hypothesis / Motivation | Observed Feature Importance |
|---|---|---|---|
screen_to_sleep_ratio |
Direct proxy for digital fatigue; screen time encroaching on sleep. | 64.89% (Dominant factor) | |
lifestyle_balance |
Ratio of restorative activities to digital consumption. | 12.88% (Second strongest) | |
Daily_Unlocks |
Raw unlocks/day | Indicator of task fragmentation and habitual phone checking. | 3.19% |
Sleep_Hours_Per_Night |
Raw sleep duration | Essential biological recovery foundation. | 2.06% |
study_to_screen_ratio |
Balance between productive focus and passive consumption. | 1.78% | |
total_daily_load |
Total cognitive and screen engagement demand per day. | 1.30% | |
Grouped_country |
Top 10 countries preserved, others 'Other'
|
Mitigates high-cardinality sparse dimensionality. | Stabilizes model variance |
Five candidate models were trained with a composite Scikit-learn Pipeline and evaluated using 5-fold cross-validation on 3,998 training records, then benchmarked against 1,000 holdout test records.
| Model Architecture | Test R² | Test RMSE | Test MAE | 5-Fold CV R² (Mean ± Std) | Status |
|---|---|---|---|---|---|
| Random Forest (Tuned v1.2) | 0.8775 | 0.4676 | 0.3496 | 0.8508 ± 0.009 | Selected Best |
| Random Forest (Default) | 0.8595 | 0.5008 | 0.3852 | 0.8357 ± 0.009 | Baseline Ensemble |
| XGBoost Regressor | 0.8293 | 0.5520 | 0.4295 | 0.8076 ± 0.011 | Gradient Boosting |
| Gradient Boosting | 0.8285 | 0.5533 | 0.4312 | 0.8084 ± 0.011 | Scikit-learn GBDT |
| Ridge Regressor | 0.7461 | 0.6732 | 0.5318 | 0.7297 ± 0.012 | Regularized Linear |
| Linear Regression | 0.7459 | 0.6735 | 0.5320 | 0.7296 ± 0.012 | Baseline Linear |
-
Residual Distribution: Centered around zero (Mean:
$+0.004$ , Std:$0.467$ ). -
Prediction Accuracy: 84.3% of all test predictions fall within
$\pm 0.50$ points of the actual score; 97.8% fall within$\pm 1.00$ point.
The backend service is powered by FastAPI and Pydantic v2.
| Method | Endpoint | Description |
|---|---|---|
GET |
/health |
Health check and pipeline readiness status |
GET |
/model-info |
Active model version, training metrics, hyperparameters, and feature list |
POST |
/predict |
Single record prediction with confidence intervals & top factors |
POST |
/batch-predict |
Batch prediction for up to 500 records with latency telemetry |
POST |
/explain |
Localized feature contribution breakdown relative to population norms |
curl -X POST "http://localhost:8000/predict" \
-H "Content-Type: application/json" \
-d '{
"age": 21,
"gender": "Female",
"country": "India",
"academic_level": "Undergraduate",
"most_used_platform": "Instagram",
"purpose_of_use": "Entertainment",
"avg_daily_usage_hours": 4.5,
"daily_unlocks": 140,
"study_hours": 3.5,
"physical_activity_hours": 1.5,
"sleep_hours_per_night": 7.0,
"stress_level": "Medium"
}'{
"predicted_mental_health_score": 6.84,
"score_band": "Balanced",
"interpretation": "Your daily rhythm appears steady, with a moderate digital footprint and healthy baseline recovery capacity.",
"confidence_interval": [6.38, 7.30],
"model_version": "1.2.0",
"top_positive_contributors": [
{
"feature": "Sleep_Hours_Per_Night",
"display_name": "Sleep Duration",
"impact": 0.12,
"direction": "positive",
"user_value": "7.0 hrs"
}
],
"top_negative_contributors": [
{
"feature": "screen_to_sleep_ratio",
"display_name": "Screen-to-Sleep Ratio",
"impact": -0.28,
"direction": "negative",
"user_value": "0.63"
}
],
"request_id": "a1b2c3d4",
"disclaimer": "This score is an ML research estimate and does NOT constitute medical or psychiatric diagnosis."
}mental-health-score/
├── .github/
│ └── workflows/
│ └── ci.yml # CI workflow for linting, testing, Docker checks
├── app/
│ ├── main.py # FastAPI application & static file mounting
│ ├── config.py # Pydantic Settings & environment variables
│ ├── api/
│ │ ├── routes.py # API route handlers (/predict, /batch, /explain, etc.)
│ │ └── deps.py # Centralized dependency injection
│ ├── schemas/
│ │ ├── request.py # Pydantic v2 validation models
│ │ └── response.py # Typed response models
│ ├── services/
│ │ ├── predictor.py # Prediction service & confidence interval estimator
│ │ └── explainer.py # Local attribution & factor contributions
│ └── utils/
│ ├── logger.py # Structured logging setup
│ └── validation.py # Shared business rule validation
├── ml/
│ ├── features.py # Scikit-learn custom transformers (CountryGrouper, LifestyleFeatureEngineer)
│ ├── pipeline.py # ColumnTransformer & composite Pipeline builder
│ ├── train.py # Full training, 5-model benchmarking, and tuning script
│ ├── evaluate.py # Evaluation reports & diagnostic plot generator
│ └── tracker.py # JSON/MLflow experiment tracking interface
├── data/
│ ├── raw/ # Raw dataset
│ └── processed/ # Split train.csv and test.csv artifacts
├── models/
│ └── latest/
│ ├── model.joblib # Serialized best model pipeline
│ ├── metadata.json # Model version, hyperparameters, and metrics
│ └── benchmark_comparison.csv # Cross-validation comparison table
├── static/
│ ├── index.html # Modern interactive dashboard
│ ├── script.js # Frontend client controller
│ └── style.css # Dark-minimalist styling
├── tests/
│ ├── conftest.py # Test fixtures and TestClient setup
│ ├── test_preprocessing.py # Unit tests for transformers & ratios
│ ├── test_model.py # Model loading & inference determinism tests
│ └── test_api.py # End-to-end endpoint & validation tests
├── ML_Project.ipynb # Executive research & experiment Jupyter notebook
├── Dockerfile # Multi-stage production container build
├── docker-compose.yml # Local container orchestration
├── requirements.txt # Production runtime dependencies
├── requirements-dev.txt # Development, test, and notebook dependencies
├── .env.example
└── README.md
# Clone the repository
git clone https://github.com/Ishant6565/Mental-Health-Score.git
cd Mental-Health-Score
# Create and activate virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install dependencies
pip install -r requirements-dev.txt# Runs deduplication, 5-model benchmark, hyperparameter tuning, and serialization
python ml/train.py
# Generates evaluation reports and diagnostic plots
python ml/evaluate.pyuvicorn app.main:app --host 0.0.0.0 --port 8000 --reload- Web Application Dashboard: http://localhost:8000/
- Interactive OpenAPI / Swagger Docs: http://localhost:8000/docs
- Interactive ReDoc: http://localhost:8000/redoc
pytest tests/ -v# Build and launch container
docker compose up --build
# Run in background
docker compose up -d- Non-Diagnostic Scope: This system models statistical patterns in self-reported survey data. It cannot capture biological markers, environmental stressors, or individual psychiatric history.
- Correlation vs. Causation: High screen-to-sleep ratios correlate with lower self-reported scores; this does not establish sole causality.
- Continuous Monitoring: Model artifacts are versioned alongside training data hashes (
models/experiments/runs.json) to prevent concept drift.
machine-learning, ml-engineering, scikit-learn, fastapi, python, predictive-analytics, data-science, model-explainability, xgboost, mlops, docker, random-forest