Evaluation API¶
Auto-generated from docstrings.
ecgen.evaluation¶
Measurements on (generated) ECGs, e.g. to check that a model follows the heart rate it was asked for.
detect_r_peaks
¶
detect_r_peaks(signal: ArrayLike, fs: int, lead: Optional[int] = None, method: str = 'simple') -> np.ndarray
R-peak sample indices of one ECG [C, T] (or [T]).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signal
|
ArrayLike
|
One ECG. |
required |
fs
|
int
|
Sampling rate in Hz. |
required |
lead
|
Optional[int]
|
Lead to use; default = the lead with the largest QRS energy. |
None
|
method
|
str
|
|
'simple'
|
Source code in src/ecgen/evaluation/measure.py
heart_rate
¶
heart_rate(signals: ArrayLike, fs: int, method: str = 'simple', lead: Optional[int] = None) -> np.ndarray
Heart rate (bpm) per ECG from the median RR interval; NaN when fewer than two beats are found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signals
|
ArrayLike
|
|
required |
fs
|
int
|
Sampling rate in Hz. |
required |
Source code in src/ecgen/evaluation/measure.py
adherence
¶
How well measured values follow requested ones (NaNs ignored).
Returns {"mae", "pearson_r", "n_valid", "n"}.
Source code in src/ecgen/evaluation/measure.py
Feature extractors for distribution metrics (Fréchet distance, MMD, precision/recall, nearest neighbours).
There is no single pretrained ECG encoder that every user has, so the default
is a set of interpretable hand-crafted features; any torch.nn.Module that
maps [B, C, T] to [B, D] (e.g. the penultimate layer of an ECG
classifier, see :mod:ecgen.evaluation.classifier) can be used instead.
handcrafted_features
¶
Per-ECG feature vector [N, D]:
- heart rate (bpm, NaN → batch median);
- per lead: standard deviation, 1st/99th percentile, and the relative power in the bands 0.5–5, 5–15, 15–40, 40–100 Hz;
- the upper triangle of the inter-lead correlation matrix.
Source code in src/ecgen/evaluation/features.py
module_features
¶
Wrap a [B, C, T] -> [B, D] network as an extractor.
Source code in src/ecgen/evaluation/features.py
Metrics for generated ECGs (plan §8): distribution fidelity and diversity, condition adherence, partial-ECG reconstruction, lead consistency, and memorisation.
Arrays are [N, C, T] (NumPy or torch). Distribution metrics work on feature
vectors from an extractor (:mod:ecgen.evaluation.features).
frechet_distance
¶
Fréchet distance between Gaussians fitted to two feature sets (FID-style).
Source code in src/ecgen/evaluation/metrics.py
mmd_rbf
¶
Unbiased squared MMD with an RBF kernel (bandwidth = median heuristic).
Source code in src/ecgen/evaluation/metrics.py
precision_recall
¶
k-NN manifold precision / recall (Kynkäänniemi et al., 2019): precision = share of generated samples inside the real manifold, recall = share of real samples inside the generated manifold.
Source code in src/ecgen/evaluation/metrics.py
distribution_metrics
¶
distribution_metrics(real: ArrayLike, fake: ArrayLike, fs: int = 500, extractor: Optional[Callable[[ArrayLike], ndarray]] = None, k: int = 3) -> Dict[str, float]
Fréchet distance, MMD and precision/recall between real and generated ECGs on
(standardized) features; default features: :func:handcrafted_features.
Source code in src/ecgen/evaluation/metrics.py
inter_lead_correlation_error
¶
Mean |corr_real − corr_fake| over lead pairs, using mean correlation matrices (MIDT-ECG).
Source code in src/ecgen/evaluation/metrics.py
einthoven_residual
¶
Relative residuals of the limb-lead identities (III = II − I, aVR = −(I + II)/2, aVL = I − II/2, aVF = II − I/2) after per-lead centering; ~0 for real recordings, larger when a model generates all 12 leads independently.
Source code in src/ecgen/evaluation/metrics.py
reconstruction_metrics
¶
MAE, RMSE and mean Pearson r on the unobserved entries (unobserved:
[N, C, T] or [C] / [N, C] bool, True = to evaluate).
Source code in src/ecgen/evaluation/metrics.py
nearest_neighbour_distances
¶
L2 distance from each query ECG to its nearest reference ECG (flattened signals).
Source code in src/ecgen/evaluation/metrics.py
memorization_ratio
¶
Median nearest-neighbour distance of generated ECGs to the training set, divided by that of held-out real ECGs. Values well below 1 suggest copying.
Source code in src/ecgen/evaluation/metrics.py
A small 1D-ResNet ECG classifier for condition adherence ("does a classifier trained on real ECGs recognise the requested labels in generated ones?") and for TSTR / TRTR (train on synthetic / real, test on real).
Train it on data separate from the generator's training split, otherwise adherence scores are optimistic.
ResNet1dClassifier
¶
Bases: Module
[B, C, T] -> [B, num_classes] logits; :meth:features gives the pooled embedding.
Source code in src/ecgen/evaluation/classifier.py
fit_classifier
¶
fit_classifier(x: ArrayLike, y: ArrayLike, multilabel: bool = True, epochs: int = 20, lr: float = 0.001, batch_size: int = 64, width: int = 64, device: Optional[str] = None, seed: int = 0) -> ResNet1dClassifier
Train :class:ResNet1dClassifier on x [N, C, T] and labels y
(multi-hot [N, K] with multilabel=True, else class indices [N]).
Source code in src/ecgen/evaluation/classifier.py
predict
¶
Probabilities: sigmoid (multi-label) or softmax (single-label).
Source code in src/ecgen/evaluation/classifier.py
label_metrics
¶
Macro AUROC over labels present with both values (multi-label), or accuracy + macro AUROC.
Source code in src/ecgen/evaluation/classifier.py
label_adherence
¶
label_adherence(model: Module, generated: ArrayLike, requested: ArrayLike, multilabel: bool = True) -> Dict[str, float]
Score generated ECGs against the labels they were generated for.
Source code in src/ecgen/evaluation/classifier.py
tstr
¶
tstr(train_x: ArrayLike, train_y: ArrayLike, test_x: ArrayLike, test_y: ArrayLike, multilabel: bool = True, **fit_kwargs) -> Dict[str, float]
Train on train_* (synthetic for TSTR, real for TRTR), test on real test_*.
Source code in src/ecgen/evaluation/classifier.py
ecgen.api¶
Public sampling API: ecgen.sample(checkpoint, n, ...) for any checkpoint
trained with ecgen train.
load_model
¶
Load a generative model from an ecgen train checkpoint.
The family is read from the checkpoint (ecgen_family); pass family
for checkpoints written before it was recorded. hf://<repo>/<path>
checkpoints are downloaded (see :func:ecgen.generate).
Source code in src/ecgen/api.py
sample
¶
sample(checkpoint: Union[PathLike, Any], n: int = 16, *, family: Optional[str] = None, cond: Optional[Mapping[str, Any]] = None, obs: Optional[Any] = None, obs_mask: Optional[Any] = None, guidance: Optional[float] = None, steps: Optional[int] = None, seed: Optional[int] = None, batch_size: int = 32, device: Optional[str] = None, derive_12: bool = False, output_dir: Optional[PathLike] = None, format: Optional[str] = 'npy', plot: int = 0, **sample_kwargs: Any) -> np.ndarray
Generate n ECGs from a checkpoint (or an already loaded model).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
checkpoint
|
Union[PathLike, Any]
|
|
required |
n
|
int
|
Number of ECGs. |
16
|
family
|
Optional[str]
|
Registry name, for checkpoints that do not record it. |
None
|
cond
|
Optional[Mapping[str, Any]]
|
Raw condition values (numeric fields in raw units; NaN = unknown;
strings for text fields). A value with a leading dimension of |
None
|
obs
|
Optional[Any]
|
Partially observed ECGs |
None
|
obs_mask
|
Optional[Any]
|
Masks of |
None
|
guidance
|
Optional[float]
|
Classifier-free guidance scale (conditional diffusion / flow / prior). |
None
|
steps
|
Optional[int]
|
Sampling steps (diffusion / flow). |
None
|
seed
|
Optional[int]
|
Seed for reproducible sampling. |
None
|
batch_size
|
int
|
ECGs generated per forward pass. |
32
|
device
|
Optional[str]
|
Default: CUDA if available. |
None
|
derive_12
|
bool
|
Complete 8 independent leads (I, II, V1–V6) to the standard 12. |
False
|
output_dir
|
Optional[PathLike]
|
Write the samples here ( |
None
|
plot
|
int
|
Render the first |
0
|
sample_kwargs
|
Any
|
Passed to the model's |
{}
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Source code in src/ecgen/api.py
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 | |
write_samples
¶
write_samples(samples: ndarray, output_dir: PathLike, lead_names: List[str], fs: int, format: Optional[str] = 'npy', scale: Any = None, cond: Optional[Mapping[str, Any]] = None, checkpoint: Any = None, plot: int = 0) -> List[Path]
Write [n, C, T] samples as npy / csv / wfdb (+ samples.json, plots).
Source code in src/ecgen/api.py
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 | |
evaluation.metrics.signal_quality¶
Signal quality metrics for ECG evaluation.
signal_to_noise_ratio
¶
Calculate signal-to-noise ratio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ecg
|
Tensor | ndarray
|
ECG signal |
required |
Returns:
| Type | Description |
|---|---|
float
|
SNR in dB |
Source code in evaluation/metrics/signal_quality.py
baseline_wander
¶
Measure baseline wander in ECG signal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ecg
|
Tensor | ndarray
|
ECG signal |
required |
sampling_rate
|
int
|
Sampling rate in Hz |
500
|
Returns:
| Type | Description |
|---|---|
float
|
Baseline wander metric |
Source code in evaluation/metrics/signal_quality.py
powerline_interference
¶
Measure 50/60 Hz powerline interference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ecg
|
Tensor | ndarray
|
ECG signal |
required |
sampling_rate
|
int
|
Sampling rate in Hz |
500
|
Returns:
| Type | Description |
|---|---|
float
|
Powerline interference metric |
Source code in evaluation/metrics/signal_quality.py
calculate_quality_metrics
¶
Calculate comprehensive signal quality metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ecg
|
Tensor | ndarray
|
ECG signal |
required |
sampling_rate
|
int
|
Sampling rate in Hz |
500
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary of quality metrics |
Source code in evaluation/metrics/signal_quality.py
evaluation.metrics.diversity¶
Diversity metrics for generated ECG samples.
pairwise_distance_diversity
¶
Calculate diversity using pairwise distances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
samples
|
Tensor | ndarray
|
Generated samples of shape (n_samples, ...) |
required |
metric
|
str
|
Distance metric ("euclidean", "cosine", etc.) |
'euclidean'
|
Returns:
| Type | Description |
|---|---|
float
|
Mean pairwise distance |
Source code in evaluation/metrics/diversity.py
intra_class_diversity
¶
Calculate diversity within each class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
samples
|
Tensor | ndarray
|
Generated samples |
required |
labels
|
ndarray
|
Class labels for each sample |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary of diversity per class |
Source code in evaluation/metrics/diversity.py
mode_coverage
¶
mode_coverage(samples: Tensor | ndarray, real_samples: Tensor | ndarray, n_clusters: int = 10) -> float
Estimate mode coverage using clustering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
samples
|
Tensor | ndarray
|
Generated samples |
required |
real_samples
|
Tensor | ndarray
|
Real samples |
required |
n_clusters
|
int
|
Number of clusters |
10
|
Returns:
| Type | Description |
|---|---|
float
|
Mode coverage score (0-1) |
Source code in evaluation/metrics/diversity.py
evaluation.metrics.fidelity¶
Fidelity metrics for generated ECG samples.
frechet_distance
¶
frechet_distance(mu1: ndarray, sigma1: ndarray, mu2: ndarray, sigma2: ndarray, eps: float = 1e-06) -> float
Calculate Fréchet Distance between two Gaussian distributions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mu1
|
ndarray
|
Mean of first distribution |
required |
sigma1
|
ndarray
|
Covariance of first distribution |
required |
mu2
|
ndarray
|
Mean of second distribution |
required |
sigma2
|
ndarray
|
Covariance of second distribution |
required |
eps
|
float
|
Small value for numerical stability |
1e-06
|
Returns:
| Type | Description |
|---|---|
float
|
Fréchet distance |
Source code in evaluation/metrics/fidelity.py
calculate_fid
¶
Calculate Fréchet Inception Distance (FID) between real and generated features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
real_features
|
Tensor | ndarray
|
Features from real samples |
required |
generated_features
|
Tensor | ndarray
|
Features from generated samples |
required |
Returns:
| Type | Description |
|---|---|
float
|
FID score |
Source code in evaluation/metrics/fidelity.py
reconstruction_error
¶
reconstruction_error(real: Tensor | ndarray, reconstructed: Tensor | ndarray, metric: str = 'mse') -> float
Calculate reconstruction error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
real
|
Tensor | ndarray
|
Real samples |
required |
reconstructed
|
Tensor | ndarray
|
Reconstructed samples |
required |
metric
|
str
|
Error metric ("mse", "mae", "rmse") |
'mse'
|
Returns:
| Type | Description |
|---|---|
float
|
Reconstruction error |
Source code in evaluation/metrics/fidelity.py
structural_similarity
¶
Calculate structural similarity between real and generated samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
real
|
Tensor | ndarray
|
Real samples |
required |
generated
|
Tensor | ndarray
|
Generated samples |
required |
Returns:
| Type | Description |
|---|---|
float
|
Structural similarity score |
Source code in evaluation/metrics/fidelity.py
evaluation.benchmark¶
Benchmarking utilities for model evaluation.
ModelBenchmark
¶
Benchmark model performance.
Source code in evaluation/benchmark.py
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 | |
measure_inference_time
¶
Measure inference time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_shape
|
tuple
|
Input tensor shape |
required |
n_runs
|
int
|
Number of runs for averaging |
100
|
warmup
|
int
|
Number of warmup runs |
10
|
Source code in evaluation/benchmark.py
measure_memory_usage
¶
Measure GPU memory usage.
Source code in evaluation/benchmark.py
count_parameters
¶
Count model parameters.
Source code in evaluation/benchmark.py
run_full_benchmark
¶
Run full benchmark suite.
Source code in evaluation/benchmark.py
print_results
¶
Print benchmark results.
Source code in evaluation/benchmark.py
evaluation.visualize¶
Evaluation visualization utilities.
plot_evaluation_results
¶
plot_evaluation_results(metrics: dict, save_path: str | Path = None, figsize: tuple = (12, 8)) -> plt.Figure
Plot evaluation results as bar charts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metrics
|
dict
|
Dictionary of metric names and values |
required |
save_path
|
str | Path
|
Optional path to save figure |
None
|
figsize
|
tuple
|
Figure size |
(12, 8)
|
Returns:
| Type | Description |
|---|---|
Figure
|
matplotlib Figure object |
Source code in evaluation/visualize.py
plot_comparison_matrix
¶
plot_comparison_matrix(models: list[str], metrics: dict[str, list[float]], save_path: str | Path = None, figsize: tuple = (12, 8)) -> plt.Figure
Plot comparison matrix of multiple models across metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
models
|
list[str]
|
List of model names |
required |
metrics
|
dict[str, list[float]]
|
Dictionary of metric names to lists of values (one per model) |
required |
save_path
|
str | Path
|
Optional path to save figure |
None
|
figsize
|
tuple
|
Figure size |
(12, 8)
|
Returns:
| Type | Description |
|---|---|
Figure
|
matplotlib Figure object |