✨ Tutorial: Bonn EEG¢

This tutorial walks through a pyhctsa analysis of the Bonn EEG dataset, from raw recordings to a classifier. You will:

  1. download the raw EEG recordings and low-pass filter them,

  2. compute features for a few recordings with FeatureCalculator,

  3. load the full feature matrix (500 recordings Γ— 6406 features), computed in advance with pyhctsa 2.0.0, or compute it yourself,

  4. drop the features that cannot be used for this dataset,

  5. look at the recordings in a two-dimensional projection of the feature space,

  6. classify the five types of recording with a linear support vector machine.

Computing all 6406 features for all 500 recordings takes about 7.8 CPU-hours, so by default the notebook downloads the precomputed feature matrix (21 MB) instead. The rest of the notebook runs in a few minutes on a laptop.

SetupΒΆ

Besides pyhctsa, this tutorial uses matplotlib, seaborn and kagglehub:

pip install matplotlib seaborn kagglehub
[1]:
import hashlib
import os
import urllib.request
import warnings
from pathlib import Path

import kagglehub
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from scipy.signal import butter, filtfilt
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import MinMaxScaler
from sklearn.svm import LinearSVC

from pyhctsa import load_results, quality_summary
from pyhctsa.calculator import FeatureCalculator

# print warnings as 'Category: message', without the temporary file name Jupyter gives each cell
warnings.formatwarning = lambda message, category, *args, **kwargs: f"{category.__name__}: {message}\n"

⬇️ (1) The Bonn EEG datasetΒΆ

The Bonn EEG dataset (Andrzejak et al., 2001) contains 500 single-channel EEG segments, 100 in each of five sets, A to E. Each segment is 23.6 s long, sampled at 173.61 Hz (4097 samples). We use the copy on Kaggle, quands/eeg-dataset, which keeps each set in its own folder:

Set

Folder

Label

Recordings

A

Z

eyesOpen

healthy volunteers, eyes open (scalp EEG)

B

O

eyesClosed

healthy volunteers, eyes closed (scalp EEG)

C

N

hippocampus

epilepsy patients between seizures, hippocampal formation of the opposite hemisphere (intracranial)

D

F

epileptogenic

epilepsy patients between seizures, epileptogenic zone (intracranial)

E

S

seizure

epilepsy patients during seizures (intracranial)

Files for this tutorialΒΆ

Two files accompany this tutorial on figshare (doi:10.6084/m9.figshare.35152588.v1):

  • bonn_eeg_labels.csv has one row per recording, ts_1 to ts_500, with its set, folder, label and file name. Its order is the row order of the feature matrix.

  • bonn_eeg_pyhctsa_2.0.0.npz holds the full feature matrix computed with pyhctsa 2.0.0, saved with FeatureCalculator.save.

They are downloaded once into a cache directory, ~/.cache/pyhctsa/bonn_eeg (or bonn_eeg inside $PYHCTSA_DATA_DIR, if that environment variable is set), and each is checked against the size and SHA-256 digest below.

[2]:
# ---- Data files for this tutorial (figshare, doi:10.6084/m9.figshare.35152588.v1) ----
LABELS_URL = "https://ndownloader.figshare.com/files/72020404"
LABELS_FILE = "bonn_eeg_labels.csv"
LABELS_SIZE = 16_829  # bytes
LABELS_SHA256 = "cae4a443b5d0be521b49db1c72a3286b69aba6c3169c8312b607104b58148477"

FEATURES_URL = "https://ndownloader.figshare.com/files/72020407"
FEATURES_FILE = "bonn_eeg_pyhctsa_2.0.0.npz"
FEATURES_SIZE = 20_838_716  # bytes
FEATURES_SHA256 = "16cae224be220c282b893aa0b60e9721a0809bb18ab140d90c3f72fee1f869e2"

CACHE_DIR = Path(os.environ.get("PYHCTSA_DATA_DIR", "~/.cache/pyhctsa")).expanduser() / "bonn_eeg"
[3]:
def sha256_of(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(1 << 20), b""):
            h.update(block)
    return h.hexdigest()


def fetch_verified(url, filename, size, sha256):
    # Return the path of a verified copy of `filename` in CACHE_DIR, downloading it from `url` if needed.
    dest = CACHE_DIR / filename
    if dest.exists() and dest.stat().st_size == size and sha256_of(dest) == sha256:
        print(f"{filename}: verified copy found in the cache")
        return dest
    CACHE_DIR.mkdir(parents=True, exist_ok=True)
    tmp = dest.with_name(filename + ".part")
    print(f"{filename}: downloading ({size / 1e6:.2g} MB)")
    urllib.request.urlretrieve(url, tmp)
    got_size, got_sha256 = tmp.stat().st_size, sha256_of(tmp)
    if got_size != size or got_sha256 != sha256:
        tmp.unlink()
        raise OSError(f"{filename} downloaded from {url} is not the expected file: size {got_size} bytes "
                      f"(expected {size}), SHA-256 {got_sha256} (expected {sha256}).")
    tmp.replace(dest)
    print(f"{filename}: downloaded and verified")
    return dest

πŸ—³ (2) Load and filter the recordingsΒΆ

kagglehub downloads the raw recordings (one text file per recording) on its first call and reuses its copy afterwards:

[4]:
dataset_dir = Path(kagglehub.dataset_download("quands/eeg-dataset")) / "Dataset"
print(sorted(p.name for p in dataset_dir.iterdir()))
['F', 'N', 'O', 'S', 'Z']

The labels file names each recording (instance) and gives its set, folder, label and file. We load the recordings in its order, which is the row order of the precomputed feature matrix. Listing the folders with os.listdir would not give a reliable order: the order it returns depends on the file system, and differs between macOS and Linux, for example.

[5]:
labels = pd.read_csv(fetch_verified(LABELS_URL, LABELS_FILE, LABELS_SIZE, LABELS_SHA256))
labels
bonn_eeg_labels.csv: downloading (0.017 MB)
bonn_eeg_labels.csv: downloaded and verified
[5]:
instance bonn_set folder label file
0 ts_1 C N hippocampus N/N005.TXT
1 ts_2 C N hippocampus N/N011.TXT
2 ts_3 C N hippocampus N/N039.TXT
3 ts_4 C N hippocampus N/N038.TXT
4 ts_5 C N hippocampus N/N010.TXT
... ... ... ... ... ...
495 ts_496 B O eyesClosed O/O049.txt
496 ts_497 B O eyesClosed O/O100.txt
497 ts_498 B O eyesClosed O/O048.txt
498 ts_499 B O eyesClosed O/O060.txt
499 ts_500 B O eyesClosed O/O074.txt

500 rows Γ— 5 columns

[6]:
labels.groupby(["bonn_set", "folder", "label"]).size()
[6]:
bonn_set  folder  label
A         Z       eyesOpen         100
B         O       eyesClosed       100
C         N       hippocampus      100
D         F       epileptogenic    100
E         S       seizure          100
dtype: int64

Each recording is low-pass filtered at 40 Hz with a 4th-order Butterworth filter. filtfilt applies the filter forwards and then backwards, so that it does not shift the signal in time.

[7]:
fs = 173.61  # sampling rate (Hz)
b, a = butter(4, 40.0 / (0.5 * fs), btype="lowpass")  # 4th-order Butterworth low-pass filter, 40 Hz cutoff

X = np.vstack([filtfilt(b, a, np.loadtxt(dataset_dir / f)) for f in labels["file"]])  # one recording per row
y = labels["label"].to_numpy()
classes = list(labels.drop_duplicates("bonn_set").sort_values("bonn_set")["label"])  # sets A to E
print(X.shape, classes)
(500, 4097) ['eyesOpen', 'eyesClosed', 'hippocampus', 'epileptogenic', 'seizure']

The first recording of each set:

[8]:
palette = dict(zip(classes, sns.color_palette("colorblind", len(classes))))
t = np.arange(X.shape[1]) / fs
fig, axs = plt.subplots(len(classes), 1, sharex=True, sharey=True, figsize=(12, 9))
for ax, c in zip(axs, classes):
    i = np.flatnonzero(y == c)[0]
    ax.plot(t, X[i], color=palette[c], lw=0.5)
    ax.set_title(f"{c} ({labels['instance'][i]}, {labels['file'][i]})", loc="left", fontsize=10)
    ax.set_ylabel("Β΅V")
axs[-1].set_xlabel("time (s)")
axs[-1].set_xlim(t[0], t[-1])
plt.tight_layout()
../_images/usage_tutorial_bon_eeg_15_0.png

βš™οΈ (3) Compute features with pyhctsaΒΆ

FeatureCalculator() sets up the default feature set: 1091 feature functions, which together return 6406 features. extract takes one series, or several as the rows of a 2-D array (or as a list), and labels names the rows of the result. Here we compute all features for the first recording of sets A, C and E. Each takes about 40 s on one CPU core.

[9]:
calc = FeatureCalculator()
demo_rows = [np.flatnonzero(y == c)[0] for c in ["eyesOpen", "hippocampus", "seizure"]]
demo = calc.extract(X[demo_rows], labels=labels["instance"].iloc[demo_rows])
demo
[9]:
hrv_classic.pnnrel025 hrv_classic.pnnrel05 hrv_classic.pnnrel1 hrv_classic.pnnrel2 hrv_classic.pnnrel3 hrv_classic.lfhf hrv_classic.vlf hrv_classic.lf hrv_classic.hf hrv_classic.tri ... l1pwc_sweep_lambda_0_005_095.rmserrsu01 l1pwc_sweep_lambda_0_005_095.nsegsu005 l1pwc_sweep_lambda_0_005_095.nsegsu001 l1pwc_sweep_lambda_0_005_095.corrsegerr l1pwc_sweep_lambda_0_005_095.bestrmserrpseg l1pwc_sweep_lambda_0_005_095.bestlambda wavelet_var_chg_db3_2 wavelet_var_chg_db3_3 wavelet_var_chg_sym2_2 wavelet_var_chg_sym2_3
instance
ts_101 0.813965 0.626709 0.321533 0.035889 0.001709 0.620085 17.386202 18.212949 29.371691 3.821828 ... 0.20 0.15 0.30 0.981768 0.001060 0.35 0.0 0.0 0.0 0.0
ts_1 0.806396 0.616211 0.326660 0.047852 0.004639 1.438589 16.373641 38.574764 26.814297 3.030325 ... 0.25 0.15 0.35 0.945679 0.003645 0.65 0.0 0.0 0.0 1.0
ts_201 0.798828 0.667236 0.395996 0.087646 0.005859 0.017189 0.237623 1.397613 81.307337 5.179520 ... 0.35 0.40 0.55 0.996966 0.000281 0.05 0.0 0.0 0.0 0.0

3 rows Γ— 6406 columns

Every value is a float: a finite number, or NaN where a feature could not be computed. For each value, calc.quality records whether it is good or why it is NaN (see pyhctsa.quality), and calc.calc_time records how long each feature function took:

[10]:
print(quality_summary(calc.quality.to_numpy()))
print("computation time per recording (s):", calc.calc_time.sum(axis=1).round(1).to_dict())
{'good': 18992, 'NaN': 226}
computation time per recording (s): {'ts_101': 37.6, 'ts_1': 39.4, 'ts_201': 35.3}

πŸ“‚ (4) The full feature matrixΒΆ

Computing all features for all 500 recordings takes about 7.8 CPU-hours (about 50 s per recording), or 17 minutes on 32 cores with LocalDistributor. By default, this tutorial instead loads the same feature matrix, computed in advance with pyhctsa 2.0.0 from the filtered recordings in the order of bonn_eeg_labels.csv.

To compute it yourself, set COMPUTE_ALL_FEATURES = True below. LocalDistributor() then runs one worker per CPU core, and the result is saved to bonn_eeg_features.npz in the working directory (read it back with load_results).

[11]:
COMPUTE_ALL_FEATURES = False  # True: compute all features for all 500 recordings here (about 7.8 CPU-hours)

if COMPUTE_ALL_FEATURES:
    from pyhctsa.distribute import LocalDistributor
    dist = LocalDistributor()  # one worker per CPU core
    values = calc.extract(X, labels=labels["instance"], distributor=dist)
    dist.close()
    calc.save("bonn_eeg_features.npz", values)
    quality = calc.quality
else:
    results = load_results(fetch_verified(FEATURES_URL, FEATURES_FILE, FEATURES_SIZE, FEATURES_SHA256))
    values, quality = results.values, results.quality
    print({k: results.meta[k] for k in ["pyhctsa_version", "config_name", "n_feature_functions", "n_features"]})

assert list(values.index) == list(labels["instance"])
print(values.shape)
print(quality_summary(quality.to_numpy()))
bonn_eeg_pyhctsa_2.0.0.npz: downloading (21 MB)
bonn_eeg_pyhctsa_2.0.0.npz: downloaded and verified
{'pyhctsa_version': '2.0.0', 'config_name': 'feature_config.yaml', 'n_feature_functions': 1091, 'n_features': 6406}
(500, 6406)
{'good': 3162409, 'NaN': 40591}

The precomputed file also records the SHA-256 digest of the raw recordings it was computed from, taken over their file names and contents in the order of the labels file. Checking it confirms that our recordings, in our order, match the rows of the feature matrix:

[12]:
if not COMPUTE_ALL_FEATURES:
    h = hashlib.sha256()
    for f in labels["file"]:
        h.update(f.encode())
        h.update((dataset_dir / f).read_bytes())
    assert h.hexdigest() == results.meta["data_sha256"], "the raw recordings do not match the precomputed features"
    print("The raw recordings match the precomputed feature matrix.")
The raw recordings match the precomputed feature matrix.

The three recordings computed above are rows of this matrix too. Almost all of their values agree with the precomputed ones to a relative tolerance of 1e-6. The others come from a few feature functions whose results are sensitive to floating-point rounding, which can differ between computers (the precomputed matrix was computed on a Linux server, and the outputs shown here on a Mac). Most of these differences are tiny; the largest are for features that simulate chaotic dynamics (force_potential_dblwell_*).

[13]:
live, stored = demo.to_numpy(), values.loc[demo.index].to_numpy()
agree = np.isclose(live, stored, rtol=1e-6, atol=0, equal_nan=True)
print(f"{agree.mean():.2%} of the {agree.size} values agree")
print(sorted({c.split(".")[0] for c in demo.columns[~agree.all(axis=0)]}))
99.69% of the 19218 values agree
['embed_pca_1_10', 'force_potential_dblwell_1_0p2_0p1', 'force_potential_dblwell_3_0p01_0p1', 'gp_hyperparameters_covSEiso_covNoise_200_first', 'preproc_compare_poly1_raw', 'preproc_compare_resample_2_1_raw', 'state_space_n4sid_2']

🧹 (5) Clean the feature matrix¢

Some features cannot be computed for every recording (they have NaN values, and quality says why), and some take the same value for every recording. Neither kind is useful to the classifier, so we drop both:

[14]:
nan_cols = values.columns[values.isna().any(axis=0)]
features = values.drop(columns=nan_cols)
constant_cols = features.columns[features.var(axis=0) == 0]
features = features.drop(columns=constant_cols)
print(f"{values.shape[1]} features: dropped {len(nan_cols)} with NaN values and {len(constant_cols)} constant ones, "
      f"leaving {features.shape[1]}")
6406 features: dropped 212 with NaN values and 88 constant ones, leaving 6106

πŸ–₯ (6) VisualisationΒΆ

To see how the features separate the five types of recording, we rescale each feature to the range [0, 1] and project the recordings into two dimensions, with principal component analysis (PCA, linear) and with t-SNE (nonlinear):

[15]:
features_scaled = MinMaxScaler().fit_transform(features)
pca = PCA(n_components=2).fit(features_scaled)
pc = pca.transform(features_scaled)
tsne = TSNE(n_components=2, perplexity=30, random_state=42).fit_transform(features_scaled)

fig, axs = plt.subplots(1, 2, figsize=(14, 5.5))
sns.scatterplot(x=pc[:, 0], y=pc[:, 1], hue=y, hue_order=classes, palette=palette, s=14, linewidth=0, ax=axs[0])
axs[0].set_xlabel(f"PC1 ({100 * pca.explained_variance_ratio_[0]:.0f}% of variance)")
axs[0].set_ylabel(f"PC2 ({100 * pca.explained_variance_ratio_[1]:.0f}% of variance)")
axs[0].set_title("PCA")
sns.scatterplot(x=tsne[:, 0], y=tsne[:, 1], hue=y, hue_order=classes, palette=palette, s=14, linewidth=0,
                ax=axs[1], legend=False)
axs[1].set_xlabel("t-SNE 1")
axs[1].set_ylabel("t-SNE 2")
axs[1].set_title("t-SNE")
plt.tight_layout()
../_images/usage_tutorial_bon_eeg_29_0.png

🎯 (7) Classification¢

Finally, we classify the 500 recordings into the five sets with a linear support vector machine (LinearSVC), using stratified 10-fold cross-validation. In each fold, the min-max scaling is fitted to the training recordings only, so nothing about the test recordings is used in training. Each test fold holds 10 recordings from each set, so accuracy here equals balanced accuracy.

[16]:
Xf = features.to_numpy()
skf = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)
fold_accuracy = []
predicted = np.empty_like(y)
for train, test in skf.split(Xf, y):
    scaler = MinMaxScaler().fit(Xf[train])
    svm = LinearSVC(max_iter=10_000).fit(scaler.transform(Xf[train]), y[train])
    predicted[test] = svm.predict(scaler.transform(Xf[test]))
    fold_accuracy.append(np.mean(predicted[test] == y[test]))
print("accuracy in each fold:", ", ".join(f"{acc:.2f}" for acc in fold_accuracy))
print(f"mean accuracy (5 classes, 10 folds): {100 * np.mean(fold_accuracy):.1f}%")
accuracy in each fold: 0.98, 0.96, 0.98, 0.94, 0.96, 0.88, 0.98, 0.94, 0.98, 0.94
mean accuracy (5 classes, 10 folds): 95.4%

The predictions for the test recordings of all ten folds show which sets are confused with each other (rows: true set; columns: predicted set):

[17]:
pd.crosstab(pd.Series(y, name="true"), pd.Series(predicted, name="predicted")).loc[classes, classes]
[17]:
predicted eyesOpen eyesClosed hippocampus epileptogenic seizure
true
eyesOpen 99 1 0 0 0
eyesClosed 5 94 0 0 1
hippocampus 1 0 94 5 0
epileptogenic 1 0 8 91 0
seizure 0 0 0 1 99