Salud Mental · Work in Progress Mental Health · Work in Progress Bloque 5 en curso Block 5 in progress

Detección temprana de deterioro depresivo a partir de datos conductuales

Early detection of depressive deterioration from behavioral data

Detectar cuándo intervenir, no predecir depresión.

Detect when to intervene, not predict depression.

Qué es GLOBEM

El primer dataset público multi-año de sensorización pasiva en salud mental, desarrollado por la Universidad de Washington. Durante 4 años consecutivos (2018–2021) recogió datos de smartphones y Fitbit de estudiantes universitarios: actividad, sueño, movilidad y uso del móvil, junto con cuestionarios clínicos de depresión.


El objetivo era construir un sistema que detectara depresión a partir del comportamiento, sin depender de que el paciente la reportara.

What GLOBEM is

The first multi-year public dataset of passive sensing in mental health, developed by the University of Washington. Over 4 consecutive years (2018–2021) it collected smartphone and Fitbit data from university students: activity, sleep, mobility and phone use, alongside clinical depression questionnaires.


The goal was to build a system that could detect depression from behavior, without relying on patient self-report.

497 participantes únicos unique participants
705 person-years person-years
4 cohortes anuales annual cohorts
INS-W_1 cohorte de trabajo (2018) working cohort (2018)
54.7% techo benchmark previo prior benchmark ceiling
Qué problema reveló

Los autores publicaron junto al dataset un benchmark de 18 algoritmos. El mejor llegó al 54.7% de precisión, apenas 9.7 puntos sobre predecir al azar. La caída respecto a los resultados que esos mismos algoritmos reportaban en sus papers originales fue de casi 19 puntos. La conclusión de los propios autores: el factor que más rompe los modelos no es técnico, son las diferencias individuales. Lo que para una persona es señal de deterioro, para otra es su estado habitual.

The problem it revealed

The authors published a benchmark of 18 algorithms alongside the dataset. The best reached 54.7% accuracy, only 9.7 points above random. The drop compared to the results those same algorithms reported in their original papers was almost 19 points. The authors' own conclusion: the factor that breaks models the most is not technical — it's individual differences. What for one person is a deterioration signal, for another is their normal state.

Qué hace este proyecto distinto

Cambia la pregunta. En lugar de "¿se parece esta persona a alguien deprimido?", pregunta "¿se está esta persona alejando de su propio patrón?". Cada paciente es su propia referencia. El sistema toma dos decisiones, no una. Primero, sobre quién puede operar de forma fiable: durante las primeras semanas construye un baseline individual y evalúa si es estable; mientras no lo sea, el usuario permanece en background sin disparar alertas, y el sistema reevalúa periódicamente hasta que el patrón se estabilice. Solo sobre los usuarios con baseline fiable, monitoriza desviaciones sostenidas y convergentes en tres dimensiones conductuales: activación, ritmo y uso pasivo. Cuando el patrón propio se rompe, dispara la decisión de intervención.

What makes this project different

It changes the question. Instead of "does this person look like someone depressed?", it asks "is this person drifting away from their own pattern?". Each patient is their own reference. The system makes two decisions, not one. First, who it can operate on reliably: during the first weeks it builds an individual baseline and evaluates whether it is stable; while it is not, the user stays in the background without triggering alerts, and the system reevaluates periodically until the pattern stabilizes. Only over users with a reliable baseline, the system monitors sustained convergent deviations across three behavioral dimensions: activation, rhythm and passive use. When the personal pattern breaks, the intervention decision is triggered.

El dataset y los conceptos del proyecto

The dataset and project concepts

El dataset y sus señales

GLOBEM recogió datos durante cuatro años consecutivos, una cohorte de estudiantes universitarios cada año: 2018, 2019, 2020 y 2021. Identificadas como INS-W_1, INS-W_2, INS-W_3 e INS-W_4. Cada participante generó datos diarios a través de su smartphone y un Fitbit, organizados en seis sensores: actividad física, sueño, localización, uso de pantalla, llamadas y proximidad por WiFi/Bluetooth.

El proyecto usa los cuatro primeros. Los dos últimos se descartan: tienen demasiados datos faltantes o son señales ruidosas que confundirían al modelo.

The dataset and its signals

GLOBEM collected data during four consecutive years, one cohort of university students per year: 2018, 2019, 2020 and 2021. Identified as INS-W_1, INS-W_2, INS-W_3 and INS-W_4. Each participant generated daily data through their smartphone and a Fitbit, organized into six sensors: physical activity, sleep, location, screen use, calls and WiFi/Bluetooth proximity.

The project uses the first four. The last two are discarded: they have too much missing data or are noisy signals that would confuse the model.

Las tres dimensiones conductuales

Esos cuatro sensores se agrupan en tres dimensiones que capturan aspectos distintos del comportamiento de una persona.
Activación: cuánto se mueve y cuánto sale de casa. La construyen los datos de actividad física y localización.
Ritmo: cómo de regulares son sus patrones diarios. La construyen los datos de sueño.
Uso pasivo: cómo se relaciona con el móvil. La construyen los datos de pantalla. El sistema vigila las tres a la vez. El deterioro real rara vez se manifiesta en una sola dimensión: aparece como un cambio sostenido y convergente en al menos dos.

The three behavioral dimensions

Those four sensors are grouped into three dimensions that capture different aspects of a person's behavior.
Activation: how much they move and how much they leave home. Built from physical activity and location data.
Rhythm: how regular their daily patterns are. Built from sleep data.
Passive use: how they interact with their phone. Built from screen data. The system monitors all three at once. Real deterioration rarely manifests in a single dimension: it appears as a sustained, convergent change in at least two.

Las features con ventana histórica

El dataset no entrega los datos crudos del sensor. Entrega features ya procesadas que resumen el comportamiento de los últimos N días. Por ejemplo, el número medio de pasos diarios de los últimos 7 días, o la duración media del sueño de los últimos 14.

Esas ventanas se llaman 7dhist y 14dhist. El proyecto trabaja con las de 7 días, no con las de 14. Razón: las de 14 días requieren que cada participante tenga al menos 14 días previos de datos válidos antes de poder calcular cualquier cosa, lo que reduce mucho el número de personas elegibles. Las de 7 días son menos profundas pero permiten incluir más participantes.

Historical-window features

The dataset does not deliver raw sensor data. It delivers pre-processed features that summarize behavior over the last N days. For example, average daily step count over the last 7 days, or average sleep duration over the last 14.

Those windows are called 7dhist and 14dhist. The project works with 7-day windows, not 14-day. Reason: 14-day features require each participant to have at least 14 prior days of valid data before any computation, which significantly reduces the number of eligible people. 7-day features are less deep but allow including more participants.

El baseline individual

Antes de poder detectar que alguien se está desviando, hay que saber cuál es su normal. El proyecto define el baseline como el patrón conductual medio de cada persona durante sus primeras tres semanas en el estudio. Cada persona es su propia referencia: no se compara con otros, se compara consigo mismo.

A partir de ese baseline, cada día posterior se traduce en una distancia respecto a su propio patrón normal. Esa distancia, medida en desviaciones típicas individuales, es el z-score intra-sujeto. Cuando el z-score se mantiene alto durante varios días seguidos en al menos dos de las tres dimensiones, el sistema considera que hay deterioro.

The individual baseline

Before being able to detect that someone is drifting, you need to know what their normal is. The project defines the baseline as each person's average behavioral pattern during their first three weeks in the study. Each person is their own reference: not compared to others, compared to themselves.

From that baseline, each subsequent day translates into a distance from their own normal pattern. That distance, measured in individual standard deviations, is the intra-subject z-score. When the z-score stays high for several consecutive days in at least two of the three dimensions, the system flags deterioration.

Marco metodológico

Methodological framework

Diseño longitudinal intra-sujeto + Control Estadístico de Procesos

Intra-subject longitudinal design + Statistical Process Control

Diseño

Diseño longitudinal intra-sujeto

Cada persona actúa como su propio grupo de control. El análisis no parte de comparar a un individuo con una población de referencia, sino de observar su evolución a lo largo del tiempo y construir una línea base de funcionamiento habitual.br


Sobre esa trayectoria individual, el objetivo es identificar desviaciones sostenidas respecto a su patrón basal: cambios en conducta, ritmo o estabilidad que indiquen que la persona empieza a alejarse de su funcionamiento esperado.

Design

Intra-subject longitudinal design

Each person acts as their own control group. The analysis does not start by comparing an individual to a reference population, but by observing their evolution over time and building a baseline of habitual functioning.


On top of that individual trajectory, the goal is to identify sustained deviations from the baseline pattern: changes in behavior, rhythm or stability that indicate the person is starting to drift from expected functioning.

Técnica estadística

Control estadístico sobre baseline individual

A partir de la línea base de cada participante, se monitorizan desviaciones persistentes, cambios de tendencia y posibles puntos de cambio que indiquen el inicio del deterioro conductual.


Baseline individual por sujeto, z-score intra-sujeto, run rules de persistencia, convergencia multivariable y CUSUM/EWMA para señales de deterioro sostenido. Change point detection (BOCPD, PELT) para localizar el inicio del deterioro.

Statistical technique

Statistical control over individual baseline

From each participant's baseline, persistent deviations, trend changes and possible change points are monitored to flag the onset of behavioral deterioration.


Individual baseline per subject, intra-subject z-score, persistence run rules, multivariable convergence and CUSUM/EWMA for sustained deterioration signals. Change point detection (BOCPD, PELT) to locate the onset of deterioration.

El problema de los 18 algoritmos anteriores: Xu et al. (2022) evaluaron 18 modelos sobre GLOBEM. El mejor alcanzó 54.7% de precisión. El motivo del fracaso no es técnico sino conceptual: compararon personas entre sí cuando la señal de deterioro es intrínsecamente individual. Este proyecto cambia la pregunta.
The problem with the 18 prior algorithms: Xu et al. (2022) evaluated 18 models on GLOBEM. The best reached 54.7% accuracy. The reason for failure is not technical but conceptual: they compared people to each other when the deterioration signal is intrinsically individual. This project changes the question.

Estado del proyecto

Project status

Dónde estamos y adónde vamos

Where we are and where it's going

Fase CRISP-DM
CRISP-DM phase
Bloque(s)
Block(s)
Estado
Status
Fase 1 Comprensión del negocio Phase 1 Data understanding
Bloque 0 Block 0
Problem framing · Definición operativa de deterioro
Problem framing · Operational definition of deterioration
Completado Completed
Fase 2 Comprensión de los datos Phase 2 Business understanding
Bloque 1 Block 1
Validación del dataset · Cobertura · Warmup · Viabilidad
Dataset validation · Coverage · Warmup · Feasibility
Completado Completed
Fase 3 Preparación de datos Phase 3 Data preparation
Bloque 2 Block 2
Construcción del baseline individual
Individual baseline construction
Bloque 3 Block 3
Z-score intra-sujeto
Intra-subject z-score
Bloque 4 Block 4
Series temporales · Ventanas rolling · Autocorrelación
Time series · Rolling windows · Autocorrelation
Bloque 5 Block 5
Feature engineering temporal
Temporal feature engineering
Completado Completed Completado Completed Completado Completed En curso In progress
Fase 4 Modelado Phase 4 Modeling
Bloque 6 Block 6
Modelado con validación temporal
Modeling with temporal validation
Pendiente Pending
Fase 5 Evaluación Phase 5 Evaluation
Bloque 7 Block 7
Evaluación orientada a intervención (CUSUM/EWMA)
Intervention-oriented evaluation (CUSUM/EWMA)
Bloque 8 Block 8
Análisis individual · Trayectorias por persona
Individual analysis · Per-person trajectories
Bloque 9 Block 9
Interpretabilidad SHAP
SHAP interpretability
Pendiente Pending Pendiente Pending Pendiente Pending
Fase 6 Producción y Despliegue Phase 6 Production & Deployment
Bloque 10 Block 10
Umbral de intervención (OCAP)
Intervention threshold (OCAP)
Bloque 11 Block 11
Producción del sistema · API · Docker · Despliegue
System productionization · API · Docker · Deployment
Pendiente Pending Pendiente Pending

Timeline estimado

Abril 2026
Bloque 0 - Problem framing
Block 0 - Problem framing
Abril 2026
April 2026
Bloque 1 - Validación de datos
Block 1 - Data validation
Mayo 2026 - Semana 1 y 2
May 2026 - Week 1 y 2
Bloque 2 - Preparación de datos 1
Block 2 - Data preparation 1
Mayo 2026 - Semana 3
May 2026 - Week 3
Bloque 3 - Preparación de datos 2
Block 3 - Data preparation 2
Mayo 2026 - Semana 4
May 2026 - Week 4
Bloque 4 - Preparación de datos 3
Block 4 - Data preparation 3
Mayo 2026 - Semana 5
May 2026 - Week 5
Bloque 5 - Feature Engineering
Block 5 - Feature Engineering
Junio 2026 - Semanas 1,2
Juny 2026 - Weeks 1,2
Bloque 6 - Modelado con validación temporal
Block 6 - Modeling with temporal validation
Junio 2026 - Semana 3
Juny 2026 - Week 3
Bloque 7 - Evaluación orientada a intervención
Block 7 - Intervention-oriented assessment
Junio 2026 - Semana 4
Juny 2026 - Week 4
Bloque 8 - Análisis individual
Block 8 - Individual analysis
Julio 2026 - Semana 1
July 2026 - Week 1
Bloque 9 - Evaluación e interpretabilidad
Block 9 - Evaluation and interpretability
Julio 2026 - Semana 2
July 2026 - Week 2
Bloque 10 - Umbral de intervención y Plan de acción
Block 10 - Intervention Threshold and Action Plan
Julio 2026 - Semanas 3,4
July 2026 - Weeks 3,4
Bloque 11 - Producción del sistema
Block 11 - System output

Bloques del proyecto

Project blocks

Cada bloque, su flujo de trabajo completo

Each block, its complete workflow

Cada bloque cierra con cuatro preguntas no negociables — decisión, renuncia, uso real, trade-off — y documenta las lecturas técnicas que lo sustentan. Este es mi sistema de control: si un bloque no responde a las cuatro, no se cierra.

Each block closes with four non-negotiable questions — decision, trade-off given up, real-world use, trade-off accepted — and documents the technical readings that support it. This is my control system: if a block does not answer all four, it does not close.

FASE 1 · BLOQUE 0 — COMPRENSIÓN DEL NEGOCIO PHASE 1 · BLOCK 0 — BUSINESS UNDERSTANDING Problem framing — Definición operativa de deterioro Problem framing — Operational definition of deterioration
Completado Completed
Pregunta resuelta: ¿Cómo se define operativamente "deterioro" cuando la etiqueta clínica del dataset (BDI-II) no es fiable y los métodos poblacionales han fracasado en predecirla?
Question solved: How is "deterioration" operationally defined when the dataset's clinical label (BDI-II) is not reliable and population methods have failed to predict it?
Bhattacharya et al. (2024) — "Imputation Strategies for Longitudinal Behavioral Studies: Predicting Depression Using GLOBEM Datasets".
Delimita con precisión el hueco que este proyecto ocupa: los enfoques más recientes sobre GLOBEM siguen sin abordar el enfoque intra-sujeto.
It clearly defines the niche this project occupies: the most recent approaches to GLOBEM still fail to address the intra-subject perspective.
SPC
Hunt, Auriemma & Cashaw (2003) — "Self-report bias and underreporting of depression on the BDI-II".
Justifica metodológicamente el rechazo del BDI-II como target. Muestra experimentalmente que los sujetos reportan más síntomas cuando el propósito del cuestionario está enmascarado — evidencia directa de infraestimación sistemática.
It provides a methodological justification for rejecting the BDI-II as a target measure. It demonstrates experimentally that participants report more symptoms when the purpose of the questionnaire is concealed—direct evidence of systematic underestimation.
SPC
Decisión
Decision
Rechazar la etiqueta del dataset (BDI-II) y construir una definición operativa propia de deterioro basada en señales conductuales pasivas y persistencia temporal. Adoptar marco N-of-1 como diseño y SPC como técnica.
Reject the dataset's label (BDI-II) and build an own operational definition of deterioration based on passive behavioral signals and temporal persistence. Adopt the N-of-1 framework as design and SPC as technique.
Renuncia
Trade-off given up
Comparabilidad directa con el benchmark de 18 algoritmos de Xu et al. (2022). No se puede comparar apples-to-apples si se cambia la pregunta de fondo.
Direct comparability with the 18-algorithm benchmark of Xu et al. (2022). You cannot compare apples-to-apples if the underlying question changes.
Uso real
Real-world use
Monitorización pasiva continua sin cuestionarios ni evaluaciones periódicas. El sistema funciona en background, como un detector de humo, no como una consulta clínica.
Continuous passive monitoring without questionnaires or periodic evaluations. The system runs in the background, like a smoke detector, not like a clinical consultation.
Trade-off
Trade-off
Se gana detección temprana y no intrusiva. Se pierde certeza de estar midiendo exactamente depresión clínica tal como la define el DSM. Es un trade-off consciente y defendible.
Early and non-intrusive detection is gained. Certainty of measuring exactly clinical depression as DSM defines it is lost. It is a conscious and defensible trade-off.
FASE 2 · BLOQUE 1 — VALIDACIÓN TÉCNICA DEL DATASET PHASE 2 · BLOCK 1 — TECHNICAL DATASET VALIDATION Validación del dataset — Cobertura, warmup y viabilidad Dataset validation — Coverage, warmup and feasibility
Completado Completed
Pregunta resuelta: ¿Qué cohortes, sensores y ventanas temporales del dataset son técnicamente viables para construir un sistema de monitorización individual?
Question solved: Which cohorts, sensors and temporal windows of the dataset are technically feasible to build an individual monitoring system?
Xu et al. (2022) — "GLOBEM Dataset: Multi-Year Datasets for Longitudinal Human Behavior Modeling".
La fuente del dataset y el benchmark de referencia. El 54.7% de precisión de su mejor modelo es el punto de partida que motiva cambiar el enfoque.
The source of the dataset and the benchmark. The 54.7% accuracy of their best model is the starting point that prompted a change in approach.
SPC
Decisión
Decision
Trabajar exclusivamente con INS-W_1 (155 participantes, pre-COVID). Features 7dhist sobre 14dhist. Excluir WiFi (96.8% NaN), Call (NaN ambiguo) y Bluetooth (señal sin valor conductual).
Work exclusively with INS-W_1 (155 participants, pre-COVID). 7dhist features over 14dhist. Exclude WiFi (96.8% NaN), Call (ambiguous NaN) and Bluetooth (signal without behavioral value).
Renuncia
Trade-off given up
Los 3 estudios restantes del dataset (2019–2021). Mayor muestra, menor fiabilidad del contexto. No merece la pena sacrificar la limpieza del baseline por más n.
The 3 remaining studies of the dataset (2019–2021). Larger sample, lower context reliability. Not worth sacrificing baseline cleanliness for more n.
Uso real
Real-world use
Cualquier sistema de monitorización real necesita datos de warmup por persona antes de poder detectar desviaciones. Aquí se fija ese período en 7 días mínimo por sujeto.
Any real monitoring system needs warmup data per person before being able to detect deviations. Here that period is set at a minimum of 7 days per subject.
Trade-off
Trade-off
7dhist sobre 14dhist: se pierde historia, se gana cobertura de participantes. Excluir WiFi/Call/Bluetooth: se pierden señales, se gana fiabilidad. Solo INS-W_1: se pierde n, se gana contexto limpio.
7dhist over 14dhist: history is lost, participant coverage is gained. Excluding WiFi/Call/Bluetooth: signals are lost, reliability is gained. Only INS-W_1: n is lost, clean context is gained.
FASE 3 · BLOQUE 2 — PREPARACIÓN DE DATOS PHASE 3 · BLOCK 2 — DATA PREPARATION Construcción del baseline individual Individual baseline construction
Completado Completed
Pregunta que resuelve: ¿Qué es el "comportamiento normal" de cada participante, cómo se mide día a día y cómo se decide en qué momentos puede servir de referencia?
Question being solved: What is each participant's "normal behaviour", how is it measured day by day, and how do you decide at which moments it can serve as reference?
Montgomery — "Introduction to Statistical Quality Control - Chapter 5".
Filosofía de SPC: causas fortuitas vs asignables, límites de control, patrones. Especialmente la sección sobre aplicaciones fuera de la manufactura — el puente conceptual entre SPC industrial y monitorización individual en salud.
SPC philosophy: chance vs assignable causes, control limits, patterns. Especially the section on applications beyond manufacturing — the conceptual bridge between industrial SPC and individual health monitoring.
SPC
Difrancesco et al. (2019) — "Sleep, circadian rhythm, and physical activity patterns in depressive and anxiety disorders". Depression and Anxiety.
Baseline / mapeo de señales: Respaldo empírico para elegir sueño y actividad como dimensiones núcleo.
Baseline / Signal Mapping: Empirical support for selecting sleep and activity as core dimensions.
N-of-1
Daza (2018). Daza, E. J. (2018). Causal Analysis of Self-tracked Time Series Data Using a Counterfactual Framework for N-of-1 Trials.
Marco counterfactual para estudios N-of-1 observacionales. Define formalmente el diseño N1OS frente al N1RT y sustenta la inferencia idiográfica sin randomización, núcleo conceptual del enfoque intra-sujeto del proyecto.
Counterfactual framework for N-of-1 observational studies. Formally defines the N1OS design as distinct from the N1RT and grounds idiographic inference without randomisation, the conceptual core of the project's within-subject approach.
N-of-1
Vieira et al. (2017). Dynamic modelling of n-of-1 data: powerful and flexible data analytics applied to individualised studies.
Modelado dinámico de datos N-of-1. Justifica formalmente el tratamiento de tendencia y autocorrelación en series longitudinales individuales, base técnica del tratamiento de autocorrelación entre z-scores en el Bloque 4.
Dynamic modelling of N-of-1 data. Provides the formal justification for handling temporal trend and autocorrelation in single-subject longitudinal series, the technical basis for the autocorrelation treatment between z-scores in Block 4.
N-of-1
James et al. — "An Introduction to Statistical Learning - Chapter 2".
Base de statistical learning: qué es un modelo, sesgo vs varianza, sobreajuste. Fundamentos aplicados al diseño del baseline rolling y al modelado posterior.
Statistical learning fundamentals: what a model is, bias vs variance, overfitting. Foundations applied to the rolling baseline design and subsequent modelling.
ML base
Decisión
Decision
Baseline rolling con buffer, calculado por persona, dimensión y día. La referencia individual se actualiza día a día con el histórico reciente del participante, lo que captura la no-estacionariedad propia de las series conductuales reales y evita por construcción el sesgo de exclusión hacia perfiles no rutinarios. Operativamente: par (media, desviación típica) sobre los 21 días que terminan 7 días antes de cada día evaluado (ventana [d-28, d-8]). El buffer de 7 días evita que la observación del día d comparta datos crudos con su propia referencia, dado que las features 7dhist son sumas deslizantes de 7 días. Feature primaria por dimensión: pasos, radio de giro, duración de sueño, duración de pantalla. Criterio de cobertura: ≥70% de días no nulos en la ventana del baseline.
Buffered rolling baseline, computed per person, dimension and day. The individual reference updates day by day with the participant's recent history, which captures the non-stationarity inherent to real behavioural series and avoids by construction the exclusion bias toward routine profiles. Operationally: pair (mean, standard deviation) over the 21 days ending 7 days before each evaluated day (window [d-28, d-8]). The 7-day buffer prevents the day d observation from sharing raw data with its own reference, given that 7dhist features are 7-day rolling sums. Primary feature per dimension: steps, radius of gyration, sleep duration, screen duration. Coverage criterion: ≥70% non-null days in the baseline window.
Renuncia
Trade-off given up
Se renuncia al baseline fijo al inicio del registro, que sería más simple de auditar. Su limitación estructural es que, al exigir que la ventana inicial cumpla un criterio de estabilidad para entrar en monitorización, todo participante que en ese tramo concreto esté en transición (mudanza, cambio de empleo, fase distinta de su rutina, etapa de mayor variabilidad) queda sistemáticamente excluido del sistema, no porque no sea evaluable, sino porque las tres semanas iniciales no eran representativas. El sistema acaba operando preferentemente sobre perfiles rutinarios y se invisibiliza el resto. La clasificación día a día de evaluabilidad por dimensión que sí mantiene el rolling no es renuncia: es una funcionalidad del sistema (módulo de detectabilidad por persona-día) que decide en qué momentos puede operar la monitorización automática y en cuáles no.
A fixed baseline at the start of the record is given up: it would be simpler to audit. Its structural limitation is that, by requiring the initial window to meet a stability criterion to enter monitoring, every participant who happens to be in transition during that stretch (relocation, job change, a different phase of their routine, a period of higher variability) is systematically excluded from the system, not because they are unevaluable, but because the initial three weeks were not representative. The system ends up operating preferentially on routine profiles and the rest become invisible. The day-by-day evaluability classification per dimension that the rolling design does keep is not a trade-off: it is a system feature (per person-day detectability module) that decides when automatic monitoring can operate and when it cannot.
Uso real
Real-world use
Las primeras 5 semanas de un usuario en una plataforma de salud digital son acumulación de histórico: no se disparan alertas, el sistema acumula los días previos necesarios para construir el primer baseline rolling con buffer. A partir del día 35 el sistema evalúa día a día qué dimensiones tienen baseline calculable para ese usuario y aplica la regla de convergencia 2/3 sobre los días evaluables. Si en algún periodo la cobertura cae en una dimensión, el sistema no opera sobre esa dimensión esos días, sin sacar al usuario del pipeline.
A user's first 5 weeks on a digital health platform are history accumulation: no alerts are triggered, the system accumulates the prior days needed to build the first buffered rolling baseline. From day 35 onwards, the system evaluates day by day which dimensions have a computable baseline for that user and applies the 2/3 convergence rule over evaluable days. If coverage drops in a dimension during some period, the system does not operate on that dimension those days, without removing the user from the pipeline.
Trade-off
Trade-off
Baseline rolling con buffer frente a baseline fijo. Se elige rolling porque la referencia individual se mantiene operativa sobre toda la cohorte sin sesgar el sistema hacia perfiles de comportamiento rutinario. Se acepta una mayor complejidad de auditoría (el baseline ya no es un par único por persona-dimensión, sino una función del día) y la posibilidad de absorción del deterioro gradual, mitigada por la regla de persistencia 7 días, la regla de convergencia 2/3 y los métodos de detección de cambio estructural del Bloque 7.
Buffered rolling baseline vs fixed baseline. Rolling is chosen because the individual reference remains operative across the whole cohort without biasing the system towards routine behavioural profiles. Greater audit complexity is accepted (the baseline is no longer a single pair per person-dimension but a function of the day), as well as the possibility of gradual deterioration absorption, mitigated by the 7-day persistence rule, the 2/3 convergence rule and the structural change detection methods of Block 7.
FASE 3 · BLOQUE 3 — PREPARACIÓN DE DATOS PHASE 3 · BLOCK 3 — DATA PREPARATION Z-score intra-sujeto / Grafico de control de Shewart Intra-subject z-score / Shewhart control chart
Completado Completed
Pregunta que resolverá: Una vez construido el baseline individual, ¿Cómo se convierte cada día de comportamiento en una medida de distancia respecto al propio patrón de cada persona?
Question to be solved: Once an individual baseline has been established, how is each day’s behavior measured against that person’s own baseline?
Montgomery — "Introduction to Statistical Quality Control - Chapter 6".
Cartas de control para variables. Es la base técnica para construir el z-score intra-sujeto.
Control charts for variables. It is the technical basis for building the intra-subject z-score.
SPC
Decisión
Decision
Estandarizar la desviación de cada persona respecto a su propio baseline expresando cada día como el número de desviaciones típicas que se aleja de su media: z = (observación − media_baseline) / std_baseline. La fórmula aplica por persona, dimensión y día evaluable con baseline válido. La estandarización hace comparables las cuatro dimensiones — pasos, radio de giro, sueño, pantalla — que tienen escalas completamente distintas en sus valores originales.
Standardize each person's deviation from their own baseline by expressing each day as the number of standard deviations from their mean: z = (observation − baseline_mean) / baseline_std. The formula applies per person, dimension and evaluable day with a valid baseline. Standardization makes the four dimensions comparable — steps, radius of gyration, sleep, screen — which have completely different scales in their original values.
Renuncia
Trade-off given up
Se renuncia a comparar personas entre sí. El z-score intra-sujeto no dice si una persona está alta o baja respecto a la población; dice si está alta o baja respecto a ella misma. Un z-score de +2 significa lo mismo para alguien muy activo que para alguien sedentario: se ha desviado dos veces su propia variabilidad habitual. No es posible comparar directamente los z-scores de dos participantes distintos.
Comparison between people is given up. The intra-subject z-score does not say whether a person is high or low relative to the population; it says whether they are high or low relative to themselves. A z-score of +2 means the same for a very active person as for a sedentary one: they have deviated two times their own habitual variability. It is not possible to directly compare the z-scores of two different participants.
Uso real
Real-world use
En producción, el z-score intra-sujeto se calcula cada día para cada usuario activo con baseline válido. Si una persona lleva varios días con z-score elevado en alguna dimensión, el sistema registra la señal sin necesitar compararla con ningún otro usuario. El umbral que activa la alerta es el mismo para todo el mundo aunque cada persona tenga un comportamiento absolutamente distinto.
In production, the intra-subject z-score is calculated each day for every active user with a valid baseline. If a person has had a high z-score in some dimension for several days, the system records the signal without needing to compare it with any other user. The threshold that triggers the alert is the same for everyone, even though each person has completely different behavior.
Trade-off
Trade-off
Se gana sensibilidad individual: el sistema es igualmente capaz de detectar deterioro en una persona con alta actividad habitual que en una persona sedentaria. Se pierde la capacidad de establecer referencias poblacionales o de comparar entre personas. El sistema no puede responder "esta persona está en el percentil X de la población"; solo puede responder "esta persona se ha alejado X desviaciones típicas de su propio patrón".
Individual sensitivity is gained: the system is equally capable of detecting deterioration in a habitually active person as in a sedentary one. The capacity to establish population references or compare between people is lost. The system cannot answer "this person is at the Xth population percentile"; it can only answer "this person has drifted X standard deviations from their own pattern".
FASE 3 · BLOQUE 4 — PREPARACIÓN DE DATOS PHASE 3 · BLOCK 4 — DATA PREPARATION Series temporales · Ventanas rolling · Autocorrelación Time series · Rolling windows · Autocorrelation
Completado Completed
Pregunta que resolverá: ¿Qué estructura temporal tienen las series del z-score? ¿La autocorrelación que se observa entre días consecutivos es señal conductual real o es una consecuencia del propio cálculo del baseline?
Question to be solved: What is the temporal structure of the z-score series? Is the autocorrelation observed between consecutive days a true behavioral signal, or is it a consequence of the baseline calculation itself?
Hyndman & Athanasopoulos — "Forecasting: Principles and Practice, the Pythonic Way, Chapters 2,3,4".
Series temporales básicas: tendencias, ventanas rolling, autocorrelación. Los conceptos técnicos del bloque, sin entrar en métodos predictivos como ARIMA que no aplican aquí.
Basic time series: trends, rolling windows, autocorrelation. The technical concepts of the block, without going into predictive methods like ARIMA that do not apply here.
Series temp
Wichers, Smit, Snippe (2020) — "Early Warning Signals Based on Momentary Affect Dynamics can Expose Nearby Transitions in Depression: A Confirmatory Single-Subject Time-Series Study"
Introduce formalmente la idea de que la varianza creciente y la autocorrelación creciente en momentos emocionales son indicadores anticipatorios de transiciones psicopatológicas.
Formally introduces the idea that rising variance and rising autocorrelation in momentary emotional data are anticipatory indicators of psychopathological transitions.
DOMINIO
Olthof, Hasselman, Strunk (2020) — "Critical Fluctuations as an Early-Warning Signal for Sudden Gains and Losses in Patients Receiving Psychotherapy for Mood Disorders"
Aplicación empírica concreta sobre 328 casos de psicoterapia. Demuestra que las fluctuaciones críticas anticipan cambios sostenidos en sesiones clínicas.
Concrete empirical application on 328 psychotherapy cases. Demonstrates that critical fluctuations anticipate sustained changes in clinical sessions.
DOMINIO
Decisión
Decision
Construir el diagnóstico temporal de las series del z-score en tres pasos: inspección visual de trayectorias individuales, análisis de autocorrelación con simulación de ruido como línea de base estructural, y caracterización mediante rolling mean y rolling std en ventana de 7 días. La ventana de 7 días no se optimiza aquí: está fijada por coherencia con las features 7dhist del dataset y con la regla de persistencia del Bloque 0. El hallazgo central del bloque es que la autocorrelación observada entre días consecutivos del z-score es prácticamente en su totalidad artefacto del propio cálculo del baseline rolling, no señal conductual neta.
Build the temporal diagnosis of the z-score series in three steps: visual inspection of individual trajectories, autocorrelation analysis with noise simulation as a structural baseline, and characterization using rolling mean and rolling std over a 7-day window. The 7-day window is not optimized here: it is fixed for coherence with the 7dhist features of the dataset and with the persistence rule from Block 0. The central finding of the block is that the autocorrelation observed between consecutive days of the z-score is almost entirely an artifact of the rolling baseline calculation itself, not a net behavioral signal.
Renuncia
Trade-off given up
Se renuncia al uso de lags cortos del z-score como features directas para el Bloque 5. El hallazgo de que la autocorrelación lag-1 es estructural hace inútil construir features de tipo "z-score de ayer" o "diferencia entre hoy y ayer": capturarían ruido del pipeline de cálculo, no señal conductual real. Las features del Bloque 5 se construirán sobre niveles sostenidos del z-score, no sobre sus variaciones diarias.
The use of short z-score lags as direct features for Block 5 is given up. The finding that lag-1 autocorrelation is structural makes it useless to build features such as "yesterday's z-score" or "difference between today and yesterday": they would capture noise from the calculation pipeline, not real behavioral signal. Block 5 features will be built on sustained z-score levels, not on their daily variations.
Uso real
Real-world use
En producción, el sistema no opera sobre la variación diaria del z-score sino sobre su nivel sostenido. El rolling mean de 7 días del z-score es el objeto que el sistema lee para decidir si una dimensión está desviada de forma persistente. La serie diaria del z-score queda como registro crudo disponible para análisis retrospectivo, no como señal de intervención directa.
In production, the system does not operate on the daily variation of the z-score but on its sustained level. The 7-day rolling mean of the z-score is the object the system reads to decide whether a dimension is persistently deviated. The daily z-score series remains as a raw record available for retrospective analysis, not as a direct intervention signal.
Trade-off
Trade-off
El rolling de 7 días introduce inercia: si el deterioro comienza hoy, el rolling mean no lo reflejará completamente hasta varios días después. Se gana robustez frente al ruido diario (días atípicos aislados no disparan el sistema) y coherencia con la regla de persistencia del marco. La tensión entre anticipación y robustez queda documentada y se abordará con los métodos CUSUM/EWMA del Bloque 7.
The 7-day rolling introduces inertia: if deterioration begins today, the rolling mean will not fully reflect it until several days later. Robustness against daily noise is gained (isolated atypical days do not trigger the system), as well as coherence with the framework's persistence rule. The tension between anticipation and robustness is documented here and will be addressed with the CUSUM/EWMA methods of Block 7.
FASE 3 · BLOQUE 5 — PREPARACIÓN DE DATOS PHASE 3 · BLOCK 5 — DATA PREPARATION Feature engineering temporal Temporal feature engineering
En Curso In progress
Pregunta que resolverá: ¿Cómo se construye operativamente la variable que define el deterioro? ¿Qué decisiones de diseño hay que tomar para pasar de las series del z-score a la convergencia 2/3 con persistencia de siete días?
Question to be solved: How is the variable that defines default constructed in practice? What design decisions need to be made to transition from the z-score series to 2/3 convergence with a seven-day persistence?
Sin lecturas adicionales planificadas.
No additional readings planned.
Este bloque se aborda directamente con el conocimiento técnico acumulado en los bloques 2–4. La construcción de features se basa en los criterios de baseline, z-score y ventanas rolling ya cerrados.
This block is addressed directly with the technical knowledge accumulated in blocks 2–4. Feature construction is based on the already-closed baseline, z-score and rolling-window criteria.
Decisión
Decision
Materializar la definición operativa de deterioro del Bloque 0 en una variable binaria por persona y día: convergencia 2/3 con persistencia de 7 días. La construcción sigue cuatro capas: umbral de voto diario por dimensión sobre el rolling mean del z-score, indicador de persistencia que exige 7 días consecutivos de voto, composición de los tres pilares conductuales (sueño, activación, uso pasivo) con la dimensión activación alimentada por steps y location con regla OR, y regla final de convergencia 2/3. Dos decisiones técnicas heredadas del Bloque 4 se aplican: winsorización al p95 del rolling mean de location y regla OR para el pilar activación.
Materialize the operational definition of deterioration from Block 0 into a binary variable per person and day: 2/3 convergence with 7-day persistence. The construction follows four layers: daily vote threshold per dimension on the z-score rolling mean, persistence indicator requiring 7 consecutive days of vote, composition of the three behavioral pillars (sleep, activation, passive use) with the activation dimension fed by steps and location using an OR rule, and the final 2/3 convergence rule. Two technical decisions inherited from Block 4 are applied: winsorization at p95 of the location rolling mean, and OR rule for the activation pillar.
Renuncia
Trade-off given up
Se renuncia a features genéricas de series temporales (pendientes, ratios de cambio, lag features) como entrada al modelo del Bloque 6. La variable de convergencia 2/3 encapsula la teoría del proyecto; añadir features no ancladas en la definición operativa de deterioro añadiría complejidad de selección sin justificación conceptual. Si el Bloque 6 necesitara más señal, se revisaría con criterio derivado de la evaluación.
Generic time series features (slopes, change ratios, lag features) as input to the Block 6 model are given up. The 2/3 convergence variable encapsulates the project's theory; adding features not anchored in the operational definition of deterioration would add selection complexity without conceptual justification. If Block 6 needed more signal, it would be reviewed based on evaluation criteria.
Uso real
Real-world use
En producción, el sistema calcula cada día, para cada usuario activo, si los tres pilares han estado en estado de voto durante los últimos 7 días y si al menos dos de ellos han convergido. El resultado es un único bit por persona y día: alerta activa o no activa. Esa señal es auditable por cualquier clínico: "el sistema disparó porque sueño y activación estuvieron desviados durante 7 días seguidos".
In production, the system calculates each day, for every active user, whether the three pillars have been in a vote state for the last 7 days and whether at least two of them have converged. The result is a single bit per person per day: alert active or not active. That signal is auditable by any clinician: "the system triggered because sleep and activation were deviated for 7 consecutive days".
Trade-off
Trade-off
La convergencia 2/3 es una regla explícita y auditable. Se pierde la flexibilidad de un modelo que pondere las dimensiones numéricamente y pueda descubrir relaciones no anticipadas. Se acepta ese trade-off a favor de transparencia e interpretabilidad, especialmente en un dominio clínico donde la confianza del usuario final es crítica y donde una regla opaca dificulta la adopción.
The 2/3 convergence is an explicit and auditable rule. The flexibility of a model that weights dimensions numerically and could discover unanticipated relationships is lost. This trade-off is accepted in favor of transparency and interpretability, especially in a clinical domain where end-user trust is critical and where an opaque rule hinders adoption.
FASE 4 · BLOQUE 6 — MODELADO PHASE 4 · BLOCK 6 — MODELING Modelado con validación temporal Modeling with temporal validation
Pendiente Pending
Pregunta que resolverá: ¿Qué arquitectura de validación (walk-forward vs. expanding window) preserva mejor la integridad temporal de los datos longitudinales y evita data leakage?
Question to be solved: Which validation architecture (walk-forward vs. expanding window) best preserves the temporal integrity of longitudinal data and avoids data leakage?
James et al. — "An Introduction to Statistical Learning - Chapters 5,8".
Validación cruzada y por qué no random split sobre datos longitudinales. Árboles de decisión, Random Forest e interpretabilidad.
Cross-validation and why not random split on longitudinal data. Decision trees, Random Forest and interpretability.
ML
Géron — "Hands-On Machine Learning with Scikit-Learn, Keras & TensorFlow - Chapters 5,6".
Implementación práctica en Python de árboles de decisión, ensemble learning y pipelines de modelado.
Practical Python implementation of decision trees, ensemble learning and modeling pipelines.
ML
FASE 5 · BLOQUE 7 — EVALUACIÓN PHASE 5 · BLOCK 7 — EVALUATION Evaluación orientada a intervención:   CUSUM-EWMA  |   BOCPD-PELT Intervention-oriented evaluation:   CUSUM-EWMA  |   BOCPD-PELT
Pendiente Pending
Pregunta que resolverá: ¿Cuántos días antes de la ventana clínica de riesgo detecta la señal CUSUM/EWMA el deterioro? ¿Cómo se localiza el punto exacto en el que la trayectoria conductual cambia de régimen?
Question to be solved: How many days before the clinical risk window does the CUSUM/EWMA signal detect deterioration? How is the exact point at which the behavioral trajectory changes regime located?
Smit, A. C., Snippe, E., & Wichers, M. (2019). "Increasing restlessness signals impending increase in depressive symptoms more than 2 months before it happens in individual patients".
Mostró que el incremento en intranquilidad (restlessness) monitorizado con SPC predijo un aumento en síntomas depresivos más de 2 meses antes de que ocurriera en pacientes individuales.
Showed that the increase in restlessness monitored with SPC predicted a rise in depressive symptoms more than 2 months before it occurred in individual patients.
DOMINIO
Smit, A. C., & Snippe, E. (2023). "Real-time monitoring of increases in restlessness to assess idiographic risk of recurrence of depressive symptoms".
Replicó su estudio anterior a mayor escala: aplicando EWMA a datos EMA de varios meses, los episodios depresivos podían preverse con semanas de antelación.
Replicated their previous study at larger scale: applying EWMA to EMA data over several months, depressive episodes could be foreseen weeks in advance.
DOMINIO
Montgomery — "Introduction to Statistical Quality Control - Chapter 9, 10".
CUSUM y EWMA: detección de desviaciones pequeñas sostenidas. Monitoreo con variables múltiples para combinar las 3 dimensiones conductuales (activación, ritmo, uso pasivo).
CUSUM and EWMA: detection of small sustained deviations. Multivariate monitoring to combine the 3 behavioral dimensions (activation, rhythm, passive use).
SPC
Aminikhanghahi & Cook (2017) — "A Survey of Methods for Time Series Change Point Detection".
Revisión de referencia. Cubre métodos clásicos (CUSUM, Bayesian) y modernos. Punto de partida obligatorio para situar las técnicas elegidas en el ecosistema completo.
Reference review. Covers classical (CUSUM, Bayesian) and modern methods. Mandatory starting point to place the chosen techniques within the full ecosystem.
Change point
Killick, Fearnhead & Eckley (2012) — "Optimal Detection of Changepoints with a Linear Computational Cost".
Paper original de PELT, el algoritmo más usado en change-point detection offline. Es el que verás implementado en la mayoría de librerías Python (ruptures).
Original PELT paper, the most-used algorithm in offline change-point detection. It is the one implemented in most Python libraries (ruptures).
Change point
Adams & MacKay (2007) — "Bayesian Online Changepoint Detection".
Paper original de BOCPD, el método más usado en monitorización online. Corto, técnico pero accesible. Alternativa bayesiana a CUSUM para detección en tiempo real.
Original BOCPD paper, the most-used method in online monitoring. Short, technical but accessible. Bayesian alternative to CUSUM for real-time detection.
Change point
Van den Burg & Williams (2020) — "An Evaluation of Change Point Detection Algorithms".
Referencia para defender la elección de algoritmo en el Bloque 7 frente a alternativas.
Reference for defending algorithm choice in Block 7 against alternatives.
Change point
FASE 5 · BLOQUE 8 — EVALUACIÓN PHASE 5 · BLOCK 8 — EVALUATION Análisis individual - Trayectorias por persona Individual analysis - Per-person trajectories
Pendiente Pending
Pregunta que resolverá: ¿Cómo se evalúa el sistema persona a persona, no solo en métricas globales? ¿Qué patrones de deterioro emergen al analizar trayectorias individuales?
Question to be solved: How is the system evaluated person-by-person, not only in global metrics? Which deterioration patterns emerge when analyzing individual trajectories?
Sin lecturas adicionales planificadas.
No additional readings planned.
Este bloque se aborda con las herramientas técnicas acumuladas (SPC, change-point detection, z-score intra-sujeto) aplicadas al análisis individual de trayectorias.
This block is addressed with the accumulated technical tools (SPC, change-point detection, intra-subject z-score) applied to individual trajectory analysis.
FASE 5 · BLOQUE 9 — EVALUACIÓN PHASE 5 · BLOCK 9 — EVALUATION Interpretabilidad - SHAP Interpretability - SHAP
Pendiente Pending
Pregunta que resolverá: ¿Qué señales explican el deterioro para cada sujeto de forma individual? ¿Cómo se traduce esa explicación a un lenguaje accionable para un clínico?
Question to be solved: Which signals explain deterioration for each subject individually? How is that explanation translated into actionable language for a clinician?
Christoph Molnar - "Interpretable Machine Learning - Chapters 17, 18".
Libro de referencia para entender SHAP. Explica cómo abrir un modelo de machine learning y ver qué variables han pesado más en cada predicción concreta, en lugar de quedarte solo con el resultado final.
Reference book for understanding SHAP. Explains how to open up a machine learning model and see which variables weighed most in each specific prediction, rather than just keeping the final result.
DOMINIO
FASE 6 · BLOQUE 10 — DESPLIEGUE PHASE 6 · BLOCK 10 — DEPLOYMENT Umbral de intervención - Decisión final (OCAP) Intervention threshold - Final decision (OCAP)
Pendiente Pending
Pregunta que resolverá: ¿Cómo se traduce la señal estadística de deterioro en una regla de disparo accionable que un clínico o una plataforma pueda usar sin necesitar entender el modelo?
Question to be solved: How is the statistical deterioration signal translated into an actionable trigger rule that a clinician or platform can use without needing to understand the model?
Montgomery — "Introduction to Statistical Quality Control - Chapter 11".
Monitoreo con variables múltiples y diseño de OCAP (out-of-control action plan). El puente entre detección estadística y regla de intervención auditable.
Multivariate monitoring and OCAP (out-of-control action plan) design. The bridge between statistical detection and an auditable intervention rule.
SPC
FASE 6 · BLOQUE 11 — PRODUCCIÓN Y DESPLIEGUE PHASE 6 · BLOCK 11 — PRODUCTION & DEPLOYMENT Producción del sistema — Arquitectura, API, contenedorización y despliegue público System productionization — Architecture, API, containerization and public deployment
Pendiente Pending
Pregunta que resolverá: ¿Cómo se transforma un sistema desarrollado en un notebook exploratorio con variables globales en un sistema modular, reproducible, contenedorizado y operable como servicio público?
Question to be solved: How is a system developed in an exploratory notebook with global variables transformed into a modular, reproducible, containerized system operable as a public service?
Wiggins, A. (2011) — "The Twelve-Factor App".
Metodología canónica para construir aplicaciones cloud-native portables y reproducibles. Justifica las decisiones de las capas 1 (modularización por responsabilidad), 5 (separación build/release/run vía Docker) y 6 (configuración en variables de entorno, dependencias declaradas explícitamente). Corta, libre y ampliamente referenciada en la industria.
Canonical methodology for building portable, reproducible cloud-native applications. Justifies the decisions of layers 1 (responsibility-based modularization), 5 (build/release/run separation via Docker), and 6 (config in environment variables, explicitly declared dependencies). Short, free, and widely referenced in the industry.
Arquitectura
Burkov, A. (2020) — "Machine Learning Engineering".
Cubre el ciclo completo de producción de un sistema ML: refactorización del código exploratorio, exposición vía API, contenedorización, testing, despliegue y monitorización básica. La referencia más concreta para el paso de notebook a producto en data science aplicado, sin sobrecargar con MLOps a gran escala. Aplica transversalmente a las siete capas.
Covers the complete production cycle of an ML system: refactoring exploratory code, API exposure, containerization, testing, deployment and basic monitoring. The most concrete reference for the notebook-to-product transition in applied data science, without overloading with large-scale MLOps. Applies transversally to the seven layers.
Producción
Capa 1 — Refactorización a módulos en src/
Separación del código del notebook en módulos Python por responsabilidad: preprocessing, baseline, deviation, spc, modeling, evaluation, visualization. El notebook queda como orquestación; las funciones core viven en src/.
Separation of notebook code into Python modules by responsibility: preprocessing, baseline, deviation, spc, modeling, evaluation, visualization. The notebook remains as orchestration; core functions live in src/.
Modularización
Capa 2 — API con FastAPI (api/main.py)
Capa HTTP que expone las funciones de src/ como endpoints. Diseño alineado con la naturaleza idiográfica del proyecto: /participants/{id}/zscores, /alerts, /trajectory, /dashboard. No copia el patrón genérico de clasificador ML (POST /predict_risk con score único).
HTTP layer that exposes src/ functions as endpoints. Design aligned with the project's idiographic nature: /participants/{id}/zscores, /alerts, /trajectory, /dashboard. Does not copy the generic ML classifier pattern (POST /predict_risk with a single score).
API
Capa 3 — Aplicación Streamlit
Interfaz web que consume la API FastAPI por HTTP y renderiza resultados. Selector de participante, vistas temporales de las cuatro dimensiones con baseline rolling sobreimpreso, z-scores, disparos CUSUM/EWMA, alertas SPC con explicación SHAP, métricas globales y OCAP. La demostración interactiva del proyecto.
Web interface that consumes the FastAPI API via HTTP and renders results. Participant selector, temporal views of the four dimensions with overlaid rolling baseline, z-scores, CUSUM/EWMA triggers, SPC alerts with SHAP explanation, global metrics and OCAP. The project's interactive demo.
UI
Capa 4 — Tests con pytest
Tests automatizados sobre funciones de src/ (baseline, z-score, CUSUM, EWMA, walk-forward validation) y sobre endpoints de api/ (códigos HTTP, manejo de errores, validación de inputs). El sello de calidad que separa prototipo de código profesional defendible.
Automated tests on src/ functions (baseline, z-score, CUSUM, EWMA, walk-forward validation) and on api/ endpoints (HTTP codes, error handling, input validation). The quality seal that separates prototype from defensible professional code.
Testing
Capa 5 — Contenedorización con Docker
Empaquetado del sistema (API + Streamlit + dependencias) en contenedores Docker. Dockerfile en la raíz, .dockerignore, docker-compose.yml para levantar ambos servicios con un único comando. Reproducibilidad y portabilidad.
Packaging of the system (API + Streamlit + dependencies) in Docker containers. Dockerfile at root, .dockerignore, docker-compose.yml to bring up both services with a single command. Reproducibility and portability.
Contenedorización
Capa 6 — Repositorio GitHub profesional
Repositorio público con README extenso (problema clínico, marco metodológico, decisiones de diseño, arquitectura, instrucciones de uso, resultados, limitaciones), requirements.txt con versiones fijadas, .gitignore correcto, estructura limpia (src/, api/, notebooks/, tests/, app.py, Dockerfile, docker-compose.yml).
Public repository with extensive README (clinical problem, methodological framework, design decisions, architecture, usage instructions, results, limitations), pinned requirements.txt, correct .gitignore, clean structure (src/, api/, notebooks/, tests/, app.py, Dockerfile, docker-compose.yml).
Repositorio
Capa 7 — Despliegue público
Despliegue del sistema completo (FastAPI + Streamlit orquestados con docker-compose) en un servicio cloud compatible con contenedores (Render, Railway o Fly.io). URL pública accesible desde cualquier navegador sin instalación local.
Deployment of the complete system (FastAPI + Streamlit orchestrated with docker-compose) on a container-compatible cloud service (Render, Railway or Fly.io). Public URL accessible from any browser without local installation.
Cloud
Decisión
Decision
Ejecutar las siete capas en orden tras cerrar el Bloque 10: refactorización a módulos en src/, exposición de la lógica vía API con FastAPI, construcción de UI con Streamlit consumiendo la API, validación con tests pytest, contenedorización con Docker, publicación en GitHub y despliegue público accesible vía URL. No introducir MLOps a gran escala (Kubernetes, Airflow, MLflow, CI/CD complejo).
Execute the seven layers in order after closing Block 10: refactoring to src/ modules, exposing logic via API with FastAPI, building UI with Streamlit consuming the API, validating with pytest tests, containerization with Docker, publishing on GitHub and public deployment accessible via URL. Do not introduce large-scale MLOps (Kubernetes, Airflow, MLflow, complex CI/CD).
Renuncia
Trade-off given up
Se renuncia a la simplicidad de mantener todo en un notebook único. Se renuncia también a una capa MLOps completa (orquestación con Airflow, tracking con MLflow, serving escalable, CI/CD avanzado), que pertenece a perfiles de ML Engineer y desviaría el foco del trabajo Health Data Scientist hacia ingeniería de plataforma sin retorno proporcional en el mercado objetivo.
The simplicity of keeping everything in a single notebook is given up. A full MLOps stack (Airflow orchestration, MLflow tracking, scalable serving, advanced CI/CD) is also given up, as it belongs to ML Engineer profiles and would shift the focus from Health Data Scientist work to platform engineering without proportional return in the target market.
Uso real
Real-world use
Cualquier persona puede abrir la URL pública y ver el sistema funcionando sin instalar nada. Cualquier desarrollador puede clonar el repositorio y levantar el entorno completo con un único comando (docker compose up). La lógica de cálculo (z-scores, SPC, alertas) queda accesible programáticamente vía API para integración futura con otros sistemas (apps clínicas, dashboards hospitalarios, EHR).
Any person can open the public URL and see the system working without installing anything. Any developer can clone the repository and bring up the complete environment with a single command (docker compose up). Computation logic (z-scores, SPC, alerts) remains programmatically accessible via API for future integration with other systems (clinical apps, hospital dashboards, EHR).
Trade-off
Trade-off
Se gana posicionamiento profesional como Data Scientist aplicado moderno, no solo investigador de notebook: se demuestra separación arquitectónica de responsabilidades, reproducibilidad por contenedores y entrega del trabajo como servicio operable. Se acepta el coste temporal de aprender y aplicar FastAPI, Docker y configuración de despliegue, herramientas no usadas durante el desarrollo del notebook pero que el mercado actual de Health DS espera ver en un portfolio competitivo.
Professional positioning as a modern applied Data Scientist (not just notebook researcher) is gained: architectural separation of responsibilities, reproducibility through containers and delivery of the work as an operable service. The time cost of learning and applying FastAPI, Docker and deployment configuration is accepted — tools not used during notebook development but that the current Health DS market expects to see in a competitive portfolio.

Bibliografía consolidada

Consolidated references

Índice completo de fuentes del proyecto

Full index of project sources

Las lecturas se distribuyen dentro de cada bloque para mostrar qué sustenta cada decisión. Esta sección recoge el índice consolidado, ordenado por para qué sirve cada fuente.

Readings are distributed within each block to show what supports each decision. This section collects the consolidated index, ordered by what each source is used for.

Daza (2018). Daza, E. J. (2018). Causal Analysis of Self-tracked Time Series Data Using a Counterfactual Framework for N-of-1 Trials. Methods of Information in Medicine, 57(Open 1), e10–e21.
Marco
Vieira et al. (2017). Dynamic modelling of n-of-1 data: powerful and flexible data analytics applied to individualised studies. Health Psychology Review, 11(3), 222–234.
Marco
Montgomery — "Introduction to Statistical Quality Control".
La base de SPC, CUSUM y EWMA. Todo el sistema de detección de deterioro sostenido se implementa sobre los principios de este libro. Es la columna vertebral técnica del proyecto, presente desde el Bloque 2 hasta el Bloque 10.
The foundation of SPC, CUSUM and EWMA. The entire sustained-deterioration detection system is implemented on this book's principles. It is the technical backbone of the project, present from Block 2 through Block 10.
SPC
Aminikhanghahi & Cook (2017) — "A Survey of Methods for Time Series Change Point Detection". KAIS.
La revisión de referencia para situar CUSUM/EWMA dentro del ecosistema más amplio de change point detection. Permite defender por qué se eligen estos métodos frente a alternativas modernas.
The reference review for situating CUSUM/EWMA within the broader change point detection ecosystem. Allows defending why these methods are chosen over modern alternatives.
Change point
Adams & MacKay (2007) — "Bayesian Online Changepoint Detection".
El paper original de BOCPD. Se evalúa como alternativa bayesiana a CUSUM para detección online. Su consideración explícita demuestra que se conoce el espacio de soluciones, no solo la solución elegida.
The original BOCPD paper. Evaluated as a Bayesian alternative to CUSUM for online detection. Its explicit consideration shows knowledge of the solution space, not just the chosen solution.
Change point
Killick, Fearnhead & Eckley (2012) — "Optimal Detection of Changepoints with a Linear Computational Cost".
Paper original del algoritmo PELT, implementado en la librería ruptures. El algoritmo offline que se usará en la fase de análisis retrospectivo de trayectorias.
Original paper of the PELT algorithm, implemented in the ruptures library. The offline algorithm that will be used in the retrospective trajectory analysis phase.
Change point
Van den Burg & Williams (2020) — An Evaluation of Change Point Detection Algorithms".
Aplicación específica de change-point detection a datos de wearables y salud. Conecta directamente con el dominio del proyecto y demuestra la viabilidad del enfoque en producción.
Specific application of change-point detection to wearables and health data. Connects directly with the project's domain and demonstrates the viability of the approach in production.
Change point
Xu et al. (2022) — "GLOBEM Dataset: Multi-Year Datasets for Longitudinal Human Behavior Modeling".
La fuente del dataset y el benchmark de referencia. El 54.7% de precisión de su mejor modelo es el punto de partida que motiva cambiar el enfoque.
The dataset's source and the reference benchmark. The 54.7% accuracy of their best model is the starting point that motivates changing the approach.
Dataset
Hunt, Auriemma & Cashaw (2003) — "Self-report bias and underreporting of depression on the BDI-II". Journal of Personality Assessment.
Justifica metodológicamente el rechazo del BDI-II como target. Muestra experimentalmente que los sujetos reportan más síntomas cuando el propósito del cuestionario está enmascarado — evidencia directa de infraestimación sistemática.
Methodologically justifies the rejection of BDI-II as target. Shows experimentally that subjects report more symptoms when the questionnaire's purpose is masked — direct evidence of systematic underreporting.
Dominio
Difrancesco et al. (2019) — "Sleep, circadian rhythm, and physical activity patterns in depressive and anxiety disorders". Depression and Anxiety.
Respaldo empírico directo para la elección de sueño y actividad como señales núcleo. Documenta los patrones conductuales específicos —sueño fragmentado, reducción de actividad, alteración circadiana— que este sistema está diseñado para detectar.
Direct empirical support for the choice of sleep and activity as core signals. Documents the specific behavioral patterns — fragmented sleep, reduced activity, circadian disruption — that this system is designed to detect.
Dominio
Bhattacharya et al. (2024) — "Imputation Strategies for Longitudinal Behavioral Studies: Predicting Depression Using GLOBEM Datasets". ACM UbiComp.
Trabajo reciente sobre el mismo dataset que sigue dentro del paradigma poblacional. Delimita con precisión el hueco que este proyecto ocupa: los enfoques más recientes sobre GLOBEM siguen sin abordar el enfoque intra-sujeto.
Recent work on the same dataset that remains within the population paradigm. Precisely delimits the gap this project fills: the most recent approaches on GLOBEM still do not address the intra-subject approach.
Dominio
Wichers, Smit & Snippe (2020) — "Early Warning Signals Based on Momentary Affect Dynamics can Expose Nearby Transitions in Depression: A Confirmatory Single-Subject Time-Series Study".
Base teórica para el Bloque 4. Introduce formalmente que la varianza creciente y la autocorrelación creciente en datos momentáneos son indicadores anticipatorios de transiciones psicopatológicas — el fundamento de por qué se monitoriza dinámica temporal y no solo niveles.
Theoretical basis for Block 4. Formally introduces that rising variance and rising autocorrelation in momentary data are anticipatory indicators of psychopathological transitions — the foundation for why temporal dynamics, not just levels, are monitored.
Dominio
Olthof, Hasselman & Strunk (2020) — "Critical Fluctuations as an Early-Warning Signal for Sudden Gains and Losses in Patients Receiving Psychotherapy for Mood Disorders".
Validación empírica del enfoque de señales tempranas. Demuestra sobre 328 casos clínicos reales que las fluctuaciones críticas anticipan cambios sostenidos — evidencia directa de que el deterioro tiene firma estadística detectable antes de manifestarse.
Empirical validation of the early-warning approach. Demonstrates on 328 real clinical cases that critical fluctuations anticipate sustained changes — direct evidence that deterioration has a detectable statistical signature before it manifests.
Dominio
Smit, Snippe & Wichers (2019) — "Increasing restlessness signals impending increase in depressive symptoms more than 2 months before it happens in individual patients".
Justificación empírica del Bloque 7 (CUSUM/EWMA). Demostró que señales monitorizadas con SPC predicen aumentos de síntomas depresivos con más de 2 meses de antelación en pacientes individuales — la evidencia de dominio más directa para el enfoque de este proyecto.
Empirical justification for Block 7 (CUSUM/EWMA). Showed that signals monitored with SPC predict increases in depressive symptoms more than 2 months in advance in individual patients — the most direct domain evidence for this project's approach.
Dominio
Smit & Snippe (2023) — "Real-time monitoring of increases in restlessness to assess idiographic risk of recurrence of depressive symptoms".
Replicación y extensión del estudio anterior. Aplicando EWMA a datos EMA de varios meses, los episodios depresivos podían preverse con semanas de antelación. Demuestra que el enfoque intra-sujeto con EWMA es viable en producción clínica real.
Replication and extension of the previous study. Applying EWMA to EMA data over several months, depressive episodes could be foreseen weeks in advance. Demonstrates that the intra-subject approach with EWMA is viable in real clinical production.
Dominio
James et al. — "An Introduction to Statistical Learning" (ISLR).
Base de los métodos de modelado supervisado que se aplicarán en el Bloque 6. También cubre los fundamentos de validación cruzada y selección de modelos. Lectura en paralelo desde el Bloque 2.
Foundation of the supervised modeling methods that will be applied in Block 6. Also covers the fundamentals of cross-validation and model selection. Read in parallel from Block 2.
ML
Géron — "Hands-On Machine Learning with Scikit-Learn, Keras & TensorFlow".
Implementación práctica de los pipelines de ML. Especialmente relevante para árboles de decisión, ensemble learning y pipelines de modelado del Bloque 6.
Practical implementation of ML pipelines. Especially relevant for decision trees, ensemble learning and the modeling pipelines of Block 6.
ML
Hyndman & Athanasopoulos — "Forecasting: Principles and Practice, the Pythonic Way. OTexts.
Cubre análisis exploratorio de series temporales — descomposición, autocorrelación, features y ventanas móviles.
Covers exploratory time series analysis — decomposition, autocorrelation, features and rolling windows.
Series temp.
Christoph Molnar — "Interpretable Machine Learning".
Referencia del Bloque 9 (SHAP). Explica cómo abrir un modelo de machine learning y ver qué variables han pesado en cada predicción concreta. Necesario para traducir la señal de deterioro a un lenguaje accionable para un clínico.
Reference for Block 9 (SHAP). Explains how to open up a machine learning model and see which variables weighed in each specific prediction. Necessary to translate the deterioration signal into actionable language for a clinician.
ML

Glosario

Glossary

Términos técnicos del proyecto

Project technical terms

¿Quieres bajar al código?

Would you like to download the code?

El notebook técnico documenta cada decisión implementada. El análisis exploratorio, la construcción del baseline y el pipeline de features están disponibles en GitHub.

The technical notebook documents every decision that was implemented. The exploratory analysis, baseline construction, and feature pipeline are available on GitHub

Ver notebook en GitHub → View the notebook on GitHub → Actualizado a medida que avanzan los bloques Updated as the blocks progress