File size: 17,773 Bytes
08c2460 060e228 08c2460 f67be28 64fc6eb f67be28 64fc6eb f67be28 64fc6eb f67be28 b2999af f67be28 64fc6eb f67be28 64fc6eb f67be28 64fc6eb f67be28 49ff53a f67be28 5b9ff4c 49ff53a f67be28 b2999af 49ff53a f67be28 b2999af f67be28 49ff53a f67be28 64fc6eb f67be28 64fc6eb f67be28 64fc6eb f67be28 49ff53a f67be28 64fc6eb f67be28 64fc6eb f67be28 49ff53a f67be28 49ff53a f67be28 64fc6eb f67be28 64fc6eb f67be28 49ff53a f67be28 5b9ff4c 49ff53a 5b9ff4c f67be28 49ff53a f67be28 49ff53a f67be28 b2999af f67be28 64fc6eb f67be28 64fc6eb f67be28 64fc6eb f67be28 64fc6eb f67be28 b2999af 49ff53a f67be28 | 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 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | ---
title: HR Attrition Prediction API - Futurisys
colorFrom: blue
colorTo: green
sdk: docker
pinned: false
---
<a id="readme-top"></a>
[![Contributors][contributors-shield]][contributors-url]
[![Forks][forks-shield]][forks-url]
[![Stargazers][stars-shield]][stars-url]
[![Issues][issues-shield]][issues-url]
<br />
<div align="center">
<h3 align="center">HR Attrition Prediction API — Futurisys</h3>
<p align="center">
A production-grade REST API that predicts employee attrition using a Gradient Boosting pipeline with SHAP explainability, deployed on Hugging Face Spaces.
<br />
<a href="https://github.com/KL38/OC_P5_v2"><strong>Explore the docs »</strong></a>
<br />
<br />
<a href="https://huggingface.co/spaces/KLEB38/OC_P5">View Live Demo</a>
·
<a href="https://github.com/KL38/OC_P5_v2/issues/new?labels=bug&template=bug-report---.md">Report Bug</a>
·
<a href="https://github.com/KL38/OC_P5_v2/issues/new?labels=enhancement&template=feature-request---.md">Request Feature</a>
</p>
</div>
<details>
<summary>Table of Contents</summary>
<ol>
<li>
<a href="#about-the-project">About The Project</a>
<ul>
<li><a href="#built-with">Built With</a></li>
</ul>
</li>
<li>
<a href="#getting-started">Getting Started</a>
<ul>
<li><a href="#prerequisites">Prerequisites</a></li>
<li><a href="#installation">Installation</a></li>
</ul>
</li>
<li><a href="#usage">Usage</a></li>
<li><a href="#running-tests">Running Tests</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#acknowledgments">Acknowledgments</a></li>
</ol>
</details>
---
## About The Project
**Futurisys** is a tech consulting firm used as the business context for this OpenClassrooms Data Science project (Project 5). The objective is to help HR departments proactively identify employees at risk of attrition before they leave.
This project delivers a complete, containerised ML system:
- A **Gradient Boosting classifier** trained on HR data and serialised into a Scikit-Learn pipeline with automated preprocessing
- **Custom feature engineering** — overall satisfaction score, expertise inconsistency (department vs. study domain mismatch), managerial stagnation, and development stagnation signals
- A **custom classification threshold of 0.37** (tuned for recall on the attrition class rather than the default 0.50)
- A **FastAPI REST API** with full input validation via Pydantic, exposing two prediction modes: submit raw employee data (`POST /predict`) or look up an existing employee by ID (`GET /predict/{id_employee}`)
- **SHAP-based explainability** — every prediction is accompanied by the top 5 most influential features and their direction of impact
- **PostgreSQL prediction logging** — every prediction (inputs, result, SHAP factors) is automatically stored in a `predictions_log` table for auditability. A separate `predictions_log_test` table is used in CI/CD and local test runs to keep production data untouched
- A complete **CI/CD pipeline** via GitHub Actions that runs the full test suite on every push before deploying to Hugging Face Spaces
<p align="right">(<a href="#readme-top">back to top</a>)</p>
### Built With
* [![Python][Python-badge]][Python-url]
* [![FastAPI][FastAPI-badge]][FastAPI-url]
* [![scikit-learn][sklearn-badge]][sklearn-url]
* [![pandas][pandas-badge]][pandas-url]
* [![SHAP][SHAP-badge]][SHAP-url]
* [![Supabase][Supabase-badge]][Supabase-url]
* [![PostgreSQL][Postgres-badge]][Postgres-url]
* [![SQLAlchemy][SQLAlchemy-badge]][SQLAlchemy-url]
* [![Docker][Docker-badge]][Docker-url]
* [![GitHub Actions][GHActions-badge]][GHActions-url]
### Architecture
```mermaid
flowchart TD
CSV["📄 3 CSV Files"]
subgraph DB["🗄️ Supabase / PostgreSQL"]
EMP["👥 Employee tables + Full View"]
LOG["📝 predictions_log"]
end
subgraph CICD["🔄 CI/CD Pipeline"]
GH["📦 GitHub Repository<br/>(FastAPI code + model)"]
ACTIONS["⚙️ GitHub Actions<br/>(pytest → deploy)"]
GH -->|push trigger| ACTIONS
end
subgraph HF["🤗 Hugging Face Spaces"]
subgraph DOCKER["🐳 Docker Container"]
API["⚡ FastAPI<br/>GET /predict/{id_employee}<br/>POST /predict"]
end
end
CSV -->|insert_data.py| DB
CSV -->|model training| CICD
ACTIONS -->|deploy| HF
EMP -->|employee lookup| API
API -->|log predictions| LOG
```
<p align="right">(<a href="#readme-top">back to top</a>)</p>
---
## Getting Started
### Prerequisites
- Python 3.13+
- A PostgreSQL database (local or remote)
- Docker (for containerised deployment)
- Git
### Installation
#### Option 1 — Run locally with Python
1. Clone the repository
```sh
git clone https://github.com/KL38/OC_P5_v2.git
cd OC_P5_v2
```
2. Install dependencies
```sh
pip install -r requirements.txt
```
3. Create a `.env` file at the project root with your database connection string
```sh
DATABASE_URL=postgresql://user:password@host:5432/dbname
```
4. Start the API
```sh
uvicorn app.main:app --reload
```
The API is available at `http://127.0.0.1:8000`. The interactive Swagger UI is at `http://127.0.0.1:8000/docs`.
#### Option 2 — Run with Docker
1. Build the image
```sh
docker build -t futurisys-api .
```
2. Run the container, passing the database URL as an environment variable
```sh
docker run -p 7860:7860 -e DATABASE_URL=postgresql://user:password@host:5432/dbname futurisys-api
```
The API is available at `http://localhost:7860`.
<p align="right">(<a href="#readme-top">back to top</a>)</p>
---
## Usage
### Endpoints
| Method | Endpoint | Description |
|--------|---------------------------|--------------------------------------------------------------------|
| `GET` | `/` | Health check — returns a welcome message |
| `GET` | `/predict/{id_employee}` | Fetches an employee from the database by ID and returns a prediction |
| `POST` | `/predict` | Predicts employee attrition risk from a submitted JSON payload |
### `POST /predict` — Input Schema
All fields use their **French alias** as the JSON key.
| JSON key | Type | Accepted values / notes |
|-----------------------------------------|--------|---------------------------------------------------------------------|
| `Genre` | string | `"M"` or `"F"` |
| `Statut Marital` | string | `"Marié(e)"`, `"Célibataire"`, `"Divorcé(e)"` |
| `Département` | string | `"Consulting"`, `"Commercial"`, `"Ressources Humaines"` |
| `Poste` | string | `"Consultant"`, `"Manager"`, `"Tech Lead"`, … |
| `Domaine d'étude` | string | `"Infra & Cloud"`, `"Marketing"`, `"Ressources Humaines"`, … |
| `Fréquence de déplacement` | string | `"Aucun"`, `"Occasionnel"`, `"Frequent"` |
| `Heures supplémentaires` | string | `"Oui"` or `"Non"` |
| `Âge` | int | |
| `Revenu mensuel` | int | |
| `Nombre d'expériences précédentes` | int | |
| `Années d'expérience totale` | int | |
| `Années dans l'entreprise` | int | |
| `Années dans le poste actuel` | int | |
| `Nombre de formations suivies` | int | |
| `Distance domicile-travail` | int | |
| `Niveau d'éducation` | int | |
| `Années depuis la dernière promotion` | int | |
| `Années sous responsable actuel` | int | |
| `Satisfaction environnement` | int | 1–4 |
| `Satisfaction nature du travail` | int | 1–4 |
| `Satisfaction équipe` | int | 1–4 |
| `Satisfaction équilibre pro/perso` | int | 1–4 |
| `Note évaluation précédente` | int | 1–4 |
| `Note évaluation actuelle` | int | 1–4 |
| `Augmentation salaire précédente` | string | Percentage as string, e.g. `"18%"` |
### Example Request
```bash
curl -X POST "http://localhost:7860/predict" \
-H "Content-Type: application/json" \
-d '{
"Genre": "M",
"Statut Marital": "Marié(e)",
"Département": "Consulting",
"Poste": "Consultant",
"Domaine d'\''étude": "Infra & Cloud",
"Fréquence de déplacement": "Occasionnel",
"Heures supplémentaires": "Non",
"Âge": 32,
"Revenu mensuel": 4883,
"Nombre d'\''expériences précédentes": 1,
"Années d'\''expérience totale": 10,
"Années dans l'\''entreprise": 10,
"Années dans le poste actuel": 4,
"Nombre de formations suivies": 3,
"Distance domicile-travail": 7,
"Niveau d'\''éducation": 2,
"Années depuis la dernière promotion": 1,
"Années sous responsable actuel": 1,
"Satisfaction environnement": 4,
"Note évaluation précédente": 3,
"Satisfaction nature du travail": 3,
"Satisfaction équipe": 1,
"Satisfaction équilibre pro/perso": 3,
"Note évaluation actuelle": 3,
"Augmentation salaire précédente": "18%"
}'
```
### Example Response
```json
{
"statut_employe": "The staff has a LOW probability of resigning",
"probability_score": 0.28,
"model_threshold": 0.37,
"note": "Decision based on a strategic threshold of 0.37, not 0.50",
"top_5_factors": {
"revenu_mensuel": {
"interpretation": "Primary driver — decreases resignation risk",
"feature_value": 4883.0
},
"annees_dans_l_entreprise": {
"interpretation": "Strong factor — decreases resignation risk",
"feature_value": 10.0
},
"statut_marital_Célibataire": {
"interpretation": "Moderate factor — decreases resignation risk",
"feature_value": "encoded"
},
"distance_domicile_travail": {
"interpretation": "Contributing factor — decreases resignation risk",
"feature_value": 7.0
},
"overall_satisfaction": {
"interpretation": "Notable factor — decreases resignation risk",
"feature_value": 2.75
}
}
}
```
### Response Schema
| Field | Type | Description |
|-------------------|--------|-----------------------------------------------------------------------------|
| `statut_employe` | string | Human-readable verdict: `"LOW probability of resigning"` or `"HIGH probability of resigning"` |
| `probability_score` | float | Raw model probability of resignation (0–1), rounded to 2 decimal places |
| `model_threshold` | float | Decision threshold applied — `0.37` (prediction is `HIGH` if score ≥ 0.37) |
| `note` | string | Reminder that the threshold is strategically set to 0.37, not the default 0.50 |
| `top_5_factors` | object | Top 5 features ranked by absolute SHAP value (most influential first) |
Each entry in `top_5_factors` is keyed by the **feature name** and contains:
| Sub-field | Type | Description |
|-------------------|----------------|-----------------------------------------------------------------------------|
| `interpretation` | string | Rank label (`Primary driver`, `Strong factor`, `Moderate factor`, `Contributing factor`, `Notable factor`) followed by the direction of impact (`increases` or `decreases resignation risk`) |
| `feature_value` | float \| string | The actual value of that feature for this employee. Returns `"encoded"` for one-hot encoded categorical features (e.g. `statut_marital_Célibataire`) whose original value is lost after encoding |
> The interactive Swagger UI (auto-generated by FastAPI) is available at `/docs` on any running instance.
<p align="right">(<a href="#readme-top">back to top</a>)</p>
---
## Running Tests
The test suite covers:
- **Unit tests** (`test_unit.py`) — feature engineering helpers (`inconsistency`, `promotion`, `developpement`, `interpret_shap`)
- **Functional tests** (`test_functional.py`) — all API endpoints (valid predictions, input validation HTTP 422, employee lookup by ID, warning logging), plus a `TestDatabase` class that verifies prediction logs are written to `predictions_log_test`, that the production table is untouched, and that both the log table and the `employees_full` view have the expected schema
A live `DATABASE_URL` is required — the test suite includes database write tests. Setting `TESTING=true` routes all prediction logs to `predictions_log_test` instead of the production `predictions_log` table, keeping production data untouched.
```sh
TESTING=true DATABASE_URL=postgresql://user:password@host:5432/dbname pytest tests/ -v --cov=app --cov-report=term-missing
```
The same configuration is used in CI (GitHub Actions): `DATABASE_URL` is injected from a repository secret, and `TESTING` is hardcoded to `"true"` directly in the workflow file.
<p align="right">(<a href="#readme-top">back to top</a>)</p>
---
## Contact
Kevin L. — [GitHub @KL38](https://github.com/KL38)
Project Link: [https://github.com/KL38/OC_P5_v2](https://github.com/KL38/OC_P5_v2)
Live Demo: [https://huggingface.co/spaces/KLEB38/OC_P5](https://huggingface.co/spaces/KLEB38/OC_P5)
<p align="right">(<a href="#readme-top">back to top</a>)</p>
---
## Acknowledgments
* [FastAPI](https://fastapi.tiangolo.com/) — high-performance async web framework
* [SHAP](https://shap.readthedocs.io/) — model explainability
* [scikit-learn](https://scikit-learn.org/) — ML pipeline and Gradient Boosting classifier
* [Hugging Face Spaces](https://huggingface.co/spaces) — Docker-based free deployment
* [othneildrew/Best-README-Template](https://github.com/othneildrew/Best-README-Template) — README structure
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- MARKDOWN LINKS & IMAGES -->
[contributors-shield]: https://img.shields.io/github/contributors/KL38/OC_P5_v2.svg?style=for-the-badge
[contributors-url]: https://github.com/KL38/OC_P5_v2/graphs/contributors
[forks-shield]: https://img.shields.io/github/forks/KL38/OC_P5_v2.svg?style=for-the-badge
[forks-url]: https://github.com/KL38/OC_P5_v2/network/members
[stars-shield]: https://img.shields.io/github/stars/KL38/OC_P5_v2.svg?style=for-the-badge
[stars-url]: https://github.com/KL38/OC_P5_v2/stargazers
[issues-shield]: https://img.shields.io/github/issues/KL38/OC_P5_v2.svg?style=for-the-badge
[issues-url]: https://github.com/KL38/OC_P5_v2/issues
[Python-badge]: https://img.shields.io/badge/Python-3776AB?style=for-the-badge&logo=python&logoColor=white
[Python-url]: https://www.python.org/
[FastAPI-badge]: https://img.shields.io/badge/FastAPI-009688?style=for-the-badge&logo=fastapi&logoColor=white
[FastAPI-url]: https://fastapi.tiangolo.com/
[sklearn-badge]: https://img.shields.io/badge/scikit--learn-F7931E?style=for-the-badge&logo=scikit-learn&logoColor=white
[sklearn-url]: https://scikit-learn.org/
[pandas-badge]: https://img.shields.io/badge/pandas-150458?style=for-the-badge&logo=pandas&logoColor=white
[pandas-url]: https://pandas.pydata.org/
[SHAP-badge]: https://img.shields.io/badge/SHAP-FF6B6B?style=for-the-badge&logoColor=white
[SHAP-url]: https://shap.readthedocs.io/
[Supabase-badge]: https://img.shields.io/badge/Supabase-3ECF8E?style=for-the-badge&logo=supabase&logoColor=white
[Supabase-url]: https://supabase.com/
[Postgres-badge]: https://img.shields.io/badge/PostgreSQL-4169E1?style=for-the-badge&logo=postgresql&logoColor=white
[Postgres-url]: https://www.postgresql.org/
[SQLAlchemy-badge]: https://img.shields.io/badge/SQLAlchemy-D71F00?style=for-the-badge&logo=sqlalchemy&logoColor=white
[SQLAlchemy-url]: https://www.sqlalchemy.org/
[Docker-badge]: https://img.shields.io/badge/Docker-2496ED?style=for-the-badge&logo=docker&logoColor=white
[Docker-url]: https://www.docker.com/
[GHActions-badge]: https://img.shields.io/badge/GitHub_Actions-2088FF?style=for-the-badge&logo=github-actions&logoColor=white
[GHActions-url]: https://github.com/features/actions
|