Este texto comenta la arquitectura y el caso de uso de mi TFM en el Master en Data Science, Big Data & Business Analytics de la Universidad Complutense de Madrid (promoción 2023-2024), desarrollado en colaboración con Dawako Med Tech (Valencia) bajo acuerdo de protección de datos. El dataset, el código fuente y los pesos entrenados no son públicos — y no lo serán. Pero el problema clínico, la lógica arquitectónica y las decisiones de despliegue sí pueden compartirse, y son lo realmente transferible a otros clientes en sectores regulados.
Por qué la sarcopenia, por qué deportistas
La sarcopenia — pérdida progresiva de masa y función muscular — dejó hace tiempo de ser un asunto exclusivo de la geriatría. En medicina deportiva de élite es un marcador temprano de sobreentrenamiento, recuperación incompleta o lesión inminente. El recto femoral es la estructura más estudiada para estimarla porque es accesible, repetible y permite medir área transversal y arquitectura fascicular con ecografía portátil.
Dawako Med Tech ya tenía un dataset clínico considerable adquirido con un ecógrafo Esaote MyLab Sigma y una aplicación propia (DAWAKO App) para que profesionales sanitarios generaran máscaras de segmentación manuales — imágenes binarias PNG donde la región muscular vale 255 y el fondo 0, sin huecos internos. El TFM consistió en construir un sistema de visión por computador capaz de aprender esa segmentación profesional y devolver áreas y clasificaciones automáticas, asistiendo al clínico, no sustituyéndolo.
El dato que no puede irse del edificio
El input clínico es ultrasonido del recto femoral. En Europa, ese dato cae con claridad bajo el Art. 9 del RGPD: categoría especial de datos relativos a la salud. La excepción 9.2.h permite tratamiento con fines de medicina preventiva y diagnóstico, pero exige garantías técnicas y organizativas reforzadas. Traducción operativa: el dato no se sube a una API SaaS estadounidense para que un endpoint te devuelva un mapa de segmentación.
No es ideología. Es ingeniería de cumplimiento. Cualquier acuerdo entre una empresa MedTech y un investigador académico — incluso con fines exclusivamente formativos como un TFM — tiene que documentar la jurisdicción del dato desde la primera línea. El NDA con Dawako lo dejó claro: el dataset no se distribuye, el código no se publica, y cualquier divulgación de resultados pasa por revisión.
El pipeline que realmente funcionó
El stack del TFM fue Python sobre TensorFlow 2.15-2.17 con interfaz Keras 2.15, ejecutado en Google Colab con acceso a GPUs gratuitas para iteración rápida. Para producción local final se empaquetó en una app interactiva de Streamlit que carga imagen ecográfica y devuelve la segmentación predicha sobre el navegador. El procesamiento de imágenes se apoyó en OpenCV, NumPy y Scikit-learn — toolkit clásico, sin frameworks exóticos, deliberadamente mantenible.
Esaote MyLab Sigma (ultrasonido RF probe)
↓
DAWAKO App (máscaras manuales · binarias 255/0)
↓
Pre-procesamiento OpenCV:
├─ pipeline A: Gaussian Blur + CLAHE (256×256)
└─ pipeline B: Median + CLAHE + Wavelet (512×512)
↓
Modelos TensorFlow/Keras (Colab GPU):
├─ U-Net para segmentación
└─ ResNet para clasificación binaria sarcopenia
↓
Métricas: Dice Coefficient + Balanced Multi-Class Accuracy
↓
Streamlit local · médico revisa antes de validar
La elección de pipeline de pre-procesamiento fue lo más interesante del trabajo. Las imágenes de ultrasonido tienen bajo contraste y ruido speckle característico, así que probamos cinco técnicas (CLAHE, Histogram Equalization global, Gaussian Blur, Bilateral Filter, Median Filter, transformada Wavelet) y dos combinaciones ganadoras quedaron documentadas:
Combinación A · 256×256. Gaussian Blur + CLAHE. El desenfoque gaussiano suaviza el ruido speckle; CLAHE realza contraste localmente con clip limit controlado para no amplificar ruido. Rápido, robusto, buen baseline.
Combinación B · 512×512. Median Filter → CLAHE → Wavelet. El filtro mediano reduce ruido salt-and-pepper preservando bordes (crítico en límites de tejido); CLAHE mejora contraste sobre la imagen ya limpia; finalmente la transformada Wavelet conserva sólo los componentes de baja frecuencia (LL) y descarta el ruido de alta frecuencia. Más caro de computar, pero el modelo aprendía bordes fasciculares con mucha más nitidez.
«Las métricas que importan en imagen biomédica no son las del paper. Son las que el clínico acepta cuando ve la salida superpuesta sobre la imagen que conoce.»
Las métricas que importaban
Dos métricas guiaron la evaluación, elegidas para los dos cabezales del modelo:
Dice Coefficient para la cabeza de segmentación — mide el solapamiento entre máscara predicha y máscara de referencia (la generada por profesionales con la DAWAKO App). Es el estándar en imagen médica porque penaliza tanto falsos positivos como negativos en la región de interés.
Balanced Multi-Class Accuracy para el clasificador. Es la métrica honesta cuando hay desequilibrio de clases (más imágenes de músculo sano que sarcopénico): calcula precisión por clase y promedia, así el modelo no puede ganar score prediciendo siempre la clase mayoritaria. Esa decisión metodológica fue la que defendí en el tribunal y la que considero más generalizable: cualquiera que reporte accuracy simple sobre un dataset clínico desbalanceado está vendiendo humo.
Cómo replantearía el despliegue hoy
El TFM se entregó en 2024. Si Dawako, o un cliente equivalente — clínica deportiva, federación, hospital deportivo de élite — entrara hoy en Digital Realism con el mismo problema, no replicaría exactamente el stack del TFM. Hay tres cosas que cambiaría, no porque el TFM fuera incorrecto, sino porque el ecosistema avanzó y porque las exigencias de un despliegue productivo son más altas que las de un trabajo académico.
Uno · adiós Colab, hola Apple Silicon nativo. Colab fue ideal para iterar rápido durante la tesis, pero como dependencia de producción es frágil: cuotas variables, sesiones que mueren, dato que viaja. PyTorch MPS (Metal Performance Shaders) cerró su brecha de soporte con CUDA durante 2024-2025 y hoy ejecuta U-Net y ResNet sobre Apple Silicon sin fricción. Un Mac Mini M4 (24-32 GB de memoria unificada) cubre inferencia productiva para una clínica con 30-60 ecografías/día con latencia sub-segundo y consumo medio ~30W. Mismo modelo, sin Colab, sin cloud, dato 100% en sede.
Dos · audit trail incorporado al producto. El TFM no necesitaba traceabilidad porque era un trabajo académico. Un despliegue clínico real sí. Langfuse self-hosted sobre la misma infraestructura del cliente registra cada inferencia (hash del input, modelo, versión, máscara devuelta, score) sin enviar nada a SaaS externo. Eso es lo que convierte un sistema improvisado en uno auditable bajo Art. 30 RGPD. Veinte líneas de código, cinco minutos de configuración, defensa técnica perpetua frente a una inspección.
Tres · cuantización int8 para producción, fp32 para reentrenamiento. El modelo cuantizado pierde una fracción de Dice contra fp32, pero gana 3-4× en latencia y eficiencia energética. Para un caso donde el clínico revisa cada salida antes de validar, esa pérdida es aceptable. La regla operativa: cuantizar lo que va a producción, mantener checkpoints fp32 para reentrenamiento periódico cuando entren imágenes nuevas anotadas.
Lo que el TFM demostró y por qué importa más allá del paper
Tres lecciones de Hygeia que valen para cualquier caso clínico equivalente — radiología, dermatología, oftalmología — donde el dato está bajo Art. 9.
El visor importa tanto como el modelo. El clínico no firma sobre una salida JSON; firma sobre una imagen anotada que entiende. Streamlit con overlay de la segmentación cubre el 90% de los casos sin necesidad de Slicer 3D ni infraestructura PACS pesada. El médico vio la máscara, asintió, y eso fue el primer indicador real de que el sistema servía.
El pre-procesamiento es 50% del modelo. La diferencia entre el pipeline ingenuo (imagen original a la red) y el pipeline Median→CLAHE→Wavelet fue mayor que cualquier ajuste de hiperparámetros que probamos después. En imagen biomédica, la decisión de pre-procesamiento es ingeniería tan crítica como la elección de arquitectura.
El acuerdo de datos es parte del entregable. Un TFM en colaboración con MedTech sin NDA no debería existir. Es lo que distingue una colaboración seria de una práctica académica. El NDA firmado con Dawako fue el motivo por el que esta entrada existe: define exactamente qué se cuenta y qué no, y eso es replicable como práctica con cualquier cliente futuro.
«La mejor arquitectura clínica no es la que usa el modelo más grande. Es la que el equipo del hospital puede mantener cuando el consultor se ha ido.»
Hygeia obtuvo el Premio al Mejor TFM de la promoción 2023-2024 del Master en Data Science de la Universidad Complutense — pero su valor real no estaba en la calificación académica. Estaba en haber cerrado el ciclo completo: problema clínico bien definido, dato real bajo NDA serio, pipeline reproducible, métricas honestas, despliegue local primero, y un clínico que dijo «esto me sirve».
This is a commentary on the architecture and use case of my M.Sc. thesis in Data Science, Big Data & Business Analytics at Universidad Complutense de Madrid (cohort 2023-2024), developed in collaboration with Dawako Med Tech (Valencia) under a data-protection agreement. The dataset, source code, and trained weights are not public — and will not be. But the clinical problem, the architectural logic, and the deployment decisions are shareable, and they are what's actually transferable to other clients in regulated sectors.
Why sarcopenia, why athletes
Sarcopenia — the progressive loss of muscle mass and function — has long since stopped being a geriatric concern alone. In elite sports medicine it is an early marker of overtraining, incomplete recovery, or imminent injury. The rectus femoris is the most-studied structure for estimating it because it's accessible, repeatable, and lets you measure cross-sectional area and fascicular architecture with portable ultrasound.
Dawako Med Tech already had a sizeable clinical dataset acquired with an Esaote MyLab Sigma ultrasound device and their own application (DAWAKO App) for healthcare professionals to generate manual segmentation masks — binary PNG images where the muscle region is 255 and background is 0, with no internal gaps. The thesis was to build a computer-vision system capable of learning that professional segmentation and returning automatic areas and classifications, assisting the clinician, not replacing them.
The data that cannot leave the building
The clinical input is rectus femoris ultrasound. In Europe, that data falls cleanly under GDPR Art. 9: special category health data. Exception 9.2.h allows processing for preventive medicine and diagnostic purposes, but demands reinforced technical and organisational safeguards. Operational translation: the data does not get uploaded to a US-based SaaS API for some endpoint to return a segmentation map.
This isn't ideology. It's compliance engineering. Any agreement between a MedTech company and an academic researcher — even for purely educational purposes like a thesis — has to document data jurisdiction from line one. The NDA with Dawako made it explicit: the dataset is not distributed, the code is not published, and any disclosure of results goes through review.
The pipeline that actually worked
The thesis stack was Python on TensorFlow 2.15-2.17 with the Keras 2.15 interface, run on Google Colab with free GPU access for fast iteration. For final local production it was packaged into an interactive Streamlit app that loads the ultrasound image and returns the predicted segmentation in the browser. Image processing leaned on OpenCV, NumPy, and Scikit-learn — classical toolkit, no exotic frameworks, deliberately maintainable.
Esaote MyLab Sigma (RF probe ultrasound)
↓
DAWAKO App (manual masks · binary 255/0)
↓
OpenCV pre-processing:
├─ pipeline A: Gaussian Blur + CLAHE (256×256)
└─ pipeline B: Median + CLAHE + Wavelet (512×512)
↓
TensorFlow/Keras models (Colab GPU):
├─ U-Net for segmentation
└─ ResNet for binary sarcopenia classification
↓
Metrics: Dice Coefficient + Balanced Multi-Class Accuracy
↓
Local Streamlit · clinician reviews before validating
The pre-processing pipeline choice was the most interesting part of the work. Ultrasound images have low contrast and characteristic speckle noise, so we tested five techniques (CLAHE, global Histogram Equalization, Gaussian Blur, Bilateral Filter, Median Filter, Wavelet transform) and two winning combinations were documented:
Combination A · 256×256. Gaussian Blur + CLAHE. Gaussian blur smooths speckle noise; CLAHE locally enhances contrast with controlled clip limit so noise isn't amplified. Fast, robust, solid baseline.
Combination B · 512×512. Median Filter → CLAHE → Wavelet. The median filter reduces salt-and-pepper noise while preserving edges (critical at tissue boundaries); CLAHE improves contrast over the cleaned image; finally the Wavelet transform keeps only low-frequency components (LL) and discards high-frequency noise. More expensive to compute, but the model learned fascicular boundaries with much more clarity.
"The metrics that matter in biomedical imaging are not the ones in the paper. They are the ones the clinician accepts when they see the output overlaid on the image they know."
The metrics that mattered
Two metrics guided evaluation, one for each model head:
Dice Coefficient for the segmentation head — measures overlap between predicted mask and ground-truth mask (the one generated by professionals with the DAWAKO App). It is the standard in medical imaging because it penalises both false positives and false negatives in the region of interest.
Balanced Multi-Class Accuracy for the classifier. It's the honest metric when there's class imbalance (more healthy than sarcopenic muscle images): it computes per-class accuracy and averages, so the model can't win score by always predicting the majority class. That methodological decision was the one I defended at the tribunal and the one I consider most generalisable: anyone reporting plain accuracy on an imbalanced clinical dataset is selling smoke.
How I would re-frame deployment today
The thesis was delivered in 2024. If Dawako, or an equivalent client — sports clinic, federation, elite sports hospital — came into Digital Realism today with the same problem, I wouldn't replicate the thesis stack exactly. There are three things I'd change, not because the thesis was wrong, but because the ecosystem moved on and because the demands of a production deployment are higher than those of an academic project.
One · goodbye Colab, hello native Apple Silicon. Colab was ideal for fast iteration during the thesis, but as a production dependency it's fragile: variable quotas, dying sessions, traveling data. PyTorch MPS (Metal Performance Shaders) closed its support gap with CUDA over 2024-2025 and today runs U-Net and ResNet on Apple Silicon without friction. A Mac Mini M4 (24-32 GB unified memory) covers production inference for a clinic with 30-60 ultrasounds/day with sub-second latency and ~30W average draw. Same model, no Colab, no cloud, data 100% on premises.
Two · audit trail built into the product. The thesis didn't need traceability because it was an academic work. A real clinical deployment does. Self-hosted Langfuse on the client's own infrastructure logs every inference (input hash, model, version, returned mask, score) without sending anything to external SaaS. That is what turns an improvised system into one auditable under GDPR Art. 30. Twenty lines of code, five minutes of configuration, perpetual technical defence against an inspection.
Three · int8 quantisation for production, fp32 for retraining. The quantised model loses a fraction of Dice against fp32, but gains 3-4× in latency and energy efficiency. For a case where the clinician reviews each output before validating, that loss is acceptable. The operational rule: quantise what goes to production, keep fp32 checkpoints for periodic retraining when new annotated images arrive.
What the thesis proved and why it matters beyond the paper
Three lessons from Hygeia that apply to any equivalent clinical case — radiology, dermatology, ophthalmology — where data falls under Art. 9.
The viewer matters as much as the model. Clinicians don't sign on JSON output; they sign on an annotated image they understand. Streamlit with segmentation overlay covers 90% of cases without needing 3D Slicer or heavy PACS infrastructure. The clinician saw the mask, nodded, and that was the first real signal the system was useful.
Pre-processing is 50% of the model. The difference between the naive pipeline (raw image into the network) and the Median→CLAHE→Wavelet pipeline was greater than any hyperparameter tuning we tried afterwards. In biomedical imaging, the pre-processing decision is engineering as critical as the architecture choice.
The data agreement is part of the deliverable. A thesis collaboration with a MedTech company without an NDA shouldn't exist. It's what distinguishes a serious collaboration from an academic exercise. The NDA signed with Dawako is the reason this entry exists: it defines exactly what gets told and what doesn't, and that is replicable as practice with any future client.
"The best clinical architecture is not the one that uses the largest model. It is the one the hospital team can maintain after the consultant is gone."
Hygeia received the Best Thesis Award for the 2023-2024 cohort of Universidad Complutense's M.Sc. Data Science programme — but its real value was not in the academic grade. It was in having closed the full cycle: a well-defined clinical problem, real data under a serious NDA, a reproducible pipeline, honest metrics, local-first deployment, and a clinician who said "this is useful to me".



