This document describes the automatic ML model retraining system that has been implemented to automatically retrain the anomaly detection model and regenerate trust scores every time a user submits an adverse event report.
- Purpose: Automatically retrain the Isolation Forest ML model with new user reports
- Key Features:
- Converts user symptom reports into AEFI-formatted features
- Incrementally retrains the anomaly detection model
- Updates and saves model artifacts (model.pkl, scaler.pkl, features.pkl)
- Symptom-to-diagnosis mapping for consistent feature engineering
- Updated: Now returns the saved report as a dict for model retraining
- Purpose: Stores user reports in CSV and provides data for retraining
- New Components:
ModelRetrainingServiceinitialization on startup- Async background thread for model retraining after report submission
- New endpoint
/api/trust-scores/livewith model status info
- Flow:
- User submits report →
POST /api/report-symptom - Report saved to CSV
- Background thread triggers
retrain_with_user_reports() - AEFI data reloaded with updated trust scores
- Frontend polls for updated scores
- User submits report →
API Service (services/api.js):
- New function:
getTrustScoresLive()- fetches trust scores with model status
Dashboard Page (pages/DashboardPage.js):
- Uses
getTrustScoresLive()instead ofgetTrustScores() - Auto-refresh every 3 seconds when
retraining_in_progress = true - Displays "Updating trust scores..." alert with spinner
Feedback Page (pages/FeedbackPage.js):
- Success message now mentions trust scores are being updated
- Blue info box: "Trust scores are being updated with your report. Check the dashboard to see the latest scores!"
API Service (services/api.js):
- New function:
getTrustScoresLive()- same as web
Dashboard Screen (screens/DashboardScreen.js):
- Uses
getTrustScoresLive() - Auto-refresh while retraining is in progress
- Displays warning alert: "Updating trust scores with latest user reports"
Feedback Screen (screens/FeedbackScreen.js):
- Success screen includes blue info box mentioning trust scores update
Request:
{
"batch_id": "COV_AN_202312_00070",
"symptoms": ["fever", "headache"],
"severity": "moderate",
"onset_days": 2,
"notes": "Optional custom description"
}Response:
{
"success": true,
"report_id": "RPT_1707406943517",
"message": "Report submitted successfully. Trust scores are being updated.",
"retraining_started": true
}Returns the aggregated trust scores for all vaccines.
Response:
{
"vaccines": [
{
"vaccine_name": "COVAXIN",
"total_batches": 150,
"trust_score": {
"score": 0.92,
"total_cases": 854,
"causal_cases": 68,
"classification_breakdown": {...}
},
"common_side_effects": [...]
}
],
"model_status": {
"retraining_in_progress": true,
"last_retrain_time": 1707406943.517,
"timestamp": 1707406945.123
}
}- User submits symptoms through FeedbackPage/FeedbackScreen
- Backend receives POST request to
/api/report-symptom - Report is saved to
user_reports.csv - Async retraining thread starts:
- Converts user report to AEFI features
- Combines with existing processed AEFI data
- Trains new Isolation Forest model
- Saves updated model artifacts
- Reloads AEFI_DF in memory
- Backend returns
"retraining_started": true - Frontend/Mobile shows success message with note about updates
- Frontend/Mobile starts auto-polling
/api/trust-scores/live - When
retraining_in_progress = false, polling stops - User sees updated trust scores on Dashboard
- Based on: WHO causality assessment classifications (A4, B1, B2, C)
- Formula:
Trust Score = 1 - (Causal Cases / Total Cases) - Range: 0.0 (no trust) to 1.0 (complete trust)
User reports are converted to AEFI features:
- Symptoms → Diagnosis codes (e.g., fever → DIAGNOSIS_FEVER)
- Severity → Outcomes & Hospitalization (mild → home, severe → hospitalized)
- Onset days → Temporal features
- Vaccine name → One-hot encoded vaccine columns
- Interval: 3 seconds (configurable)
- Trigger: When
modelStatus.retraining_in_progress === true - Stop: Automatically stops when retraining completes
Located in ModelRetrainingService._train_isolation_forest():
- Algorithm: Isolation Forest (sklearn)
- Estimators: 300 trees
- Contamination: 0.1 (10% anomalies)
- Max Jobs: -1 (use all CPU cores)
backend/services/model_retraining_service.py- Complete retraining servicetest_model_retraining.py- Test script for verification
backend/app.py- Added retraining logic and new endpointbackend/services/report_service.py- Returns report dictfrontend/src/services/api.js- AddedgetTrustScoresLive()frontend/src/pages/DashboardPage.js- Auto-refresh logicfrontend/src/pages/FeedbackPage.js- Success message updatevaxtrust-mobile/src/services/api.js- AddedgetTrustScoresLive()vaxtrust-mobile/src/screens/DashboardScreen.js- Auto-refresh + status alertvaxtrust-mobile/src/screens/FeedbackScreen.js- Success message update
vaxtrust_covid_data/user_reports.csv- Fixed header with "other" columnbackend/data/user_reports.csv- Fixed header with "other" column
Run the test script to verify model retraining:
cd /home/frosfres/Documents/project/Vaxtrust
./.venv/bin/python test_model_retraining.pyExpected output:
Testing model retraining service...
==================================================
Retraining Result:
Success: True
Message: Model retrained successfully
Records Processed: 2
Total Records: 3
Timestamp: 2026-02-08T15:43:03.517381
✓ Model retraining completed successfully!
==================================================
- Retraining Time: ~1-2 seconds per report (background thread)
- Memory Usage: Loads AEFI data into memory (~100MB for full dataset)
- Scalability: Isolation Forest scales well with feature count, not sample count
- Polling: 3-second interval strikes balance between freshness and server load
- WebSocket Integration: Real-time push updates instead of polling
- Batch Processing: Accumulate N reports before retraining
- Model Versioning: Save historical model versions
- Performance Metrics: Track model accuracy metrics over time
- Distributed Training: Use multi-processing for faster retraining
- Database Integration: Move from CSV to SQL database for analytics
- Check Flask app logs for errors during retraining
- Verify
RETRAINING_SERVICEis initialized - Ensure
report_service.pyreturns dict fromsave_user_report()
- Check browser console for API errors
- Verify
/api/trust-scores/liveendpoint returnsmodel_status - Check auto-refresh interval (should be 3 seconds)
- Check logs for feature column mismatches
- Verify AEFI CSV columns exist
- Ensure scikit-learn and pandas are installed
For questions or issues, refer to the main README.md and project documentation.