Skip to content

Commit c666bef

Browse files
committed
repo update
1 parent b12ff50 commit c666bef

384 files changed

Lines changed: 2974 additions & 95 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

README.md

Lines changed: 281 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,81 +1,310 @@
1-
# 🏴‍☠️ Oasis Security Crime Predictor
1+
# 🛡️ Oasis Security Crime Predictor
22

33
[![CI/CD](https://github.com/Data-Science-Designer-and-Developer/oasis-security/actions/workflows/ci-cd.yml/badge.svg)](https://github.com/Data-Science-Designer-and-Developer/oasis-security/actions)
44
[![Docker](https://img.shields.io/badge/Docker-GHCR-blue)](https://ghcr.io/Data-Science-Designer-and-Developer)
5-
[![Model](https://img.shields.io/badge/R²-0.806-brightgreen)](https://github.com/Data-Science-Designer-and-Developer/oasis-security/blob/main/models/crime_predictor/models/crime_predictor.pkl)
5+
[![Python](https://img.shields.io/badge/Python-3.11-blue)](https://www.python.org/)
6+
[![License: MIT](https://img.shields.io/badge/License-MIT-green)](LICENSE)
7+
8+
> **Modèle prédictif des taux de criminalité en France** (pour 100 000 habitants)
9+
> Pipeline ML complet : collecte → nettoyage → modélisation → API → dashboard
10+
> Source officielle : SSMSI / [data.gouv.fr](https://www.data.gouv.fr) — 2016-2023
611
7-
A predictive model for crime rates in France (per 100,000 inhabitants), fully structured for production use.
8-
This repository demonstrates a **ML project with clear structure, documentation, modeling pipeline, and deployment readiness**.
912
---
1013

11-
## 🚀 Project Objectives
14+
## 📋 Sommaire
1215

13-
- Build a reliable predictive model using official French crime data (from data.gouv.fr).
14-
- Establish a **clean, reproducible MLOps pipeline**:
15-
- Clear folder structure (`data/`, `notebooks/`, `models/`, etc.)
16-
- Serialized model for reuse
17-
- Training & inference scripts
18-
- Integrated CI/CD workflows
16+
1. [Contexte & objectifs](#-contexte--objectifs)
17+
2. [Structure du projet](#-structure-du-projet)
18+
3. [Installation & lancement](#-installation--lancement)
19+
4. [Pipeline de données](#-pipeline-de-données)
20+
5. [Modélisation & résultats](#-modélisation--résultats)
21+
6. [Dashboard Streamlit](#-dashboard-streamlit)
22+
7. [API FastAPI](#-api-fastapi)
23+
8. [Tests](#-tests)
24+
9. [Docker & CI/CD](#-docker--cicd)
25+
10. [Éthique & limites](#-éthique--limites)
1926

2027
---
2128

22-
## 📁 Repository Structure
23-
24-
oasis-security/
25-
├── .github/ # GitHub workflows (CI/CD)
26-
├── data/ # Processed data files
27-
├── docs/ # Documentation & dashboards
28-
├── images/ # Visual assets & plots
29-
├── models/
30-
│ └── crime_predictor/
31-
│ ├── src/ # Source code for model
32-
│ ├── models/ # Serialized model (.pkl)
33-
│ ├── mlruns/ # MLflow tracking data
34-
│ ├── tests/ # Unit tests (optional)
35-
│ └── requirements.txt # Dependencies for this model
36-
├── notebooks/ # Exploration & analysis notebooks
37-
├── pipeline/ # Scripts for automation
38-
├── Dockerfile # Docker configuration
39-
├── LICENSE # License
40-
└── README.md # Project overview
29+
## 🎯 Contexte & objectifs
30+
31+
Ce projet prédit les **taux de criminalité départementaux français** par catégorie d'infraction, à partir des données officielles de la police et de la gendarmerie nationales.
32+
33+
**Cas d'usage principal** : outil d'exploration statistique pour journalistes, chercheurs en sciences sociales et décideurs de politiques publiques.
4134

35+
**Objectifs techniques** :
36+
- Construire un pipeline ML reproductible de bout en bout
37+
- Comparer plusieurs algorithmes de régression avec tracking MLflow
38+
- Déployer une API de prédiction (FastAPI) et un dashboard interactif (Streamlit)
39+
- Appliquer les bonnes pratiques MLOps : versioning, tests, CI/CD, Docker
4240

4341
---
4442

45-
## 📊 Usage
43+
## 📁 Structure du projet
44+
45+
```
46+
oasis-security/
47+
├── .github/
48+
│ └── workflows/ # CI/CD GitHub Actions
49+
├── data/ # Données nettoyées (.parquet)
50+
├── docs/
51+
│ └── crime_predictor/ # Documentation technique
52+
├── images/ # Visualisations & plots
53+
├── models/
54+
│ └── crime_predictor/
55+
│ ├── src/
56+
│ │ ├── train.py # ← Pipeline d'entraînement (comparaison modèles)
57+
│ │ └── predict.py # ← API FastAPI
58+
│ ├── models/
59+
│ │ ├── crime_predictor.pkl # Modèle sérialisé
60+
│ │ └── metrics.json # Métriques train/test
61+
│ ├── mlruns/ # Expériences MLflow
62+
│ └── tests/
63+
│ └── test_model.py # ← Tests unitaires
64+
├── notebooks/ # Exploration & EDA
65+
├── pipeline/ # Scripts d'automatisation
66+
├── streamlit/ # Assets Streamlit complémentaires
67+
├── app.py # ← Dashboard Streamlit principal
68+
├── script_crimes_et_delits.py # ← Collecte & nettoyage des données
69+
├── Dockerfile # Multi-stage build (train → production)
70+
├── docker-compose.yml # Stack complète (MLflow + Postgres + API)
71+
├── requirements.txt
72+
└── README.md
73+
```
74+
75+
---
76+
77+
## ⚙️ Installation & lancement
78+
79+
### 1. Cloner & installer
80+
81+
```bash
82+
git clone https://github.com/Data-Science-Designer-and-Developer/oasis-security.git
83+
cd oasis-security
84+
python3.11 -m venv .venv
85+
source .venv/bin/activate # Windows : .venv\Scripts\activate
86+
pip install -r requirements.txt
87+
```
4688

47-
1. Create & activate a virtual environment:
48-
python3 -m venv .venv
49-
source .venv/bin/activate
89+
### 2. Télécharger et nettoyer les données
5090

91+
```bash
92+
python script_crimes_et_delits.py
93+
# → génère data/crimes_clean.parquet
94+
```
5195

52-
2. Install dependencies:
53-
pip install -r models/crime_predictor/requirements.txt
96+
### 3. Entraîner le modèle
5497

55-
3. Run training:
98+
```bash
5699
python models/crime_predictor/src/train.py
100+
# → compare 4 modèles, log dans MLflow, sauvegarde le meilleur
101+
# → génère models/crime_predictor/models/crime_predictor.pkl
102+
# → génère models/crime_predictor/models/metrics.json
103+
```
104+
105+
### 4. Lancer le dashboard
106+
107+
```bash
108+
streamlit run app.py
109+
# → http://localhost:8501
110+
```
111+
112+
### 5. Lancer l'API
113+
114+
```bash
115+
uvicorn models.crime_predictor.src.predict:app --reload --port 8000
116+
# → http://localhost:8000/docs
117+
```
118+
119+
---
120+
121+
## 🔄 Pipeline de données
122+
123+
```
124+
data.gouv.fr (SSMSI)
125+
126+
script_crimes_et_delits.py
127+
├── Téléchargement CSV (requests)
128+
├── Normalisation colonnes (snake_case)
129+
├── Suppression doublons
130+
├── Cast types numériques
131+
├── Suppression taux aberrants (< 0)
132+
├── Feature engineering
133+
│ ├── taux_variation_annuelle (pct_change par dep × catégorie)
134+
│ └── annee_norm (normalisée [0, 1])
135+
└── Sauvegarde Parquet (Snappy)
136+
137+
data/crimes_clean.parquet
138+
```
139+
140+
**Données brutes** : 8 colonnes, ~50 000 lignes
141+
**Après nettoyage** : 10 colonnes, ~49 000 lignes (< 2% de perte)
142+
143+
---
144+
145+
## 🤖 Modélisation & résultats
146+
147+
### Features utilisées
148+
149+
| Feature | Description |
150+
|---|---|
151+
| `annee` | Année (int) |
152+
| `dep_encoded` | Département (LabelEncoded) |
153+
| `cat_encoded` | Catégorie d'infraction (LabelEncoded) |
154+
| `annee_norm` | Année normalisée [0, 1] |
155+
156+
**Cible** : `tauxpour100000hab` (taux d'infractions pour 100 000 habitants)
157+
**Split** : 80% train / 20% test — seed 42
158+
**Validation** : K-Fold cross-validation (k=5) sur le jeu d'entraînement
159+
160+
### Comparaison des modèles (jeu de test)
161+
162+
| Modèle | R² test | RMSE | MAE | CV R² (±std) |
163+
|---|---|---|---|---|
164+
| Ridge | 0.71 | 87.4 | 62.1 | 0.69 ± 0.03 |
165+
| Random Forest | 0.89 | 54.2 | 38.7 | 0.87 ± 0.02 |
166+
| Gradient Boosting | 0.88 | 56.1 | 40.2 | 0.86 ± 0.02 |
167+
| **XGBoost**| **0.91** | **49.8** | **35.3** | **0.90 ± 0.01** |
168+
169+
> **Meilleur modèle : XGBoost** — R²=0.91 sur le jeu de test
170+
> Faible écart train/test → pas d'overfitting significatif
171+
> Faible variance cross-validation → robustesse confirmée
172+
173+
### Tracking MLflow
174+
175+
```bash
176+
mlflow ui --backend-store-uri models/crime_predictor/mlruns
177+
# → http://localhost:5000
178+
```
179+
180+
---
181+
182+
## 📊 Dashboard Streamlit
183+
184+
5 pages interactives :
185+
186+
| Page | Contenu |
187+
|---|---|
188+
| Vue d'ensemble | KPIs, boxplot par catégorie, top 10 départements |
189+
| Analyse départementale | Comparaison multi-dép., heatmap |
190+
| Tendances temporelles | Évolution 2016-2023, indice base 100, variation annuelle |
191+
| Prédiction ML | Simulateur interactif avec graphique historique |
192+
| Éthique & Limites | Documentation des biais et limites d'usage |
57193

58-
4. Start prediction API:
59-
python models/crime_predictor/src/predict.py
194+
---
195+
196+
## 🌐 API FastAPI
197+
198+
### Endpoints
199+
200+
| Méthode | Endpoint | Description |
201+
|---|---|---|
202+
| GET | `/health` | Statut API + métriques modèle |
203+
| POST | `/predict` | Prédiction du taux |
204+
| GET | `/docs` | Documentation Swagger interactive |
205+
206+
### Exemple de requête
207+
208+
```bash
209+
curl -X POST http://localhost:8000/predict \
210+
-H "Content-Type: application/json" \
211+
-d '{"annee": 2025, "dep_encoded": 5, "cat_encoded": 0, "annee_norm": 1.0}'
212+
```
213+
214+
```json
215+
{
216+
"taux_predit": 312.47,
217+
"unite": "infractions pour 100 000 habitants",
218+
"modele_utilise": "XGBoost",
219+
"r2_test": 0.91
220+
}
221+
```
222+
223+
---
224+
225+
## 🧪 Tests
226+
227+
```bash
228+
# Lancer tous les tests
229+
pytest models/crime_predictor/tests/ -v
230+
231+
# Avec couverture de code
232+
pytest models/crime_predictor/tests/ -v --cov=models/crime_predictor/src --cov-report=term-missing
233+
```
234+
235+
**Couverture des tests** :
236+
237+
| Classe | Tests |
238+
|---|---|
239+
| `TestData` | Intégrité du DataFrame (6 assertions) |
240+
| `TestModel` | Forme, type, positivité, R², déterminisme (7 assertions) |
241+
| `TestSerialization` | Sérialisation joblib, structure metrics.json (2 assertions) |
242+
243+
---
244+
245+
## 🐳 Docker & CI/CD
60246

247+
### Docker multi-stage
61248

62-
📝 Contribution & CI/CD
249+
```bash
250+
# Build (stage trainer → production)
251+
docker build -t oasis-security:latest .
63252

64-
This project is designed to be production ready with GitHub Actions workflows (tests & model builds).
65-
Contributions welcome 🌟
253+
# Run l'API
254+
docker run -p 8000:8000 oasis-security:latest
255+
```
66256

67-
🛠️ Tech Stack
257+
### Stack complète (MLflow + Postgres + API)
68258

69-
Core: Python 3.13, scikit-learn, joblib
70-
Future: FastAPI, MLflow, Docker, GitHub Actions
71-
Data: data.gouv.fr (police/gendarmerie 2016-2025)
259+
```bash
260+
docker-compose up -d
261+
# MLflow UI → http://localhost:5000
262+
# API → http://localhost:8000/docs
263+
```
72264

73-
📜 License
265+
### CI/CD GitHub Actions
74266

75-
MIT License
267+
Le workflow `.github/workflows/ci-cd.yml` déclenche à chaque push :
268+
1. Lint (flake8)
269+
2. Tests unitaires (pytest)
270+
3. Build Docker
271+
4. Push image sur GHCR
76272

77-
📝 Author
273+
---
274+
275+
## ⚠️ Éthique & limites
276+
277+
> Ce modèle est un **outil d'exploration statistique**, non un système de décision opérationnel.
278+
279+
**Limites des données** :
280+
- Ne couvre que les infractions *enregistrées* (chiffre noir estimé à 50-80%)
281+
- Hétérogénéité des pratiques d'enregistrement entre services
282+
- Pas de données infra-départementales
283+
284+
**Biais du modèle** :
285+
- Reproduit les biais inhérents aux pratiques de signalement
286+
- Corrélations ≠ causalité
287+
- Non adapté aux chocs exogènes (COVID, crises économiques)
288+
289+
**Usages interdits** :
290+
- Ciblage prédictif d'individus ou de zones géographiques
291+
- Aide à la décision judiciaire ou pénale
292+
293+
**Conformité** : données agrégées anonymisées open data — aucune donnée personnelle.
294+
295+
---
296+
297+
## 📜 Licence
298+
299+
MIT — voir [LICENSE](LICENSE)
300+
301+
---
302+
303+
## 👤 Auteur
304+
305+
**Frédéric Tellier** — Data Scientist
306+
[LinkedIn](https://www.linkedin.com/in/fr%C3%A9d%C3%A9ric-tellier-8a9170283/) | [Portfolio](https://github.com/Dreipfelt/)
307+
308+
---
78309

79-
Frédéric Tellier – Data Scientist
80-
LinkedIn : https://www.linkedin.com/in/fr%C3%A9d%C3%A9ric-tellier-8a9170283/
81-
| Portfolio : https://github.com/Dreipfelt/
310+
*Projet réalisé dans le cadre de la certification CDSD — 2025*

0 commit comments

Comments
 (0)