← Todos los proyectosAll projects
PythonPandasSciPyScikit-learnpyprojLeaflet

Siniestralidad vial en Madrid 2024Road accidents in Madrid, 2024

Un análisis del parte de accidentes del Ayuntamiento de Madrid para encontrar cuándo, dónde y por qué se producen los accidentes con heridos graves, y un modelo de cribado para priorizar las pruebas de alcohol. An analysis of Madrid City Council's accident records to find out when, where and why accidents with serious injuries happen, plus a screening model to prioritise alcohol tests.

DatosData: Portal de datos abiertos de MadridMadrid open data portal PeriodoPeriod: 2024 CódigoCode: madrid_accidents.py
Pregunta de negocioBusiness question

¿En qué franja horaria se producen los accidentes más graves (ingreso de más de 24 h o fallecidos) y qué condiciones (tiempo, tipo de accidente, alcohol…) influyen en ello? At what time of day do the most serious accidents happen (hospital stay over 24 h or deaths), and which conditions (weather, accident type, alcohol…) influence them?

01

Una fila no es un accidenteA row is not an accident

El CSV tiene una fila por persona implicada (49.330), no por accidente. Casi la mitad de las filas pertenecen a accidentes con 3 o más personas, así que contar filas exagera los accidentes múltiples. Lo primero fue agrupar por expediente: 20.692 accidentes. Esa decisión cambió varias conclusiones de mi primera versión. The CSV has one row per person involved (49,330), not per accident. Almost half the rows belong to accidents with 3 or more people, so counting rows overweights multi-person accidents. The first step was grouping by case number: 20,692 accidents. That decision changed several conclusions from my first version.

Accidentes por día de la semana y horaAccidents by weekday and hour

El volumen sigue al reloj laboral: el pico es el viernes a las 14:00 · pasa el cursor por cada celdaVolume follows the working day: the peak is Friday at 2 pm · hover any cell

menosfewermásmore
02

Volumen y gravedad no coinciden: la madrugada es la franja más graveVolume and severity don't match: late night is the most severe time

La tarde acumula más accidentes graves en número (230) porque es cuando más se circula, pero en proporción es la menos grave (2,24 %). La madrugada (0–5 h) es la más grave: el 3,54 % de sus accidentes, y el 4,15 % la de fin de semana. Las diferencias son estadísticamente significativas (χ², p < 0,001). Afternoons have the most serious accidents in absolute terms (230) because that's when traffic peaks, but proportionally they are the least severe (2.24%). Late night (midnight–5 am) is the most severe: 3.54% of its accidents, and 4.15% at weekends. The differences are statistically significant (χ², p < 0.001).

% de accidentes graves por franja horaria y tipo de día% of serious accidents by time of day and type of day

Madrugada 0–5 h · mañana 6–11 h · tarde 12–19 h · noche 20–23 h · la línea discontinua es la mediaLate night 0–5 · morning 6–11 · afternoon 12–19 · evening 20–23 · dashed line = average

03

El factor que más pesa en la gravedad: los atropellosThe biggest driver of severity: pedestrian collisions

Los atropellos son solo el 6 % de los accidentes, pero el 12,5 % acaban con heridos graves o fallecidos: 4,7 veces la media. Mirando a las personas, el 11 % de los peatones implicados sufre lesiones graves, frente al 0,9 % de los conductores. Pedestrian collisions are only 6% of accidents, yet 12.5% end with serious injuries or deaths: 4.7 times the average. Looking at people, 11% of pedestrians involved are seriously injured, versus 0.9% of drivers.

% de accidentes con heridos graves o fallecidos, por tipo% of accidents with serious injuries or deaths, by type

Tipos con al menos 150 accidentes · la línea discontinua es la media de la ciudadTypes with at least 150 accidents · dashed line = city average

04

El alcohol explica cuándo, no cuán graveAlcohol explains when, not how severe

De madrugada da positivo el 11 % de las personas con prueba, frente al 2,9 % global. Los positivos se concentran en los accidentes en que el vehículo se queda solo: salida de la vía (14,9 %), vuelco (12,7 %) y choque contra obstáculo (8,6 %). Pero dar positivo no va ligado a lesiones más graves: 1,26 % de graves entre positivos frente a 1,21 % entre negativos. Late at night, 11% of people tested are positive, versus 2.9% overall. Positives concentrate in single-vehicle accidents: running off the road (14.9%), rollovers (12.7%) and hitting fixed objects (8.6%). But testing positive is not linked to more serious injuries: 1.26% serious among positives vs 1.21% among negatives.

% de positivos en alcohol por franja y tipo de día% testing positive for alcohol by time and type of day

Personas con prueba registradaPeople with a recorded test

% de positivos por tipo de accidente% testing positive by accident type

Tipos con al menos 150 personas · la línea discontinua es la mediaTypes with at least 150 people · dashed line = average

05

La lluvia no hace los accidentes más graves (y corregí mi primera conclusión)Rain doesn't make accidents more serious (and I corrected my first conclusion)

En la primera versión concluí que la lluvia aumentaba la gravedad, pero había promediado una escala de gravedad por persona. Medido por accidente, con lluvia la proporción de graves baja (2,0 % frente a 3,1 %; χ², p = 0,03 excluyendo el tiempo "Desconocido"). Una explicación probable: con lluvia se circula más despacio. In my first version I concluded that rain increased severity, but I had averaged a severity scale per person. Measured per accident, the share of serious accidents goes down in rain (2.0% vs 3.1%; χ², p = 0.03 excluding "Unknown" weather). A likely explanation: people drive more slowly in the rain.

% de accidentes graves según el tiempo% of serious accidents by weather

Estados con al menos 50 accidentesConditions with at least 50 accidents

06

Dónde: el mapa de los accidentes gravesWhere: a map of serious accidents

Los 552 accidentes graves, geolocalizados (convertí las coordenadas UTM ETRS89 del Ayuntamiento a latitud/longitud con pyproj). Se agrupan en el centro y en las grandes vías de entrada. Haz zoom para ver los puntos concretos. All 552 serious accidents, geolocated (I converted the council's UTM ETRS89 coordinates to latitude/longitude with pyproj). They cluster in the city centre and along the main arterial roads. Zoom in to see individual points.

Mapa baseBase map: © OpenStreetMap

Distritos: volumen frente a gravedadDistricts: volume vs severity

Cada punto es un distrito. Los distritos con más accidentes no son los que tienen más proporción de graves.Each dot is a district. The districts with the most accidents are not the ones with the highest share of serious ones.

07

Un modelo de cribado: detectar 7 de cada 10 positivosA screening model: catching 7 in 10 positives

Entrené una regresión logística que estima si una persona implicada dará positivo en alcohol a partir de la franja, el tipo de accidente, la edad, el sexo y el vehículo. Con solo un 2,9 % de positivos, un modelo que dijera siempre "sobrio" tendría un 97 % de accuracy sin detectar a nadie, así que lo evalúo con recall y precisión. Mi primera versión tenía fuga de datos (codificaba cada categoría con su tasa de alcohol calculada con todo el dataset); esta usa one-hot y no ve el objetivo. I trained a logistic regression that estimates whether a person involved will test positive for alcohol from the time of day, accident type, age, sex and vehicle. With only 2.9% positives, a model that always said "sober" would score 97% accuracy while catching no one, so I evaluate it on recall and precision. My first version leaked data (it encoded each category with its alcohol rate computed on the full dataset); this one uses one-hot encoding and never sees the target.

Matriz de confusión en testTest confusion matrix

Métricas en test (clase positiva = alcohol)Test metrics (positive class = alcohol)

Split 80/20 estratificado · class_weight="balanced"Stratified 80/20 split · class_weight="balanced"

Lectura: sirve como filtro para priorizar pruebas, no como prueba: detecta 206 de 287 positivos, pero solo 1 de cada 10 personas señaladas es positiva.Takeaway: it works as a filter to prioritise tests, not as a test: it catches 206 of 287 positives, but only 1 in 10 people flagged is actually positive.

→

Conclusiones y recomendacionesConclusions & recommendations

  1. Peatones primero. Los atropellos son el tipo de accidente con más graves en proporción. Revisaría pasos de peatones y tiempos de semáforo en los puntos calientes del mapa.Pedestrians first. Pedestrian collisions have the highest share of serious outcomes. I would review crossings and signal timings at the map's hotspots.
  2. Controles de madrugada. Entre las 0 y las 5 h se juntan la mayor gravedad y la mayor tasa de positivos; el modelo puede ayudar a decidir a quién hacer la prueba primero.Late-night checkpoints. Between midnight and 5 am the highest severity and the highest positive rate coincide; the model can help decide who to test first.
  3. Separar volumen de riesgo. Para medir el riesgo real hay que dividir por la exposición (intensidad de tráfico), no solo contar accidentes.Separate volume from risk. To measure real risk you need to divide by exposure (traffic intensity), not just count accidents.
  4. Medir bien antes de concluir. Cambiar de unidad de análisis (de persona a accidente) y quitar la fuga de datos del modelo cambió tres conclusiones de la primera versión.Measure correctly before concluding. Switching the unit of analysis (from person to accident) and removing the model's data leak changed three conclusions from the first version.

Limitaciones y métodoLimitations & method

  • "Grave" = ingreso hospitalario de más de 24 h o fallecimiento (códigos de lesividad 3 y 4). Un accidente es grave si al menos una persona lo es."Serious" = hospital stay over 24 h or death (injury codes 3 and 4). An accident is serious if at least one person is.
  • No hay datos de intensidad de tráfico, así que las comparaciones son de proporciones, no de tasas por vehículo-km. Tampoco hay velocidad, que probablemente explica parte de la gravedad nocturna.There's no traffic-intensity data, so comparisons are shares, not rates per vehicle-km. There's no speed data either, which probably explains part of the late-night severity.
  • En el 13 % de los accidentes el tiempo es "Desconocido" y casi ninguno es grave: parece un sesgo de registro, por eso lo excluyo del test de la lluvia.Weather is "Unknown" in 13% of accidents and almost none are serious: it looks like a recording bias, so I exclude it from the rain test.
  • Las personas de un mismo accidente no son independientes entre sí, lo que el modelo (a nivel persona) no tiene en cuenta.People in the same accident aren't independent of each other, which the (person-level) model doesn't account for.
Siguiente proyectoNext project Qué restaurantes de NYC inspeccionar primeroWhich NYC restaurants to inspect first →