---
title: 'EEG-MedRAG: Hypergraph RAG for EEG Data'
url: https://www.emergentmind.com/topics/eeg-medrag
type: topic
---

# EEG-MedRAG: Hypergraph RAG for EEG Data

EEG-MedRAG is a three-layer hypergraph-based retrieval-augmented generation (RAG) framework designed to address the efficient retrieval and semantic interpretation of large-scale, heterogeneous EEG (electroencephalography) data in clinical and neuroscience contexts. By unifying EEG domain knowledge, patient case histories, and extensive EEG repositories into a single traversable n-ary relational hypergraph, EEG-MedRAG enables semantically coherent, temporally informed retrieval and diagnostic reasoning. It further introduces a comprehensive clinical QA benchmark for evaluating generalization and role-specific reasoning across multiple neurological disorders and professional perspectives [2508.13735].

## 1. Hierarchical Hypergraph Structure

EEG-MedRAG operationalizes the complete EEG information space as a hypergraph $G = (V, E)$ with three disjoint but interconnected layers:

- **Knowledge Hypergraph (KGH):**  
  This layer encodes domain knowledge as entities ($V^K$) and hyperedges ($E^H$) representing n-ary clinical relations. Each clinical document $d \in \mathcal{D}$ is parsed into facts $F_n^d = \{ (e_i^H, V_i^H) \}$, associating a natural-language relation (hyperedge) $e_i^H$ with involved entity tuples $V_i^H$. The incidence matrix $H^K \in \{0,1\}^{|V^K| \times |E^H|}$ defines the bipartite structure (entities to hyperedges), and all nodes are embedded via a textual encoder $f_\text{text}: V \rightarrow \mathbb{R}^d$.  

- **Patient Cases Hypergraph (CGH):**  
  Patient cases are modeled as nodes ($V^C$) and multi-attribute hyperedges ($E^C$). Each case $p$ is represented as a tuple $(h_p, e_p)$ and embedded via $f_{CGH}(p) = f(h_p \oplus e_p) \in \mathbb{R}^d$. Augmented pseudo-cases are included through soft nearest-neighbor inference, creating $G'_{CGH} = G_{CGH} \cup \{ (\hat h_p, \hat e_p) \}$. Incidence matrices are defined analogously to KGH.

- **EEG Vector Database (EVD):**  
  Raw EEG segments $x \in \mathbb{R}^{C \times T}$ are transformed via channel-wise Piecewise Aggregate Approximation (PAA) with window size $n$:
  $$
  f_{EEG}(x) = \mathrm{concat}(\mathrm{PAA}(x_1, n), ..., \mathrm{PAA}(x_C, n)) \in \mathbb{R}^{C \cdot n}
  $$
  Each EEG segment is thus represented as a fixed-length embedding (nodes $V^E$), absent higher-order hyperedges.

The global hypergraph may be represented either as a high-rank incidence tensor $\mathcal{H} \in \{0,1\}^{|V| \times |V| \times ...}$ for n-ary relations or as layer-wise incidence matrices. This architecture supports efficient semantic, structural, and temporal traversals.

## 2. Semantic–Temporal Joint Retrieval

Given a new patient query, consisting of a raw EEG recording $x_q$ and metadata $m_q$ (age, symptoms, history), EEG-MedRAG performs multi-step context retrieval:

- **EEG-Level Retrieval:**  
  $f_{EEG}(x_q)$ is computed as above. For each stored EEG vector $x_i \in V^E$, the Dynamic Time Warping (DTW) distance is calculated:
  $$
  DTW_i = DTW(f_{EEG}(x_q), f_{EEG}(x_i))
  $$
  The top-$K$ segments minimizing DTW are retrieved:
  $$
  R_{EEG}(x_q) = \underset{x_i \in V^E}{\mathrm{argmin}}\, DTW_i
  $$

- **Hyperedge-Level (Knowledge) Retrieval:**  
  Query metadata is encoded as $u_q = f_\text{text}(m_q)$. For each knowledge hyperedge $e \in E^H$, with embedding $z_e = f_\text{text}(e)$, cosine similarity is computed:
  $$
  s_e = \cos(u_q, z_e) = \frac{u_q \cdot z_e}{\|u_q\|\|z_e\|}
  $$
  The top-$M$ hyperedges are selected:
  $$
  R_H(m_q) = \underset{e \in E^H}{\mathrm{argmax}}\, s_e
  $$

- **Entity-Level Expansion:**  
  For each retrieved hyperedge, incident entities are collected via $H^K$. Additional hyperedges may be fetched for enhanced context.

- **Subgraph Fusion:**  
  The three retrieval sets—EEG similarities ($C_{EEG}$), knowledge hyperedges ($C_H$), and entities ($C_E$)—are merged. The context subgraph $K^*$ is computed as:
  $$
  K^* = \mathrm{SubgraphClosure}(C_{EEG} \cup C_H \cup C_E)
  $$
  This union defines a connected, clinically meaningful evidence set by closure within one or two hops in the overall hypergraph.

This retrieval process tightly integrates low-level signal similarity, high-level semantic knowledge, and graph connectivity, supporting comprehensive evidence gathering.

## 3. Causal-Chain Diagnostic Reasoning

Context subgraph $K^*$ forms the prompt for a diagnostic large language model (LLM), e.g., GPT-4o-mini. Generation comprises:

- **Prompt Assembly:**  
  The prompt concatenates:
  - A “diagnostic instruction” template $p_{gen}$ (“Based on the following EEG segments, patient history, and medical facts, provide a diagnostic reasoning chain and final recommendation.”)
  - Retrieved EEG PAA vectors or their summaries
  - Textual descriptions of entities and hyperedges in $K^*$
  - The patient’s question $q$
 
- **Conditional Generation:**  
  The model samples the output:
  $$
  y^* \sim \pi(y \mid p_{gen}, K^*, q)
  $$
  where $\pi(\cdot)$ denotes the instruction-tuned LLM.

- **Supervised Fine-Tuning (optional):**  
  The approach is amenable to chain-of-thought or stepwise reasoning supervision via the loss:
  $$
  L(\theta) = -\sum_{t=1}^{T} \log P_\theta(y_t^{true} \mid y_{<t}, p_{gen}, K^*, q)
  $$
  where $\theta$ are LLM parameters.

The explicit fusion of retrieved semantic, structural, and time-series evidence enables interpretable, traceable causal-chain diagnostic outputs, in contrast to prior RAG methods lacking domain-specific graph structure or temporal alignment.

## 4. Cross-Disease, Cross-Role EEG Clinical QA Benchmark

EEG-MedRAG introduces the first large-scale, systematically curated EEG clinical QA dataset spanning both disorder diversity and professional roles:

| EEG Disorder Domain         | Clinical Roles                  | Example Data Sources       |
|----------------------------|---------------------------------|---------------------------|
| Epilepsy                   | Doctor, Patient, Nurse,         | CHB-MIT, OpenNeuro        |
| Depression                 | Researcher, Hospital Intern     | Various OpenNeuro sets    |
| Parkinson’s Disease        |                                 |                           |
| Alzheimer’s Disease        |                                 |                           |
| Sleep Deprivation          |                                 |                           |
| Psychiatric Disorders      |                                 |                           |
| mTBI                       |                                 |                           |

- **Coverage:**  
  - 7 domains: Epilepsy, Depression, Parkinson’s Disease, Alzheimer’s Disease, Sleep Deprivation, Psychiatric Disorders (e.g., psychosis), Mild Traumatic Brain Injury
  - 5 roles: Doctor, Patient, Researcher, Hospital Intern, Nurse

- **Data Construction:**  
  - EEG data sourced from CHB-MIT (23 epilepsy patients) and seven OpenNeuro datasets (over 200 subjects).  
  - Knowledge and QA pairs are derived from clinical guidelines, textbooks, interpretation protocols; totals ~2,500 QA pairs (7 domains × 5 roles × 50–100 questions each).
  - Each QA pair undergoes hierarchical retrieval-based automatic generation, followed by validation by two board-certified neurologists.

- **Annotation and Release:**  
  Annotated with salient EEG events and labeled factual relations, role-conditioned prompts, and human-validated ground truths; provided in standardized JSON format, split into train/dev/test without cross-subject overlap.

This dataset enables systematic benchmarking of disease-agnostic reasoning and role-awareness within the EEG context [2508.13735].

## 5. Empirical Performance and Ablation Analysis

EEG-MedRAG demonstrates quantifiable gains over established baselines in diagnostic accuracy and retrieval:

- **Metrics:**  
  - Exact Match (EM): binary correctness
  - Token-level F1: overlap between generated and reference responses

- **Baselines Compared:**  
  - NaiveGeneration (LLM without retrieval)
  - StandardRAG (chunk-based retrieval)
  - HyperGraphRAG (binary-relation graph RAG)
  - TimeRAG (time-series retrieval, no domain knowledge)

- **Key Results (GPT-4o-mini backbone):**  
  - F1:  
    - NaiveGeneration: 43.35  
    - StandardRAG: 45.44  
    - HyperGraphRAG: 48.93  
    - TimeRAG: 48.21  
    - **EEG-MedRAG: 53.16** (+7.72 vs. StandardRAG)
  - EM:  
    - StandardRAG: 26.19  
    - **EEG-MedRAG: 32.16** (+5.97)
  - Domain-specific improvements >10 F1 points (e.g., Alzheimer’s 53.18→68.06)
  - Similar performance improvements observed for Deepseek-r1 (+17.23 F1, +9.49 EM) and Gemini-2.5-flash (+5.35 F1).
  
- **Ablation Study:**  
  The three modules—Knowledge Retrieval (CL), Hyperedge Retrieval (IL), and EEG Fusion (EL)—each contribute substantially and roughly equally:
  - Full F1: 53.16
  - w/o CL: 49.32 (–3.84)
  - w/o IL: 48.52 (–4.64)
  - w/o EL: 48.26 (–4.90)

These findings indicate that all major components are essential for high performance, and the multi-layer hypergraph structure is critical for semantic, structural, and temporal integration.

## 6. Implementation and Public Resources

EEG-MedRAG is released as open-source software with all code and data available at https://github.com/yi9206413-boop/EEG-MedRAG under the MIT license (data: CC-BY 4.0).

- **Codebase Organization:**  
  - `/preprocess`: EEG PAA segmentation and embedding  
  - `/graph_build`: Hypergraph (KGH/CGH) construction  
  - `/retrieval`: DTW-based EEG and hyperedge retrieval  
  - `/generation`: Prompt assembly and LLM interfaces  
  - `/benchmark`: Dataset loaders and evaluation scripts

- **Dependencies:**  
  Python 3.8+, PyTorch, Transformers, numpy, scipy, dtw-python, networkx, scikit-learn

- **Workflow (Quick Start):**  
  1. Clone repository and install dependencies
  2. Download EEG data to `/data`
  3. Run EEG embedding script
  4. Build hypergraphs (KGH/CGH)
  5. Run retrieval and generation pipeline

This infrastructure provides a standardized and extensible platform for EEG-based, retrieval-augmented clinical reasoning research.

---

EEG-MedRAG’s principled integration of semantic knowledge, temporal dynamics, and clinical context within a hierarchical hypergraph framework advances the field of EEG interpretation and diagnostic QA, with robust empirical validation across multiple disorders and professional perspectives [2508.13735].

Source: https://www.emergentmind.com/topics/eeg-medrag