File size: 1,289 Bytes
47566f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99b52ce
47566f0
99b52ce
 
 
 
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
"""Embed one ECG with the self-supervised encoder, using all 12 leads and Lead I only."""
import json
import numpy as np
import onnxruntime as ort
from 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 Hz
x = (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: keep only Lead I
watch = embed(lead_i)
print(f"ECG {ex['id']} (cardiologist label {ex['labels']})")
print(f"12-lead embedding: shape {full.shape}, first values {np.round(full[:5], 3)}")
print(f"Lead-I embedding:  shape {watch.shape}, first values {np.round(watch[:5], 3)}")
print("Next step: compute embeddings for your own labelled ECGs and fit e.g. sklearn LogisticRegression on them.")