File size: 7,307 Bytes
64cc5fe
fee08ca
4905dc2
6da40bb
 
fee08ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6da40bb
fee08ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64cc5fe
fee08ca
6da40bb
fee08ca
6da40bb
fee08ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6da40bb
fee08ca
 
 
 
 
 
 
 
 
 
 
 
 
ddc5b19
fee08ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
---

language: en
license: apache-2.0
app_type: gradio
space: Tumo505/SSL-ECG-Classification
datasets:
- ptb-xl
metrics:
- auroc
- accuracy
tags:
- ecg
- medical
- time-series
- classification
- self-supervised-learning
- ssl
- cardiac
- healthcare
model-index:
- name: SSL-ECG-Classifier
  results:
  - task:
      name: Time Series Classification
      type: tabular-classification
    dataset:
      name: PTB-XL
      type: ptb-xl
      split: test
      args:
        fold: 10
    metrics:
    - name: AUROC
      type: auroc
      value: 0.8717
    - name: Accuracy
      type: accuracy
      value: 0.8234
inference: true
widget:
- src: https://huggingface.co/datasets/Tumo505/ecg-samples/resolve/main/example_normal.csv
  example_title: "Normal ECG (NORM)"
- src: https://huggingface.co/datasets/Tumo505/ecg-samples/resolve/main/example_mi.csv
  example_title: "Myocardial Infarction (MI)"
- src: https://huggingface.co/datasets/Tumo505/ecg-samples/resolve/main/example_sttc.csv
  example_title: "ST/T Changes (STTC)"
---


# SSL-ECG-Classifier: Self-Supervised Learning for ECG Classification

**Self-Supervised Learning (SSL)** pre-trained model for ECG cardiovascular disease classification.

## Model Overview

| Property | Value |
|----------|-------|
| **Framework** | SimCLR |
| **Test AUROC** | 0.8717 |
| **Test Accuracy** | 0.8234 |
| **Dataset** | PTB-XL (21.8K ECGs) |
| **Fine-tuning** | 10% labeled data (1,747 samples) |
| **Input** | 12-lead ECG @ 100 Hz (5,000 samples) |
| **Output** | 5-class classification |

## Classes Predicted

- **NORM**: Normal ECG
- **MI**: Myocardial Infarction
- **STTC**: ST/T Changes
- **HYP**: Hypertrophy (LVH)
- **CD**: Conduction Disturbances

## Quick Start

### Python (Transformers)

```python

import torch

from transformers import AutoModel



# Load model

model = AutoModel.from_pretrained("Tumo505/SSL-ECG-Classificcation", trust_remote_code=True)

model.eval()



# Prepare 12-lead ECG (batch_size, 12 leads, 5000 samples)

ecg = torch.randn(1, 12, 5000)



# Predict

with torch.no_grad():

    output = model(ecg)

    logits = output["logits"]

    probs = torch.softmax(logits, dim=-1)



classes = ["NORM", "MI", "STTC", "HYP", "CD"]

prediction = classes[probs.argmax(dim=-1)[0]]

confidence = probs.max().item()



print(f"Prediction: {prediction} ({confidence:.1%})")

```

### Try Online

Click the **"Use this model"** button above to test on Gradio Space!

### API Endpoint (Deploy)

Click the **"Deploy"** button to get a live inference endpoint:

```bash

curl -X POST https://your-api-url.hf.space/api/predict \

  -H "Authorization: Bearer YOUR_HF_TOKEN" \

  -H "Content-Type: application/json" \

  -d '{

    "inputs": [[[... 12-lead ECG array ...]]]

  }'

```

## Model Architecture

```

Input (B × 12 × 5000)

    ↓

1D CNN Encoder

  - Conv1d(12 → 32) + BatchNorm + ReLU + MaxPool

  - Conv1d(32 → 64) + BatchNorm + ReLU + MaxPool

  - Conv1d(64 → 128) + BatchNorm + ReLU

  - AdaptiveAvgPool1d(1) + Flatten

    ↓

Projection Head (128-dim embedding)

    ↓

Classification Head (5 classes)

    ↓

Output (B × 5) logits

```

## Performance Metrics

### Test Set Results (PTB-XL Fold 10: 3,044 samples)

```

Class     | Precision | Recall | F1-Score | Support

----------|-----------|--------|----------|----------

NORM      | 0.897     | 0.882  | 0.889    | 1,275

MI        | 0.856     | 0.834  | 0.845    |   904

STTC      | 0.871     | 0.859  | 0.865    |   776

HYP       | 0.812     | 0.798  | 0.805    |   356

CD        | 0.843     | 0.866  | 0.854    |   733

----------|-----------|--------|----------|----------

Macro Avg | 0.856     | 0.848  | 0.852    | 4,044

```

### Comparison to Baselines

| Model | Framework | AUROC | Accuracy | Method |
|-------|-----------|-------|----------|--------|
| **SimCLR (This)** | **SSL + Supervised** | **0.8717** | **0.8234** | **Recommended** |
| BYOL SSL | SSL momentum | 0.8565 | 0.8134 | Alternative |
| Supervised CNN | None | 0.8606 | 0.8193 | Baseline |

## Training Details

### Pre-training (Unsupervised SSL)

- **Framework:** SimCLR
- **Epochs:** 20
- **Batch Size:** 128
- **Optimizer:** Adam (lr=1e-3)
- **Loss:** Contrastive (NT-Xent with Ï„=0.07)
- **Data:** All PTB-XL training folds (no labels used)

### Fine-tuning (Supervised)

- **Labeled Data:** 1,747 samples (10% of fold 1-8)
- **Epochs:** 20 with early stopping (patience=5)
- **Batch Size:** 32
- **Optimizer:** Adam (lr=5e-4)
- **Loss:** Focal Loss with class weights
- **Augmentations:** Training-time augmentations (same as pre-training)

### Domain-Adaptive Augmentations

Applied during SSL pre-training:
1. **Frequency warping** (±5% heart rate variation)
2. **Medical mixup** (ECG-aware blending of two signals)
3. **Bandpass filtering** (physiologically grounded)
4. **Segment CutMix** (temporal masking)
5. **Motion artifacts** (baseline wander simulation)
6. **Per-channel noise** (independent Gaussian)
7. **Temporal dropout** (with interpolation)

## Dataset

### PTB-XL v1.0.3

**Source:** https://www.physionet.org/content/ptb-xl/1.0.3/

- **Total ECGs:** 21,799
- **Unique Patients:** 18,869
- **Recording Rate:** 500 Hz → downsampled to 100 Hz
- **Leads:** 12-lead standard
- **Duration:** ~10 seconds per recording

**Class Distribution:**

| Class | Count | Percentage |
|-------|-------|-----------|
| NORM | 9,514 | 43.7% |
| MI | 5,469 | 25.1% |
| STTC | 5,235 | 24.0% |
| CD | 4,898 | 22.5% |
| HYP | 2,649 | 12.2% |

*Note: Samples can belong to multiple classes*

**Splits Used:**
- **Training**: Folds 1-8 (17,536 samples)
- **Validation**: Fold 9 (1,791 samples)
- **Test**: Fold 10 (3,044 samples)

## Limitations & Biases

### Limitations

**Not validated for clinical use** - Research purposes only

- Trained exclusively on PTB-XL; generalization to other datasets unknown
- 12-lead ECG format required; doesn't work with 6-lead or converted signals
- 10% labeled data regime may not reflect full model capacity
- Works only for the 5 trained classes

### Potential Biases

- **Geographic bias:** Primarily European patient population (PTB-XL)
- **Hospital bias:** Data from hospital patients (not general population)
- **Class imbalance:** NORM over-represented, HYP under-represented
- **Demographic:** Skew toward older patients; male/female ratio not controlled

## Environmental Impact

- **Training:** ~12 GPU hours on RTX 5070 Ti
- **CO2 Emissions:** ~0.5 kg (estimated)
- **Inference:** ~50ms per 10-second ECG on GPU

## License

Apache 2.0 - See LICENSE file in repository


## Acknowledgments

- PTB-XL Dataset: Physionet, Wagner et al. (2020)
- SimCLR Framework: Chen et al. (2020)
- Implementation: Built with PyTorch & Hugging Face

## Model Card Contact

- **Author:** Tumo Kgabeng
- **GitHub:** https://github.com/Tumo505/SSL-for-ECG-classification

## Changelog

### v1.0 (2026-04-18)
- Initial release
- SimCLR pre-training + supervised fine-tuning
- 10% labeled data regime
- Test AUROC: 0.8717

---

**Questions?** Open an issue on [GitHub](https://github.com/Tumo505/SSL-for-ECG-classification)