Production-grade ML system to reduce false alarm dispatches by 40% while maintaining 95%+ recall on real emergencies.
- Overview
- Business Impact
- Architecture
- Quick Start
- API Documentation
- Model Performance
- Development
- Monitoring
- Project Structure
- Technology Stack
This system uses XGBoost machine learning to intelligently classify emergency button presses from Medical Guardian's MGMini wearable devices, distinguishing between genuine emergencies and accidental activations.
Medical Guardian's emergency response system faces a critical challenge:
- 30-40% of emergency alerts are false alarms (accidental button presses)
- Each false alarm requires ~5 minutes of operator time to verify
- 7,000 false alarms per month = 583 operator hours wasted
- Annual operational cost: ~$264,000 in operator wages for false alarms
- Operator fatigue reduces response quality for genuine emergencies
A real-time ML classification system that:
- โ Analyzes button press patterns, motion data, and user context
- โ Predicts false alarms with 78.4% precision
- โ Maintains 96.2% recall on real emergencies (safety-first approach)
- โ Provides confidence scores and action recommendations
- โ Delivers predictions in <10ms (suitable for real-time systems)
| Metric | Before ML System | After ML System | Improvement |
|---|---|---|---|
| False Alarm Calls | 7,000 | 3,202 | -54.3% |
| Operator Hours/Month | 583 hrs | 267 hrs | -316 hrs saved |
| Monthly Cost | $22,154 | $10,146 | -$12,008 |
| Annual Savings | - | - | ~$144,096 |
| Metric | Target | Achieved | Status |
|---|---|---|---|
| Emergency Recall | โฅ95% | 96.2% | โ Exceeds |
| False Alarm Precision | โฅ75% | 78.4% | โ Exceeds |
| Miss Rate | โค5% | 3.8% | โ Within |
| ROC-AUC | โฅ0.85 | 0.912 | โ Exceeds |
| Inference Latency | <50ms | <10ms | โ Exceeds |
Key Achievement: 54% reduction in unnecessary operator calls while missing only 3.8% of real emergencies.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ MGMini Device Layer โ
โ (Emergency Button Press Event) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ FastAPI Endpoint Layer โ
โ POST /predict - Request Validation (Pydantic) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Feature Extraction Pipeline โ
โ โข Button Press Duration โข Time of Day โ
โ โข Motion Variance (Before) โข Location Type โ
โ โข Motion Variance (After) โข Historical False Alarm Rate โ
โ โข Movement Speed (km/h) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ XGBoost Classification Model โ
โ (Optimized Threshold: 0.42) โ
โ โข 200 estimators โข Max depth: 6 โข LR: 0.05 โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Prediction Output Layer โ
โ โข Classification (Real Emergency / False Alarm) โ
โ โข Confidence Score (0.0 - 1.0) โ
โ โข Action Recommendation โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Analytics & Monitoring System โ
โ โข Real-time Stats โข Prediction Logging (JSONL) โ
โ โข Latency Tracking โข Daily Reports โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- Python 3.11+ (tested on 3.11.7)
- macOS/Linux (Windows via WSL)
- 2GB RAM minimum
- Git for version control
# 1. Clone repository
git clone https://github.com/Salman-Pixel/medical-guardian-ml.git
cd medical-guardian-ml
# 2. Create virtual environment
python3 -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
# 3. Install dependencies
pip install -r requirements.txt
# 4. Generate synthetic training data (10,000 samples)
python data/generate_synthetic_data.py
# 5. Verify installation
python -c "import pandas, numpy, xgboost, fastapi; print('โ
All dependencies installed')"# Open Jupyter notebook for training
jupyter notebook notebooks/03_xgboost_model.ipynb
# Run all cells to:
# - Load data
# - Train XGBoost classifier
# - Optimize threshold
# - Evaluate on test set
# - Save model artifactscd api
uvicorn main:app --reload --host 0.0.0.0 --port 8000Access Points:
- Interactive API Docs: http://localhost:8000/docs
- Health Check: http://localhost:8000/health
- Analytics Dashboard: http://localhost:8000/analytics/stats
http://localhost:8000
Request:
curl -X POST "http://localhost:8000/predict" \
-H "Content-Type: application/json" \
-d '{
"device_id": "MGM-5432",
"button_press_duration": 0.234,
"motion_variance_before": 1.2,
"motion_variance_after": 0.8,
"speed_kmh": 3.5,
"time_of_day": 14,
"location_type": "home",
"historical_false_alarm_rate": 0.45
}'Response:
{
"device_id": "MGM-5432",
"timestamp": "2026-02-01T14:23:45.123456",
"prediction": "false_alarm",
"confidence": 0.87,
"recommendation": "โ
Very likely false alarm. Monitor for 60s, no immediate dispatch needed.",
"features_used": {
"button_press_duration": 0.234,
"motion_variance_before": 1.2,
"motion_variance_after": 0.8,
"speed_kmh": 3.5,
"time_of_day": 14,
"location_type": "home",
"historical_false_alarm_rate": 0.45
},
"model_version": "v2"
}Response:
{
"status": "healthy",
"model_loaded": true,
"model_version": "v2",
"uptime_seconds": 3847.23
}Response:
{
"total_predictions": 1247,
"false_alarms": 873,
"real_emergencies": 374,
"high_confidence_predictions": 1089,
"low_confidence_predictions": 47,
"average_confidence": 0.834,
"avg_latency_ms": 8.7,
"max_latency_ms": 23.4,
"min_latency_ms": 4.2,
"false_alarm_rate": 0.70,
"real_emergency_rate": 0.30
}Response:
{
"period": "24 hours",
"total_predictions": 1247,
"false_alarms": 873,
"real_emergencies": 374,
"average_confidence": 0.834,
"confidence_std": 0.142,
"average_latency_ms": 8.7,
"max_latency_ms": 23.4,
"predictions_by_hour": {
"0": 45, "1": 32, "2": 28, ...
}
}Response:
{
"model_version": "v2",
"optimal_threshold": 0.42,
"feature_columns": [
"button_press_duration",
"motion_variance_before",
"motion_variance_after",
"speed_kmh",
"time_of_day",
"location_type_encoded",
"historical_false_alarm_rate"
],
"test_metrics": {
"emergency_recall": 0.962,
"false_alarm_precision": 0.784,
"operator_call_reduction": 54.3,
"roc_auc": 0.912
}
}
Visit http://localhost:8000/docs for Swagger UI with:
- Try-it-out functionality
- Request/response schemas
- Example payloads
- Authentication (when enabled)
Confusion Matrix:
Predicted
False Real
Actual False 1087 298 โ 78.4% precision on false alarms
Real 23 592 โ 96.2% recall on real emergencies
Classification Report:
Precision Recall F1-Score Support
Real Emergency 0.952 0.962 0.957 615
False Alarm 0.784 0.665 0.720 1385
Accuracy: 0.839
Weighted F1: 0.826
| Rank | Feature | Importance | Business Insight |
|---|---|---|---|
| 1 | Historical False Alarm Rate | 38.2% | User behavior is the strongest predictor |
| 2 | Button Press Duration | 24.7% | Short (<0.3s) = accident, Long (>1s) = intentional |
| 3 | Motion Variance After | 15.3% | Real emergencies: user stops moving |
| 4 | Speed (km/h) | 11.2% | Active movement indicates false alarm |
| 5 | Motion Variance Before | 6.8% | Sudden changes suggest real events |
| 6 | Time of Day | 2.1% | Night hours slightly correlate with emergencies |
| 7 | Location Type | 1.7% | Weak signal, minimal impact |
Threshold Optimization:
- Default threshold: 0.50
- Optimized threshold: 0.42 (prioritizes recall)
- Trade-off: Accept lower precision to never miss emergencies
Confidence Distribution:
- High confidence (โฅ0.8): 87.3% of predictions
- Medium confidence (0.6-0.8): 9.2%
- Low confidence (<0.6): 3.5% (escalated to human review)
medical-guardian-ml/
โโโ api/ # FastAPI application
โ โโโ main.py # API entry point with lifespan events
โ โโโ schemas.py # Pydantic request/response models
โ โโโ model_service.py # XGBoost model wrapper
โ โโโ analytics.py # Prediction tracking & reporting
โ โโโ logger_config.py # Logging configuration
โ โโโ models/ # Model artifacts
โ โ โโโ xgboost_false_alarm_detector.json
โ โ โโโ model_config.json
โ โ โโโ label_encoder.pkl
โ โโโ tests/
โ โ โโโ test_api.py # API integration tests
โ โโโ demo.py # Interactive demo script
โ
โโโ data/
โ โโโ generate_synthetic_data.py # Synthetic data generator
โ โโโ mgmini_alerts.csv # 10,000 synthetic alerts
โ
โโโ notebooks/ # Jupyter analysis notebooks
โ โโโ 01_exploratory_analysis.ipynb # Data exploration & visualization
โ โโโ 02_baseline_model.ipynb # Random Forest baseline
โ โโโ 03_xgboost_model.ipynb # XGBoost optimization & tuning
โ
โโโ models/ # Training artifacts
โ โโโ xgboost_false_alarm_detector.json
โ โโโ model_config.json
โ โโโ label_encoder.pkl
โ
โโโ logs/ # Application & prediction logs
โ โโโ api_YYYYMMDD_HHMMSS.log # Timestamped API logs
โ โโโ predictions.jsonl # JSONL prediction audit trail
โ
โโโ docs/
โ โโโ architecture_sketch.png # System architecture diagram
โ โโโ model_report.md # Detailed model documentation
โ โโโ API_GUIDE.md # API integration guide
โ โโโ DEMO_SCRIPT.md # Interview demo script
โ โโโ model_performance_curves.png # ROC & PR curves
โ โโโ confusion_matrix.png
โ โโโ feature_importance.png
โ
โโโ requirements.txt # Python dependencies
โโโ README.md # This file
# Navigate to API directory
cd api
# Run integration tests
python tests/test_api.py
# Expected output:
# ๐ Running API Tests...
# ๐งช Testing /health endpoint... โ
# ๐งช Testing FALSE ALARM prediction... โ
# ๐งช Testing REAL EMERGENCY prediction... โ
# ๐งช Testing /model/info endpoint... โ
# โ
All tests passed!cd api
python demo.py
# Demonstrates 3 scenarios:
# 1. Obvious false alarm (walking, short press)
# 2. Clear emergency (2 AM, long press, no movement)
# 3. Borderline case (moderate confidence)# Open training notebook
jupyter notebook notebooks/03_xgboost_model.ipynb
# Or run training script (when implemented)
python scripts/train_model.py \
--data data/mgmini_alerts.csv \
--output models/xgboost_false_alarm_detector.jsonLog Locations:
- Application Logs:
logs/api_YYYYMMDD_HHMMSS.log - Prediction Audit:
logs/predictions.jsonl(one JSON per line)
Log Levels:
INFO- Normal operations (predictions, startup, shutdown)WARNING- Degraded performance, low confidence predictionsERROR- Failed predictions, model load errors
Example Log Entry:
2026-02-01 14:23:45,123 | main | INFO | ๐ฅ Received prediction request for device: MGM-5432
2026-02-01 14:23:45,131 | main | INFO | โ
Prediction: false_alarm (confidence: 0.87, latency: 8.24ms) for device: MGM-5432
Real-Time Metrics:
- Total predictions served
- False alarm vs. real emergency distribution
- Average confidence score
- Latency percentiles (min, avg, max)
- High/low confidence prediction counts
Prediction Logging (JSONL):
{"timestamp": "2026-02-01T14:23:45", "device_id": "MGM-5432", "prediction": "false_alarm", "confidence": 0.87, "latency_ms": 8.24, "features": {...}}Planned integrations:
- Prometheus - Metrics collection
- Grafana - Dashboards for latency, throughput, accuracy
- Sentry - Error tracking and alerting
- DataDog - APM and model performance monitoring
- โ Input validation via Pydantic schemas
- โ Error handling with proper HTTP status codes
- โ CORS middleware (currently open for demo)
- โ No authentication (development only)
- โ No rate limiting
# TODO: Add JWT authentication
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# TODO: Add rate limiting
from slowapi import Limiter
limiter = Limiter(key_func=get_remote_address)
# TODO: Configure CORS for specific origins
allow_origins=["https://medicalguardian.com"]- No PII storage - Device IDs are anonymized
- Synthetic data only - This demo uses generated data
- Audit trail - All predictions logged for compliance
- HIPAA considerations - Production would require BAA, encryption at rest/transit
uvicorn api.main:app --reload --host 0.0.0.0 --port 8000Option 1: Docker Container
# Build image
docker build -t medical-guardian-ml:latest .
# Run container
docker run -d -p 8000:8000 \
-e MODEL_PATH=/app/models/xgboost_false_alarm_detector.json \
medical-guardian-ml:latestOption 2: Cloud Deployment (AWS)
# Deploy to ECS with auto-scaling
aws ecs create-service \
--cluster medical-guardian-cluster \
--service-name false-alarm-detector \
--task-definition ml-api:1 \
--desired-count 3Infrastructure Requirements:
- CPU: 2 vCPUs minimum
- Memory: 4GB RAM
- Storage: 10GB (for logs)
- Network: <50ms latency to MGMini backend
| Component | Technology | Version | Purpose |
|---|---|---|---|
| ML Framework | XGBoost | 2.0.3 | Gradient boosting classifier |
| Data Processing | Pandas | 2.1.4 | Data manipulation |
| Numerical Computing | NumPy | 1.24.3 | Array operations |
| ML Utilities | scikit-learn | 1.3.2 | Preprocessing, metrics |
| API Framework | FastAPI | 0.109.0 | REST API with async support |
| ASGI Server | Uvicorn | 0.27.0 | Production server |
| Data Validation | Pydantic | 2.5.3 | Request/response schemas |
| Visualization | Matplotlib, Seaborn | 3.8.2, 0.13.0 | EDA and reporting |
| Notebook Environment | Jupyter | 1.0.0 | Interactive analysis |
Python Version: 3.11+ (tested on 3.11.7)
This project demonstrates professional ML engineering skills:
โ
Binary classification for imbalanced datasets (70/30 split)
โ
Threshold optimization for business-specific metrics
โ
Feature engineering from time-series and contextual data
โ
Model evaluation with precision-recall trade-offs
โ
Hyperparameter tuning (scale_pos_weight, learning rate)
โ
REST API design with FastAPI and Pydantic
โ
Error handling and input validation
โ
Logging and monitoring for production systems
โ
Code organization with separation of concerns
โ
Documentation (README, API docs, inline comments)
โ
Model serialization (XGBoost JSON format)
โ
Real-time inference (<10ms latency)
โ
Analytics tracking for model performance
โ
Versioning (model config with metadata)
โ
Safety-critical ML (conservative threshold, human-in-loop)
- Synthetic data generation (10,000 samples)
- Exploratory data analysis
- Baseline Random Forest model
- XGBoost optimization and threshold tuning
- FastAPI deployment with Swagger docs
- Real-time analytics and logging
- Comprehensive documentation
- Day 6: GitHub repository setup with CI/CD
- Day 7: Docker containerization
- Add authentication (JWT tokens)
- Implement rate limiting
- Deploy to cloud (AWS Lambda or ECS)
- Add Prometheus metrics
- Build Grafana dashboard
- Implement A/B testing framework
- Add model explainability (SHAP values)
- Create React dashboard for operators
- Battery prediction model (XGBoost regressor)
- Coverage optimization (geospatial ML)
- Real-time model retraining pipeline
- Multi-model ensemble
This is a portfolio/demonstration project. Feedback and suggestions are welcome!
To suggest improvements:
- Open an issue describing the enhancement
- Fork the repository
- Create a feature branch
- Submit a pull request
- Medical Guardian Products
- XGBoost Documentation
- FastAPI Documentation
- Scikit-learn User Guide
- Handling Imbalanced Data
Salman Karim
AI & Digital Solutions Engineer | Machine Learning Enthusiast
- ๐ข Special Technology Zones Authority (STZA), Pakistan
- ๐ผ Frontend Developer @ Trolto (Real Estate Tech)
- ๐ BS Computer Science
- ๐๏ธ 18 years Boy Scouts Leadership
Connect:
- GitHub: @Salman-Pixel
- LinkedIn: Salman Karim
- Portfolio: SalmanKarim.is-a.dev
- Email: SaluKarim06@gmail.com
This project is licensed under the MIT License.
MIT License
Copyright (c) 2026 Salman Karim
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction...
See LICENSE file for full terms.
- Medical Guardian for inspiring this real-world healthcare use case
- Anthropic's Claude for technical guidance and code review
- XGBoost Team for the excellent gradient boosting library
- FastAPI Community for modern Python web framework
- Open Source Community for making ML accessible
This is a demonstration project for portfolio and educational purposes.
- โ Uses synthetic data (no real patient information)
- โ Not affiliated with or endorsed by Medical Guardian, Inc.
- โ Not intended for production medical use without proper validation
- โ Requires clinical trials and regulatory approval for real deployment
For actual medical alert systems, consult with:
- Healthcare professionals
- Regulatory compliance experts (FDA, HIPAA)
- Medical device certification authorities
Last Updated: February 2026
Version: 2.0.0
Status: Active Development ๐