Machine Learning & MLOps
Employee Attrition Prediction
Case study: A tech company's HR team
Is this employee likely to resign, and why? The model flags people at risk early enough for HR to act, and shows what drives each prediction.
Check an employee's riskThe problem
Case study: a tech company's HR team sees too many people resign and wants to understand why, then spot the employees at risk before they hand in their notice. The data came as three files, the HR system, the annual reviews and a staff survey, covering 1,470 employees, of whom 237 (16%) had left.
The work came in two stages. First, an analysis: what separates the people who left from those who stayed, and can a model predict it? Second, putting that model into production: an API another application can call, with input validation, a database, tests and automatic deployment.
What the demo does
You start from a ready-made profile or edit an employee record: age, pay, overtime, the four satisfaction scores, years in the company, years since the last promotion, business travel, and so on. The API returns the estimated probability of leaving, a risk level (low below 0.3, moderate up to 0.545, high above) and the decision at the 0.545 threshold.
Below the result, the factors that weighed on this particular prediction are listed in plain words, the ones that raised the risk and the ones that lowered it. They are SHAP values computed for that one employee.
For technical visitors, the API's documentation page lets you send your own requests, and every call is stored in the database with its result.
Results
- 2 in 3Departures caught (recall 0.68)
- In a test group of 294 employees the model never saw during training, 47 had left. It flagged 32 of them.
- 0.46Precision of the alerts
- 70 employees were flagged in that test group and 32 of them really left, so roughly one alert in two is right. For HR, a false alert costs a conversation; a missed departure costs a resignation nobody saw coming. The threshold leans toward catching departures.
- 97%Test coverage of the API (18 tests)
- 18 automated tests cover the data checks, the preprocessing, the model and the API routes. They run on every push, and nothing reaches production unless they pass.
On the 294 test employees (47 leavers), at the 0.545 threshold:
- recall 0.68 on departures: 32 of the 47 leavers flagged;
- precision 0.46: 32 real leavers among the 70 people flagged;
- F1 score 0.55.
I did not use accuracy as the main metric. With 84% of employees staying, a model that always answers "stays" gets 84% accuracy and catches nobody.
What drives departures, according to three methods that agree (XGBoost's own importance, permutation importance and SHAP):
- overtime, by far the strongest signal, and worse when combined with below-median pay;
- low satisfaction, averaged over the four survey scores;
- career stagnation: many years in the company or the same job without a promotion;
- participation in the employee savings plan goes with fewer departures.
These are correlations, not causes. Overtime may stand for stress or a difficult manager, which the data does not contain. Things like management quality or outside job offers are missing too, and the dataset is small (237 departures), which caps how far any model can go.
A finding from building this demo: when I replayed the 294 test employees through the original API, two features came out different from training. The "overtime and low pay" flag used a fixed 3,000 instead of the median salary (4,919), and one ratio divided by age instead of years of work. Through that API, the model caught 28 leavers out of 47 instead of 32. All 18 tests passed, because they checked shapes and ranges, not that the API gives the same answers as the notebook. The version behind this demo fixes both, and a new test checks that it catches the same 32 of 47.
How it's built
Architecture, stack and technical choices.
Diagram as text
flowchart LR
U["Client (web form, script)"] -->|"POST /predict, JSON, 25 fields"| V["Pydantic<br/>types and ranges"]
V --> P["Preprocessing<br/>25 fields to 38 features"]
P --> M["XGBoost<br/>threshold 0.545"]
M --> DB[("PostgreSQL<br/>inputs + outputs")]
M --> R["Response<br/>probability, risk level"]
GH["GitHub Actions"] -->|"lint + 18 tests on each push"| GH2["merge to main"]
GH2 -->|"automatic deploy"| HF["Hugging Face Spaces (Docker)"]Stack
- Python
- pandas
- scikit-learn
- XGBoost
- imbalanced-learn
- SHAP
- FastAPI
- Pydantic
- SQLAlchemy
- PostgreSQL
- SQLite
- Pytest
- GitHub Actions
- Docker
- Hugging Face Spaces
- uv
The analysis, step by step:
- Merge the three files on the employee ID (1,470 rows, 32 columns) and compare leavers with stayers, with statistical tests (Mann-Whitney, Kolmogorov-Smirnov).
- Prepare the data: drop constant columns, gender (too small a gap to use) and one column strongly correlated with others; group rare job titles; create 6 features (pay per year of experience, average satisfaction, overtime with low pay, years per promotion, time in job versus time in company, previous jobs per working year). 38 features in the end.
- Compare a baseline that always predicts "stays", a logistic regression and XGBoost. Out of the box, XGBoost memorized the training set (F1 0.91 on training data, 0.34 on test). Shallow trees (depth 2), subsampling and L1/L2 penalties fixed that.
- Handle the imbalance. Weighting the leavers (
scale_pos_weight5.19) beat SMOTE in 5-fold cross-validation: F1 0.54 against 0.47. - Pick the decision threshold from the precision-recall curve, built on out-of-fold predictions so the training data never scores itself: 0.545.
- Tune with GridSearchCV: 2,187 combinations, 5 folds repeated 3 times, with a custom scorer that applies the 0.545 threshold. Recall on test went from 0.62 to 0.68.
The production side:
- FastAPI with Pydantic models: a request with an age under 18, a satisfaction score outside 1 to 4 or a missing field gets a 422 error with the reason. The documentation page is generated from the same declarations.
- The model (a 272 KB joblib file) loads once at startup. The preprocessing reproduces the notebook's steps for a single row.
- SQLAlchemy with three tables: the training data, the inputs of every call with a timestamp, and the outputs linked to their input. PostgreSQL locally; SQLite in CI and on Hugging Face Spaces, where PostgreSQL is not available. The same code runs on both, only the connection URL changes.
- GitHub Actions: ruff and the 18 tests on every push and pull request; on merge to main, the files are pushed to Hugging Face Spaces, which builds the Docker image and starts the API. Branches
feature/*→dev→main, versions tagged. - One practical snag: Hugging Face rejected the model file through
git push, then through Git LFS, after moving to its new storage system. Uploading with thehf uploadcommand worked.
Next steps
- Write the feature engineering once, as a shared module or a scikit-learn pipeline saved with the model, instead of copying it from the notebook into the API. Copying is how the two features drifted apart.
- Add a parity test from day one: the API must give the same predictions as the notebook on the test set. It would have caught the problem above in seconds.
- Plan authentication and a request limit from the start (the original API had neither), and track the predictions over time to see when the incoming data starts to drift.
- Discuss the threshold with HR in terms of cost: how much a missed departure costs compared with an unnecessary conversation. The current threshold maximizes F1, which is a technical compromise, not a business one.