El departamento de salud no puede inspeccionar todo a la vez. ¿Podemos predecir, antes de ir, qué restaurantes tienen más probabilidad de suspender la inspección inicial (14 puntos o más, sin nota A) para visitarlos primero? The health department can't inspect everything at once. Can we predict, before visiting, which restaurants are most likely to fail their initial inspection (14+ points, no A grade) so they can be visited first?
De 0,9998 a 0,67: tres versiones del mismo modeloFrom 0.9998 to 0.67: three versions of the same model
La primera versión clasificaba la nota (A frente a B/C) casi a la perfección. Leyendo la documentación oficial encontré el motivo: la nota se calcula directamente a partir de la puntuación (menos de 14 = A), y yo estaba usando esa puntuación como variable. Al quitarla, el modelo bajó a 0,83, pero seguía usando las infracciones anotadas en la misma inspección: explica la nota, pero no sirve para decidir a quién visitar. La versión final solo usa lo que se sabe antes de ir. The first version classified the grade (A vs B/C) almost perfectly. Reading the official documentation, I found out why: the grade is computed directly from the score (under 14 = A), and I was using that score as a feature. Removing it brought the model down to 0.83, but it still used the violations recorded in the same inspection: it explains the grade, but can't help decide whom to visit. The final version only uses what is known before going.
ROC-AUC con SCORE y el tipo de inspección. Reconstruye una regla conocida.
ROC-AUC with SCORE and inspection type. It rebuilds a known rule.
Sin SCORE ni tipo de inspección, pero con las infracciones de esa misma visita. Explica la nota a posteriori.
Without SCORE or inspection type, but with that same visit's violations. Explains the grade after the fact.
Historial del restaurante, cocina y distrito, validado en inspecciones posteriores a julio de 2025. Más bajo, pero sirve para priorizar. Restaurant history, cuisine and borough, validated on inspections after July 2025. Lower, but usable for prioritising.
Lo que importa al negocio: cuántos suspensos encuentras por visitaWhat matters to the business: failures found per visit
Si los inspectores visitan primero el 30 % de los restaurantes con más riesgo según el modelo, encuentran el 43 % de todos los suspensos. Al azar encontrarían el 30 %. También supera a la regla intuitiva de "ir primero a los que peor puntuaron la última vez". If inspectors first visit the model's riskiest 30% of restaurants, they find 43% of all failures. At random they would find 30%. It also beats the intuitive rule of "visit the worst scorers from last time first".
Curva de captura: % de suspensos encontrados según el % de restaurantes inspeccionadosCapture curve: % of failures found vs % of restaurants inspected
Conjunto de test: inspecciones iniciales desde julio de 2025 (no vistas en el entrenamiento)Test set: initial inspections since July 2025 (not seen during training)
El tipo de cocina marca diferencias de casi 3 a 1Cuisine type makes a nearly 3-to-1 difference
El 40 % de las inspecciones iniciales acaban en suspenso, pero varía mucho: los locales de donuts y hamburguesas (cadenas con procesos estandarizados) suspenden menos de 1 de cada 5 veces, y las cocinas caribeña, latinoamericana y china, más de la mitad. 40% of initial inspections end in a fail, but it varies a lot: donut and burger shops (chains with standardised processes) fail less than 1 time in 5, while Caribbean, Latin American and Chinese kitchens fail more than half the time.
% de inspecciones iniciales suspendidas por tipo de cocina% of initial inspections failed, by cuisine
Cocinas con al menos 800 inspecciones iniciales · línea discontinua = mediaCuisines with at least 800 initial inspections · dashed line = average
Qué se encuentra en las inspeccionesWhat inspectors actually find
Las infracciones más comunes son de limpieza de superficies y de plagas. Queens y el Bronx tienen algo más de notas B y C que Manhattan o Staten Island. The most common violations are about surface cleanliness and pests. Queens and the Bronx get slightly more B and C grades than Manhattan or Staten Island.
Infracciones más frecuentesMost frequent violations
Distribución de notas por distritoGrade distribution by borough
Cómo lo construíHow I built it
- Unidad de análisis: el CSV tiene una fila por infracción (288.829). Lo agrupé a una fila por inspección (92.026) antes de nada.Unit of analysis: the CSV has one row per violation (288,829). I grouped it to one row per inspection (92,026) first.
- Variables solo del pasado: puntuación, infracciones críticas y cierres de inspecciones anteriores, días desde la última visita, peor nota histórica, cocina, distrito y mes.Past-only features: score, critical violations and closures from previous inspections, days since last visit, worst past grade, cuisine, borough and month.
- Validación temporal: entreno con inspecciones hasta junio de 2025 (28.945) y evalúo con las posteriores (17.082), igual que se usaría en la realidad.Time-based validation: trained on inspections up to June 2025 (28,945) and evaluated on later ones (17,082), just as it would be used in practice.
- Modelo:
HistGradientBoostingClassifierde scikit-learn, con variables categóricas nativas y nulos (restaurantes sin historial) gestionados por el propio modelo.Model: scikit-learn'sHistGradientBoostingClassifier, with native categorical features and missing values (restaurants with no history) handled by the model. - Comparación justa: frente a elegir al azar y frente a una regla sencilla basada en la última puntuación.Fair comparison: against random selection and against a simple rule based on the last score.
Limitaciones y siguientes pasosLimitations & next steps
- Un ROC-AUC de 0,67 es moderado: el modelo ayuda a priorizar, no sustituye la inspección.A 0.67 ROC-AUC is moderate: the model helps prioritise, it doesn't replace inspections.
- El dataset público solo tiene historial completo desde 2022, así que muchos restaurantes tienen pocas inspecciones previas.The public dataset only has full history from 2022, so many restaurants have few prior inspections.
- Siguiente paso: añadir quejas ciudadanas del 311 y datos de licencias, que probablemente aportan señal antes de la inspección.Next step: add 311 citizen complaints and licensing data, which likely carry signal before an inspection.