Release model, model card and example
Browse filesFiles changed (6)
- README.mdAdded+79
- config.jsonAdded+60
- encoder.onnxAdded+3
- encoder.ptAdded+3
- example.pyAdded+25
- example_ecg.jsonAdded
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879---license: cc-by-4.0library_name: onnxpipeline_tag: feature-extractiontags: [ecg, electrocardiogram, self-supervised-learning, simclr, foundation-model, contrastive-learning, embeddings, healthcare, medical-ai, pytorch, onnx]datasets: [ptb-xl]metrics: [roc_auc]---
# Before the Labels: a self-supervised ECG encoder (SimCLR, 70,244 unlabelled ECGs)
A small ECG **foundation encoder**: it turns any 2.5-second, 100 Hz ECG window (12 leads, or fewer with the missing ones set to 0)into a **256-number embedding**. It was pretrained with **SimCLR contrastive learning on 70,244 unlabelled 12-lead ECGs** fromGermany (PTB-XL folds 1–8) and China (Chapman–Shaoxing, Ningbo, CPSC 2018 + extra), without any diagnosis labels.
Use it to train a good ECG classifier from **very few labels**, or to search for and cluster ECGs by similarity.
> ⚠️ **Research model, not a medical device.** Trained and tested on public retrospective data only. Do not use it for diagnosis or treatment decisions.
**Code, full report and model card:** https://github.com/rigel08/ecg-foundation-model
## Does pretraining help? (PTB-XL test fold 10, macro AUROC, mean of 3 seeds, 95% bootstrap CI)
| Labels used | From scratch | **This encoder, fine-tuned** | Gain ||---|---|---|---|| 1% (171 ECGs) | 0.819 | **0.846** | +0.027 [+0.022, +0.033] || 10% | 0.890 | **0.897** | +0.007 [+0.003, +0.011] || 100% | 0.929 | **0.933** | +0.004 [+0.002, +0.006] |
- **The gain is biggest when labels are scarce, and small with all labels.**- On an unseen US hospital (Georgia, never seen in pretraining or training): 0.788 vs 0.764 at 1% labels.- **Lead I only (smartwatch-style), 171 labels:** this encoder kept **frozen**, with a logistic regression on top, scores **0.798**. A full network trained from scratch on the same ECGs scores 0.767.
## Files
| File | What it is ||---|---|| `encoder.onnx` | Encoder. Input `x` (batch, 12, time), output `embedding` (batch, 256). Matches PyTorch to within 4e-6 || `encoder.pt` | PyTorch `state_dict` for the `Encoder` class in the GitHub repo (`src/models.py`) || `config.json` | Lead order, per-lead normalisation, window length, pretraining details || `example_ecg.json` | One real PTB-XL test ECG || `example.py` | Embeds the example ECG (12 leads and Lead I only) and compares them |
## Use it
```bashpip install onnxruntime huggingface_hub numpypython example.py```
```pythonimport json, numpy as np, onnxruntime as ortfrom huggingface_hub import hf_hub_download
repo = "rigel08/before-the-labels-ecg-encoder"cfg = json.load(open(hf_hub_download(repo, "config.json")))enc = ort.InferenceSession(hf_hub_download(repo, "encoder.onnx"))
ecg = np.array(json.load(open(hf_hub_download(repo, "example_ecg.json")))["x_mV_time_by_lead"], np.float32) # (1000, 12) mV, 100 Hzx = (ecg - np.array(cfg["per_lead_mean_mV"])) / np.array(cfg["per_lead_std_mV"]) # per-lead normalisationwindows = np.stack([x[s:s + 250].T for s in range(0, 751, 125)]).astype(np.float32) # (7, 12, 250)emb = enc.run(None, {"x": windows})[0].mean(0) # (256,) embedding of the whole ECG# Single-lead ECG? Normalise, then set the other 11 leads to 0 before embedding.```
Then train a logistic regression or small MLP on these embeddings with your own labels.
## Pretraining- SimCLR (NT-Xent loss): two random augmentations of the same window are pulled together and other windows are pushed apart. Augmentations include random crop, scaling, Gaussian noise, baseline wander and lead dropout.- Encoder: 7-tap conv stem + 3 residual blocks (width 128), then concat(average, max) pooling (405,760 parameters). 40 epochs on an Apple M2 (8 GB).- Every source was harmonised to 100 Hz, millivolts and the standard lead order. Records with more than 2 flat leads were removed.
## Limitations- Data from two countries only (Germany, China). Validated downstream on PTB-XL and one US dataset (Georgia).- Gains at 100% labels are small (+0.004). The value is in low-label settings.- Lead I results use Lead I taken from 12-lead recordings, not real smartwatch signals.
**Portfolio:** https://rigel08.github.io/portfolio-site/ · **GitHub:** https://github.com/rigel08 · **All my models and demos:** https://huggingface.co/rigel08123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960{ "embedding_dim": 256, "input": "(batch, 12, 250): 2.5 s at 100 Hz, leads I,II,III,aVR,aVL,aVF,V1-V6, per-lead normalised; missing leads = 0", "sampling_rate_hz": 100, "window_samples": 250, "all_leads": [ "I", "II", "III", "aVR", "aVL", "aVF", "V1", "V2", "V3", "V4", "V5", "V6" ], "per_lead_mean_mV": [ -0.0017467011930420995, -0.001521246274933219, 0.00022543493832927197, 0.0016164503758773208, -0.0009318771190010011, -0.0006254705949686468, 0.00017760322953108698, -0.0009518787846900523, -0.0015651548746973276, -0.0013563017128035426, -0.0007997320499271154, -0.002423869911581278 ], "per_lead_std_mV": [ 0.16000984609127045, 0.15922950208187103, 0.15997213125228882, 0.13814756274223328, 0.13876701891422272, 0.13797743618488312, 0.23434923589229584, 0.3342159688472748, 0.3284686505794525, 0.2927635908126831, 0.27206921577453613, 0.2809426784515381 ], "pretraining": { "method": "SimCLR (NT-Xent)", "epochs": 40, "records": 70244, "sources": [ "PTB-XL folds 1-8 (Germany)", "Chapman-Shaoxing (China)", "Ningbo (China)", "CPSC 2018 (China)", "CPSC 2018 extra (China)" ] }}123version https://git-lfs.github.com/spec/v1oid sha256:01e28919ba70f2d2dce16421657a1455695c82cdf1da30fe0bb702cce3c36395size 1623345123version https://git-lfs.github.com/spec/v1oid sha256:4fa1b3af1b39a5995e50097bb0556866606637010bb78bc56a4bd886aea7434asize 164413312345678910111213141516171819202122232425"""Embed one ECG with the self-supervised encoder, using all 12 leads and Lead I only."""import jsonimport numpy as npimport onnxruntime as ortfrom huggingface_hub import hf_hub_download
REPO = "rigel08/before-the-labels-ecg-encoder"cfg = json.load(open(hf_hub_download(REPO, "config.json")))enc = ort.InferenceSession(hf_hub_download(REPO, "encoder.onnx"))ex = json.load(open(hf_hub_download(REPO, "example_ecg.json")))ecg = np.array(ex["x_mV_time_by_lead"], np.float32) # (1000, 12), mV, 100 Hzx = (ecg - np.array(cfg["per_lead_mean_mV"])) / np.array(cfg["per_lead_std_mV"])
def embed(x): windows = np.stack([x[s:s + cfg["window_samples"]].T for s in range(0, 1000 - 250 + 1, 125)]).astype(np.float32) return enc.run(None, {"x": windows})[0].mean(0)
full = embed(x)lead_i = x.copy(); lead_i[:, 1:] = 0 # smartwatch-style: only Lead I keptwatch = embed(lead_i)cos = float(full @ watch / (np.linalg.norm(full) * np.linalg.norm(watch)))print(f"ECG {ex['id']} ({ex['labels']}): embedding shape {full.shape}")print(f"cosine similarity, 12-lead vs Lead-I-only embedding: {cos:.3f}")README.mdAdded+79
config.jsonAdded+60
encoder.onnxAdded+3
encoder.ptAdded+3
example.pyAdded+25
example_ecg.jsonAdded