Skip to content

QMOS-Lab/qsvm-eeg

Repository files navigation

QSVM-EEG

Quantum Support Vector Machine for EEG-based BIS Index Prediction.

Uses quantum kernel estimation (QKE) to compute fidelity-based kernel matrices for Support Vector Regression, predicting Bispectral Index (BIS) values from EEG features during general anesthesia.

Project Structure

qsvm-eeg/
├── configs/
│   ├── default.yaml            # Full pipeline config (both models, all patients)
│   ├── svr_qke_48.yaml         # Quantum kernel only, patient 48
│   ├── svr_qke_411.yaml        # Quantum kernel only, patient 411
│   ├── svr_rbf.yaml            # Classical RBF only
│   ├── svr_rbf_48.yaml         # Classical RBF only, patient 48
│   └── svr_rbf_411.yaml        # Classical RBF only, patient 411
│
├── data/
│   ├── raw/                    # Immutable inputs (patient{id}_eeg.csv, patient{id}_bis.csv)
│   ├── processed/              # Cached feature arrays (.pkl)
│   └── models/                 # Saved model artifacts (.pkl)
│
├── reports/
│   ├── figures/                # Generated plots (timeseries, correlation, batch preview)
│   └── logs/                   # Per-run log files
│
├── src/qsvm_eeg/
│   ├── __init__.py
│   ├── data.py                 # Data loading, trimming, sliding window, caching
│   ├── features.py             # EEG feature extraction (DE, spikes, PE per band)
│   ├── quantum_kernel.py       # Fixed and trainable quantum kernel circuits
│   ├── metrics.py              # KTA, expressibility, Haar KL divergence, KTA optimization
│   ├── plotter.py              # Publication-ready plotting utilities
│   │
│   └── models/
│       ├── __init__.py
│       ├── base.py             # Abstract base class (train/predict/save)
│       ├── svr_rbf.py          # Classical SVR with RBF kernel
│       ├── svr_qkernel.py      # Quantum kernel SVR (precomputed kernel)
│       └── registry.py         # Model factory
│
├── main.py                     # Experiment runner (CLI)
├── inference.py                # Inference on saved models (CLI)
├── pyproject.toml
└── README.md

Prerequisites

  • Python >= 3.12
  • uv package manager
  • CUDA toolkit (optional, for lightning.gpu backend)

Installation

uv sync

For GPU-accelerated quantum simulation on Linux:

uv sync --extra gpu

Data Format

Place raw CSV files in data/raw/:

data/raw/patient48_eeg.csv    # Column: EEG (128 Hz)
data/raw/patient48_bis.csv    # Column: BIS (1 Hz)

BIS values are the Bispectral Index (0-100 scale) used as regression targets. EEG signals are sampled at 128 Hz and segmented into sliding windows.

Features

Each EEG window (default 56 seconds) produces 11 features:

Index Feature Description
0-4 DE^2 (delta, theta, alpha, beta, gamma) Squared differential entropy per frequency band
5-9 Spikes (delta, theta, alpha, beta, gamma) Count of points exceeding 3 std from mean
10 PE (delta) Permutation entropy of the delta band

Usage

Training

Run a full experiment (train + evaluate + log to MLflow):

uv run main.py --config configs/default.yaml

Run quantum kernel only on patient 48 with 1000 samples:

uv run main.py --config configs/svr_qke_48.yaml --samples 1000

Override which models to run:

uv run main.py --models svr_rbf svr_qkernel

Inference

Run predictions with a saved model:

uv run inference.py \
  --model-path data/models/model.pkl \
  --model-type svr_qkernel \
  --config configs/default.yaml \
  --patients 411 \
  --save-plots reports/figures

Configuration

All parameters are set via YAML config files. Key settings:

experiment_name: "QSVM_EEG_Comparison"
random_state: 42
patients: ["48", "411"]

# Signal processing
fs: 128                    # EEG sampling rate (Hz)
advance_steps: 60          # BIS prediction horizon (seconds ahead)
window_sec: 56.0           # Sliding window length (seconds)
step_sec: 1.0              # Window step size (seconds)

# Quantum backend
backend: "lightning.gpu"   # or "lightning.qubit", "default.qubit"
batch_size: null           # QNode batch size (null = auto)
jobs: -1                   # Parallel workers (-1 = all cores)

# Expressibility analysis (Sim et al. 2019)
n_haar_samples: 5000
n_haar_bins: 75

# Kernel Target Alignment training
kta_training:
  enabled: false           # Set true to optimize kernel parameters
  n_layers: 6             # Trainable ansatz layers (H-RZ-RY-CRZ per layer)
  n_steps: 500            # Max optimization steps
  batch_size: 8           # Samples per gradient step
  lr: 0.2                 # Adam optimizer learning rate
  patience: 50            # Early stopping patience

# Model hyperparameter grids
models:
  svr_rbf:
    enabled: true
    param_grid:
      C: [0.1, 1, 10, 50, 100, 500, 1000]
      epsilon: [0.1, 0.5, 1.0, 2.0, 4.0]
      gamma: ["scale", "auto"]

  svr_qkernel:
    enabled: true
    param_grid:
      C: [0.1, 1, 10, 50, 100, 500, 1000]
      epsilon: [0.1, 0.5, 1.0, 2.0, 4.0]

Quantum Kernel

Fixed kernel (default)

Uses PennyLane AngleEmbedding to encode scaled features (MinMaxScaler to [0, pi]) as rotation angles, one qubit per feature. The kernel value between two samples is the fidelity of their quantum states:

K(x1, x2) = |<0| U_adj(x2) U(x1) |0>|^2

where U(x) applies AngleEmbedding(x) to the qubits.

Trainable kernel (KTA-optimized)

When kta_training.enabled: true, a parameterized data re-uploading ansatz replaces the fixed embedding. Each layer applies:

H -> RZ(data) -> RY(trainable) -> CRZ(entangling)

Parameters are optimized to maximize Kernel-Target Alignment (Cristianini et al. 2001) via gradient descent on mini-batches before computing the full kernel matrix for SVR.

Analysis Metrics

Each quantum kernel run logs:

  • KTA score: Kernel-Target Alignment between kernel matrix and ideal regression target (higher = kernel better captures label structure)
  • Haar KL divergence: KL divergence between circuit fidelity distribution and Haar measure (expressibility metric, Sim et al. 2019)
  • Kernel fidelities: Off-diagonal kernel matrix entries exported for distribution analysis

Experiment Tracking

All runs are tracked with MLflow. Artifacts are stored under the project root in mlruns/.

View results:

uv run mlflow ui

Logged per run: hyperparameters, metrics (MSE, RMSE, R2, Pearson r, 95% CI), training time, inference time, figures (timeseries, correlation, batch preview), Haar expressibility plot, kernel fidelities, and KTA parameters (if trained).

References

  • Havlicek et al. (2018). Supervised learning with quantum-enhanced feature spaces. Nature.
  • Cristianini et al. (2001). On kernel-target alignment. NeurIPS.
  • Sim et al. (2019). Expressibility and entangling capability of parameterized quantum circuits. Advanced Quantum Technologies.
  • Zhou et al. (2023). Quantum kernel estimation-based quantum support vector regression. QIP.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages