PTB-XL, a large publicly available electrocardiography dataset: sample notebook

A worked notebook for PTB-XL, a large publicly available electrocardiography dataset, with 6 code cells and the output each one printed. On Scigantic it opens in a hosted JupyterLab with the dataset already mounted, so nothing is downloaded first.

Provider
Patrick Wagner, Nils Strodthoff, Ralf-Dieter Bousseljot, Wojciech Samek, and Tobias Schaeffter
License
PhysioNet Open Access
Stored at
Amazon S3, s3://physionet-open/ptb-xl (us-east-1)
Access
Free and public. No account with the data provider is needed.

The notebook

Start here. Click the grey cell below and press Shift+Enter. It reads one ECG from the archive and prints who it came from and what the cardiologist wrote. Then change ECG_ID to any number from 1 to 21837 and run it again (a few ids in that range do not exist).

import ast, os, warnings
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import wfdb

warnings.filterwarnings("ignore")
ECG_ID = 17

ROOT = Path(os.environ.get("SCIGANTIC_MOUNT_PATH", "/mnt/archive")) / "1.0.3"
Y = pd.read_csv(ROOT / "ptbxl_database.csv", index_col="ecg_id")
Y["scp_codes"] = Y["scp_codes"].apply(ast.literal_eval)

row = Y.loc[ECG_ID]
signal, info = wfdb.rdsamp(str(ROOT / row.filename_lr))
print(f"ECG {ECG_ID}: {signal.shape[0] / info['fs']:.0f} s at {info['fs']} Hz, leads {' '.join(info['sig_name'])}")
print(f"  patient {int(row.patient_id)}, age {row.age:.0f}, {'female' if row.sex == 1 else 'male'}, recorded {row.recording_date}")
print(f"  statements: {row.scp_codes}")
print(f"  report: {row.report}")

PTB-XL: 12-lead clinical ECGs with cardiologist labels

PTB-XL is a set of 10-second, 12-lead electrocardiograms collected at the Physikalisch-Technische Bundesanstalt (PTB), the national metrology institute of Germany, and released in 2020. Each record carries a written report and a set of coded statements. It is a widely used open benchmark for ECG classification.

The archive holds three versions (1.0.1, 1.0.2, 1.0.3) and a zip of each. This notebook uses 1.0.3. Inside it:

ages = Y.age
print(f"{len(Y):,} ECGs from {Y.patient_id.nunique():,} patients")
print(f"sex: {(Y.sex == 0).sum():,} male, {(Y.sex == 1).sum():,} female")
print(f"age: median {ages[ages < 300].median():.0f}, range {ages.min():.0f} to {ages[ages < 300].max():.0f}; "
      f"{(ages == 300).sum()} records have age 300, the code used for patients over 89")
print(f"recorded {Y.recording_date.min()[:10]} to {Y.recording_date.max()[:10]}")
print(f"checked by a human cardiologist: {Y.validated_by_human.mean():.0%} of records")
print()
print("first two record folders:", sorted(os.listdir(ROOT / "records100"))[:2], "of", len(os.listdir(ROOT / "records100")))

Output:

21,799 ECGs from 18,869 patients
sex: 11,354 male, 10,445 female
age: median 61, range 2 to 89; 293 records have age 300, the code used for patients over 89
recorded 1984-11-09 to 2001-06-11
checked by a human cardiologist: 74% of records

first two record folders: ['00000', '01000'] of 22

Labels

scp_codes is a dictionary from statement code to a likelihood (0 to 100; 0 means the statement was made without a stated likelihood). There are diagnostic statements (what is wrong), form statements (what a wave looks like) and rhythm statements. The diagnostic ones group into five superclasses, and most published benchmarks predict those. The cell below does the grouping the way the dataset's own example_physionet.py does.

scp = pd.read_csv(ROOT / "scp_statements.csv", index_col=0)
print(f"{len(scp)} statement codes: {int(scp.diagnostic.sum())} diagnostic, {int(scp.form.sum())} form, {int(scp.rhythm.sum())} rhythm (a code can be more than one kind)\n")

diagnostic = scp[scp.diagnostic == 1]
Y["superclass"] = Y.scp_codes.apply(lambda codes: sorted({diagnostic.loc[c, "diagnostic_class"] for c in codes if c in diagnostic.index}))

meaning = {"NORM": "normal ECG", "MI": "myocardial infarction", "STTC": "ST/T change",
           "CD": "conduction disturbance", "HYP": "hypertrophy"}
counts = Y.superclass.explode().value_counts()
for name, n in counts.items():
    print(f"  {name:5} {meaning[name]:24} {n:6,} records ({n / len(Y):.0%})")
print(f"\n  {(Y.superclass.str.len() > 1).sum():,} records are in more than one superclass, {(Y.superclass.str.len() == 0).sum():,} are in none")
print(f"  the diagnostic codes also group into {diagnostic.diagnostic_subclass.nunique()} finer subclasses (column diagnostic_subclass)")

Output:

71 statement codes: 44 diagnostic, 19 form, 12 rhythm (a code can be more than one kind)

  NORM  normal ECG                9,514 records (44%)
  MI    myocardial infarction     5,469 records (25%)
  STTC  ST/T change               5,235 records (24%)
  CD    conduction disturbance    4,898 records (22%)
  HYP   hypertrophy               2,649 records (12%)

  5,144 records are in more than one superclass, 411 are in none
  the diagnostic codes also group into 23 finer subclasses (column diagnostic_subclass)

A record can be in several superclasses at once (an old infarction and a conduction disturbance, for example), so this is a multi-label problem and the percentages add up to more than 100.

One ECG, twelve leads

The cell below draws the first four seconds of the 500 Hz version of a record that is labeled normal and nothing else, and has no signal-quality note.

noise_columns = ["baseline_drift", "static_noise", "burst_noise", "electrodes_problems"]
clean = Y[noise_columns].isna().all(axis=1)          # no signal-quality problem was noted
normal_ids = Y.index[(Y.superclass.apply(lambda s: s == ["NORM"])) & Y.validated_by_human & clean]
ecg_id = normal_ids[0]
sig, info = wfdb.rdsamp(str(ROOT / Y.loc[ecg_id, "filename_hr"]))
tt = np.arange(len(sig)) / info["fs"]

fig, axes = plt.subplots(6, 2, figsize=(10, 6), dpi=72, sharex=True)
for i, name in enumerate(info["sig_name"]):
    a = axes[i % 6, i // 6]
    a.plot(tt[: 4 * info["fs"]], sig[: 4 * info["fs"], i], lw=0.8, color="#111827")
    a.set_ylabel(name, rotation=0, labelpad=16, va="center"); a.set_yticks([])
    a.spines[["top", "right", "left"]].set_visible(False)
axes[-1, 0].set_xlabel("seconds"); axes[-1, 1].set_xlabel("seconds")
fig.suptitle(f"ECG {ecg_id}: {Y.loc[ecg_id, 'report']}", fontsize=10)
plt.tight_layout(); plt.show()
print(f"ECG {ecg_id}: {sig.shape[0]:,} samples x {sig.shape[1]} leads at {info['fs']} Hz, units {set(info['units'])}")

Output:

ECG 2: 5,000 samples x 12 leads at 500 Hz, units {'mV'}

What a label looks like in the signal

Left bundle branch block (code CLBBB) is a conduction disturbance: the electrical signal reaches the left ventricle late, by a slower route, so the QRS complex (the sharp spike of each beat) becomes wide, and in lead V1 it points down. That makes it a good first check that labels and waveforms line up.

The cell below takes 30 records labeled normal and 30 labeled CLBBB with likelihood 100, finds the heartbeats in each with NeuroKit2, lines the beats up on their R peak, and takes the median beat for each record.

import neurokit2 as nk

def median_beat(ecg_id, lead, before=0.25, after=0.45):
    """Median heartbeat of one record in one lead (500 Hz), aligned on R peaks found in lead II. Returns (beat, heart rate)."""
    sig, info = wfdb.rdsamp(str(ROOT / Y.loc[ecg_id, "filename_hr"]))
    fs = info["fs"]
    clean = nk.ecg_clean(sig[:, info["sig_name"].index("II")], sampling_rate=fs)
    peaks = nk.ecg_peaks(clean, sampling_rate=fs)[1]["ECG_R_Peaks"]
    a, b = int(before * fs), int(after * fs)
    x = sig[:, info["sig_name"].index(lead)]
    beats = [x[p - a : p + b] for p in peaks if p - a >= 0 and p + b <= len(x)]
    beat = np.median(beats, axis=0)
    return beat - np.median(beat[: int(0.05 * fs)]), 60 * fs / np.median(np.diff(peaks))

groups = {
    "normal": Y.index[(Y.superclass.apply(lambda s: s == ["NORM"])) & Y.validated_by_human][:30],
    "left bundle branch block": Y.index[Y.scp_codes.apply(lambda c: c.get("CLBBB") == 100.0) & Y.validated_by_human][:30],
}
tb = (np.arange(int(0.70 * 500)) - int(0.25 * 500)) / 500 * 1000   # milliseconds from the R peak

fig, axes = plt.subplots(2, 2, figsize=(10, 5.6), dpi=72, sharex=True, sharey="row")
for col, (name, ids) in enumerate(groups.items()):
    rates = []
    for row, lead in enumerate(["V1", "V6"]):
        beats = []
        for i in ids:
            beat, hr = median_beat(i, lead)
            beats.append(beat)
            if row == 0:
                rates.append(hr)
            axes[row, col].plot(tb, beat, lw=0.5, color="#9ca3af")
        axes[row, col].plot(tb, np.median(beats, axis=0), lw=2, color="#b91c1c" if col else "#1d4ed8")
        axes[row, col].set_title(f"{name}, lead {lead}", fontsize=10)
        axes[row, col].spines[["top", "right"]].set_visible(False)
    print(f"{name:26} {len(ids)} records, median heart rate {np.median(rates):.0f} beats/min")
axes[1, 0].set_xlabel("ms from R peak"); axes[1, 1].set_xlabel("ms from R peak")
axes[0, 0].set_ylabel("mV"); axes[1, 0].set_ylabel("mV")
plt.tight_layout(); plt.show()

Output:

normal                     30 records, median heart rate 67 beats/min
left bundle branch block   30 records, median heart rate 74 beats/min

Each grey line is one patient's median beat and the colored line is the median across the group. In the normal group the QRS is a narrow spike in both leads. In the left bundle branch block group it is wide: a deep, broad downward deflection in V1 and a broad upward wave in V6, each followed by a T wave pointing the other way. Individual patients vary far more than in the normal group.

The recommended train and test split

strat_fold assigns every record to one of ten folds. All records from the same patient are in the same fold, so a model cannot be tested on a patient it trained on. The authors recommend folds 1 to 8 for training, 9 for validation and 10 for testing.

by_fold = Y.groupby("strat_fold").agg(records=("patient_id", "size"), patients=("patient_id", "nunique"),
                                      human_validated=("validated_by_human", "mean"))
for name in counts.index:
    by_fold[name] = Y.superclass.apply(lambda s: name in s).groupby(Y.strat_fold).mean()
print(by_fold.round(2).to_string())

folds_per_patient = Y.groupby("patient_id").strat_fold.nunique()
print(f"\npatients whose records fall in more than one fold: {(folds_per_patient > 1).sum()}")

Output:

            records  patients  human_validated  NORM    MI  STTC    CD   HYP
strat_fold                                                                  
1              2175      1878             0.67  0.43  0.25  0.24  0.22  0.12
2              2181      1849             0.66  0.44  0.25  0.24  0.22  0.12
3              2192      1887             0.67  0.45  0.24  0.23  0.22  0.12
4              2174      1883             0.68  0.43  0.25  0.24  0.23  0.12
5              2174      1890             0.68  0.43  0.26  0.24  0.23  0.12
6              2173      1884             0.64  0.43  0.26  0.24  0.23  0.12
7              2176      1871             0.68  0.45  0.25  0.24  0.22  0.12
8              2173      1881             0.68  0.43  0.25  0.24  0.23  0.12
9              2183      1942             1.00  0.44  0.25  0.24  0.23  0.12
10             2198      1904             1.00  0.44  0.25  0.24  0.23  0.12

patients whose records fall in more than one fold: 0

The class proportions are close to equal across folds, which is what "stratified" means here, and the count of patients appearing in more than one fold is printed above. The human_validated column shows that folds 9 and 10 hold only records a cardiologist checked, so validation and test labels are the most reliable ones.

Going further

Source: Wagner P, Strodthoff N, Bousseljot R-D, Kreiseler D, Lunze FI, Samek W, Schaeffter T. PTB-XL, a large publicly available electrocardiography dataset. Scientific Data 7, 154 (2020). Distributed by PhysioNet under CC BY 4.0.

Run it

Open this notebook to run it, see the dataset page for the full description, or browse the full catalog.