A FastAPI application that serves churn predictions from the XGBoost model built in Part 3. Includes input validation, batch prediction, test suite, Docker support, and a monitoring/responsible-use plan.
├── README.md
├── app/
│ └── main.py ← FastAPI application (3 endpoints)
├── train_model.py ← Script to train & save the model
├── model.pkl ← Saved model (generated by train_model.py or Part 3)
├── feature_cols.pkl ← Feature column list (generated)
├── metrics.json ← Model metrics (generated)
├── tests/
│ ├── __init__.py
│ └── test_api.py ← 6 test cases
├── monitoring_plan.md ← Monitoring + responsible use guidelines
├── Dockerfile ← Docker setup
├── requirements.txt
pip install -r requirements.txt# Download CSVs to a data/ folder first
python train_model.py --data_dir data/This creates model.pkl, feature_cols.pkl, and metrics.json.
uvicorn app.main:app --reload --port 8000API docs available at: http://localhost:8000/docs
curl http://localhost:8000/healthResponse:
{
"status": "ok",
"model_loaded": true,
"threshold": 0.35
}curl -X POST http://localhost:8000/predict \
-H "Content-Type: application/json" \
-d '{
"recency_days": 45,
"frequency_180d": 5,
"monetary_180d": 3200.0,
"return_rate_180d": 0.1,
"avg_discount_pct_180d": 0.15,
"avg_rating_180d": 4.2,
"category_diversity_180d": 3,
"ticket_count_90d": 1,
"negative_ticket_rate_90d": 0.0,
"avg_resolution_hours_90d": 12.0,
"days_since_signup": 300,
"sessions_30d": 8,
"product_views_30d": 20,
"cart_adds_30d": 3,
"wishlist_adds_30d": 1,
"abandoned_carts_30d": 1,
"email_opens_30d": 5,
"campaign_clicks_30d": 2,
"last_visit_days_ago": 3,
"city_tier": "Tier 1",
"age_group": "25-34",
"acquisition_channel": "Google Search",
"loyalty_tier": "Silver",
"preferred_category": "Skin Care",
"marketing_consent": "Yes"
}'Response:
{
"churn_probability": 0.2341,
"predicted_class": 0,
"risk_level": "low",
"risk_explanation": "Customer shows healthy engagement across key metrics."
}curl -X POST http://localhost:8000/batch_predict \
-H "Content-Type: application/json" \
-d '{"customers": [<customer1>, <customer2>, ...]}'Response:
{
"predictions": [...],
"total_customers": 2,
"high_risk_count": 1
}pytest tests/test_api.py -vTests cover: health check, single prediction, batch prediction, invalid input validation (bad city_tier, negative recency), empty batch.
docker build -t churn-api .
docker run -p 8000:8000 churn-apiNote: To use Docker with a trained model, either:
- Copy
model.pklandfeature_cols.pklinto the build context, OR - Mount a volume with the data CSVs and uncomment the
RUN python train_model.pyline in the Dockerfile
Model trained on rfm_modeling_snapshot.csv from: https://drive.google.com/drive/folders/1PmLapJI1VSDgvl_AxARNKwM1MCd3WFX0?usp=sharing