OSCR

Evaluating EEG-to-text models through noise-based performance analysis

Code ↔ Paper

5 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 5 matches
  1. [1] § Materials and methods › EEG-to-text decoding evaluation › EEG-to-text decoding ↔ model_sentiment.py, lines 170–209 · score 0.67 · cross entropy loss, transformer encoder, heads, decoder, layered, module
  2. [2] § Materials and methods › EEG-to-text decoding evaluation › EEG-to-text decoding ↔ model_sentiment.py, lines 170–209 · score 0.62 · cross entropy loss, transformer encoder, heads, layer, pretrained, modeling
  3. [3] § Materials and methods › EEG-to-text decoding evaluation › EEG-to-text decoding ↔ train_decoding.py, lines 20–124 · score 0.56 · cross entropy loss, language modeling, weights, decoding
  4. [4] § Materials and methods › EEG-to-text decoding evaluation › EEG-to-text decoding ↔ eval_sentiment.py, lines 306–370 · score 0.52 · cross entropy loss, decoder, encoder, layered, sequences, embeddings
  5. [5] § Materials and methods › EEG-to-text decoding evaluation › Evaluation ↔ eval_decoding.py, lines 77–115 · score 0.50 · repetition penalty, beam, sequences

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 249 lines · 12 KB · no license · 2 matches

  1. import torch.nn as nn
  2. import torch.nn.functional as F
  3. import torch.utils.data
  4. from transformers import BartTokenizer, BartForConditionalGeneration, BartConfig, BertForSequenceClassification
  5. import math
  6. import numpy as np
  7. from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
  8. """MLP baseline using sentence level eeg"""
  9. # using sent level EEG, MLP baseline for sentiment
  10. class BaselineMLPSentence(nn.Module):
  11. def __init__(self, input_dim = 840, hidden_dim = 128, output_dim = 3):
  12. super(BaselineMLPSentence, self).__init__()
  13. self.fc1 = nn.Linear(input_dim, hidden_dim)
  14. self.relu1 = nn.ReLU()
  15. self.fc2 = nn.Linear(hidden_dim, hidden_dim)
  16. self.relu2 = nn.ReLU()
  17. self.fc3 = nn.Linear(hidden_dim, output_dim) # positive, negative, neutral
  18. self.dropout = nn.Dropout(0.25)
  19. def forward(self, x):
  20. out = self.fc1(x)
  21. out = self.relu1(out)
  22. out = self.fc2(out)
  23. out = self.relu2(out)
  24. out = self.dropout(out)
  25. out = self.fc3(out)
  26. return out
  27. """bidirectional LSTM baseline using word level eeg"""
  28. class BaselineLSTM(nn.Module):
  29. def __init__(self, input_dim = 840, hidden_dim = 256, output_dim = 3, num_layers = 1):
  30. super(BaselineLSTM, self).__init__()
  31. self.hidden_dim = hidden_dim
  32. self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers = 1, batch_first = True, bidirectional = True)
  33. self.hidden2sentiment = nn.Linear(hidden_dim*2, output_dim)
  34. def forward(self, x_packed):
  35. # input: (N,seq_len,input_dim)
  36. # print(x_packed.data.size())
  37. lstm_out, _ = self.lstm(x_packed)
  38. last_hidden_state = pad_packed_sequence(lstm_out, batch_first = True)[0][:,-1,:]
  39. # print(last_hidden_state.size())
  40. out = self.hidden2sentiment(last_hidden_state)
  41. return out
  42. """ Bert Baseline: Finetuning from a pretrained language model Bert"""
  43. class NaiveFineTunePretrainedBert(nn.Module):
  44. def __init__(self, input_dim = 840, hidden_dim = 768, output_dim = 3, pretrained_checkpoint = None):
  45. super(NaiveFineTunePretrainedBert, self).__init__()
  46. # mapping hidden states dimensioin
  47. self.fc1 = nn.Linear(input_dim, hidden_dim)
  48. self.pretrained_Bert = BertForSequenceClassification.from_pretrained('bert-base-cased',num_labels=3)
  49. if pretrained_checkpoint is not None:
  50. self.pretrained_Bert.load_state_dict(torch.load(pretrained_checkpoint))
  51. def forward(self, input_embeddings_batch, input_masks_batch, labels):
  52. embedding = F.relu(self.fc1(input_embeddings_batch))
  53. out = self.pretrained_Bert(inputs_embeds = embedding, attention_mask = input_masks_batch, labels = labels, return_dict = True)
  54. return out
  55. """ Finetuning from a pretrained language model BART, two step training"""
  56. class FineTunePretrainedTwoStep(nn.Module):
  57. def __init__(self, pretrained_layers, in_feature = 840, d_model = 1024, additional_encoder_nhead=8, additional_encoder_dim_feedforward = 2048):
  58. super(FineTunePretrainedTwoStep, self).__init__()
  59. self.pretrained_layers = pretrained_layers
  60. # additional transformer encoder, following BART paper about
  61. self.additional_encoder_layer = nn.TransformerEncoderLayer(d_model=in_feature, nhead=additional_encoder_nhead, dim_feedforward = additional_encoder_dim_feedforward, batch_first=True)
  62. self.additional_encoder = nn.TransformerEncoder(self.additional_encoder_layer, num_layers=6)
  63. # NOTE: add positional embedding?
  64. # print('[INFO]adding positional embedding')
  65. # self.positional_embedding = PositionalEncoding(in_feature)
  66. self.fc1 = nn.Linear(in_feature, d_model)
  67. def forward(self, input_embeddings_batch, input_masks_batch, input_masks_invert, labels):
  68. """input_embeddings_batch: batch_size*Seq_len*840"""
  69. """input_mask: 1 is not masked, 0 is masked"""
  70. """input_masks_invert: 1 is masked, 0 is not masked"""
  71. """labels: sentitment labels 0,1,2"""
  72. # NOTE: add positional embedding?
  73. # input_embeddings_batch = self.positional_embedding(input_embeddings_batch)
  74. # use src_key_padding_masks
  75. encoded_embedding = self.additional_encoder(input_embeddings_batch, src_key_padding_mask = input_masks_invert)
  76. # encoded_embedding = self.additional_encoder(input_embeddings_batch)
  77. encoded_embedding = F.relu(self.fc1(encoded_embedding))
  78. out = self.pretrained_layers(inputs_embeds = encoded_embedding, attention_mask = input_masks_batch, return_dict = True, labels = labels)
  79. return out
  80. """ Zero-shot sentiment discovery using a finetuned generation model and a sentiment model pretrained on text """
  81. class ZeroShotSentimentDiscovery(nn.Module):
  82. def __init__(self, brain2text_translator, sentiment_classifier, translation_tokenizer, sentiment_tokenizer, device = 'cpu'):
  83. # only for inference
  84. super(ZeroShotSentimentDiscovery, self).__init__()
  85. self.brain2text_translator = brain2text_translator
  86. self.sentiment_classifier = sentiment_classifier
  87. self.translation_tokenizer = translation_tokenizer
  88. self.sentiment_tokenizer = sentiment_tokenizer
  89. self.device = device
  90. def forward(self, input_embeddings_batch, input_masks_batch, input_masks_invert, target_ids_batch_converted, sentiment_labels):
  91. """input_embeddings_batch: batch_size*Seq_len*840"""
  92. """input_mask: 1 is not masked, 0 is masked"""
  93. """input_masks_invert: 1 is masked, 0 is not masked"""
  94. """labels: sentitment labels 0,1,2"""
  95. def logits2PredString(logits):
  96. probs = logits[0].softmax(dim = 1)
  97. # print('probs size:', probs.size())
  98. values, predictions = probs.topk(1)
  99. # print('predictions before squeeze:',predictions.size())
  100. predictions = torch.squeeze(predictions)
  101. predict_string = self.translation_tokenizer.decode(predictions)
  102. return predict_string
  103. # only works on batch is one
  104. assert input_embeddings_batch.size()[0] == 1
  105. seq2seqLMoutput = self.brain2text_translator(input_embeddings_batch, input_masks_batch, input_masks_invert, target_ids_batch_converted)
  106. predict_string = logits2PredString(seq2seqLMoutput.logits)
  107. predict_string = predict_string.split('</s></s>')[0]
  108. predict_string = predict_string.replace('<s>','')
  109. print('predict string:', predict_string)
  110. re_tokenized = self.sentiment_tokenizer(predict_string, return_tensors='pt', return_attention_mask = True)
  111. input_ids = re_tokenized['input_ids'].to(self.device) # batch = 1
  112. attn_mask = re_tokenized['attention_mask'].to(self.device) # batch = 1
  113. out = self.sentiment_classifier(input_ids = input_ids, attention_mask = attn_mask, return_dict = True, labels = sentiment_labels)
  114. return out
  115. """ Miscellaneous: jointly learn generation and classification (not working well) """
  116. class BartClassificationHead(nn.Module):
  117. # from transformers: https://huggingface.co/transformers/_modules/transformers/models/bart/modeling_bart.html
  118. """Head for sentence-level classification tasks."""
  119. def __init__(
  120. self,
  121. input_dim: int,
  122. inner_dim: int,
  123. num_classes: int,
  124. pooler_dropout: float,
  125. ):
  126. super().__init__()
  127. self.dense = nn.Linear(input_dim, inner_dim)
  128. self.dropout = nn.Dropout(p=pooler_dropout)
  129. self.out_proj = nn.Linear(inner_dim, num_classes)
  130. def forward(self, hidden_states: torch.Tensor):
  131. hidden_states = self.dropout(hidden_states)
  132. hidden_states = self.dense(hidden_states)
  133. hidden_states = torch.tanh(hidden_states)
  134. hidden_states = self.dropout(hidden_states)
  135. hidden_states = self.out_proj(hidden_states)
  136. return hidden_states
  137. class JointBrainTranslatorSentimentClassifier(nn.Module):
  138. def __init__(self, pretrained_layers, in_feature = 840, d_model = 1024, additional_encoder_nhead=8, additional_encoder_dim_feedforward = 2048, num_labels = 3):
  139. super(JointBrainTranslatorSentimentClassifier, self).__init__()
  140. self.pretrained_generator = pretrained_layers
  141. # additional transformer encoder, following BART paper about
  142. self.additional_encoder_layer = nn.TransformerEncoderLayer(d_model=in_feature, nhead=additional_encoder_nhead, dim_feedforward = additional_encoder_dim_feedforward, batch_first=True)
  143. self.additional_encoder = nn.TransformerEncoder(self.additional_encoder_layer, num_layers=6)
  144. self.fc1 = nn.Linear(in_feature, d_model)
  145. self.num_labels = num_labels
  146. self.pooler = Pooler(d_model)
  147. self.classifier = BartClassificationHead(input_dim = d_model, inner_dim = d_model, num_classes = num_labels, pooler_dropout = pretrained_layers.config.classifier_dropout)
  148. def forward(self, input_embeddings_batch, input_masks_batch, input_masks_invert, target_ids_batch_converted, sentiment_labels):
  149. """input_embeddings_batch: batch_size*Seq_len*840"""
  150. """input_mask: 1 is not masked, 0 is masked"""
  151. """input_masks_invert: 1 is masked, 0 is not masked"""
  152. # NOTE: add positional embedding?
  153. # input_embeddings_batch = self.positional_embedding(input_embeddings_batch)
  154. # use src_key_padding_masks
  155. encoded_embedding = self.additional_encoder(input_embeddings_batch, src_key_padding_mask = input_masks_invert)
  156. # encoded_embedding = self.additional_encoder(input_embeddings_batch)
  157. encoded_embedding = F.relu(self.fc1(encoded_embedding))
  158. LMoutput = self.pretrained_generator(inputs_embeds = encoded_embedding, attention_mask = input_masks_batch, return_dict = True, labels = target_ids_batch_converted, output_hidden_states = True)
  159. hidden_states = LMoutput.decoder_hidden_states # N, seq_len, hidden_dim
  160. # print('hidden states len:', len(hidden_states))
  161. last_hidden_states = hidden_states[-1]
  162. # print('last hidden states size:', last_hidden_states.size())
  163. sentence_representation = self.pooler(last_hidden_states)
  164. classification_logits = self.classifier(sentence_representation)
  165. loss_fct = nn.CrossEntropyLoss()
  166. classification_loss = loss_fct(classification_logits.view(-1, self.num_labels), sentiment_labels.view(-1))
  167. classification_output = {'loss':classification_loss,'logits':classification_logits}
  168. # print('successful one forward!!!!')
  169. return LMoutput, classification_output
  170. """ helper modules """
  171. # modified from BertPooler
  172. class Pooler(nn.Module):
  173. def __init__(self, hidden_size):
  174. super().__init__()
  175. self.dense = nn.Linear(hidden_size, hidden_size)
  176. self.activation = nn.Tanh()
  177. def forward(self, hidden_states):
  178. # We "pool" the model by simply taking the hidden state corresponding
  179. # to the first token.
  180. first_token_tensor = hidden_states[:, 0]
  181. pooled_output = self.dense(first_token_tensor)
  182. pooled_output = self.activation(pooled_output)
  183. return pooled_output
  184. # from https://pytorch.org/tutorials/beginner/transformer_tutorial.html
  185. class PositionalEncoding(nn.Module):
  186. def __init__(self, d_model, dropout=0.1, max_len=5000):
  187. super(PositionalEncoding, self).__init__()
  188. self.dropout = nn.Dropout(p=dropout)
  189. pe = torch.zeros(max_len, d_model)
  190. position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
  191. div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
  192. pe[:, 0::2] = torch.sin(position * div_term)
  193. pe[:, 1::2] = torch.cos(position * div_term)
  194. pe = pe.unsqueeze(0).transpose(0, 1)
  195. self.register_buffer('pe', pe)
  196. def forward(self, x):
  197. # print('[DEBUG] input size:', x.size())
  198. # print('[DEBUG] positional embedding size:', self.pe.size())
  199. x = x + self.pe[:x.size(0), :]
  200. # print('[DEBUG] output x with pe size:', x.size())
  201. return self.dropout(x)

model_sentiment.py at commit 00a50d0, no license · at the source

Overview

Authors: Hyejeong Jo1, Yiqian Yang2, Juhyeok Han1, Yiqun Duan3, Hui Xiong2, Won Hee Lee1
ORCID iDs: Won Hee Lee
  1. Department of Software Convergence, Kyung Hee University, Yongin-si, 17104 Republic of Korea
  2. HKUST(GZ), Guangzhou, 511453 People’s Republic of China
  3. GrapheneX-UTS HAI Centre, Australian Artificial Intelligence Institute, Faculty of Engineering and Information Technology, University of Technology Sydney, Sydney, 2007 Australia
Journal: n/a, volume 16, issue 1, article 350
Dates: received 4 October 2024; accepted 18 November 2025; published online 1 December 2025
Type: Research article · Language: English
License: none stated
Identifiers: DOI 10.1038/s41598-025-29587-x · PMCID PMC12770527 · OpenAlex W4416879689
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: EEG (modality), human (organism), methods / tools (subfield)
Methods: Smoothing, state filtering, decompositions, Spectral & time-frequency, Machine learning, Physiology & signal measures
Keywords: Neuroscience, Biomedical engineering
MeSH: Brain-Computer Interfaces*, Electroencephalography*, Brain, Humans, Machine Learning, Signal Processing, Computer-Assisted, Signal-To-Noise Ratio (* major topic)
Topic: EEG and Brain-Computer Interfaces (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Funding: Korea Creative Content Agency (RS-2023-00226263); Institute for Information and Communications Technology Promotion (RS-2024-00509257)
Citations: cited by 1 paper (Europe PMC); 25 references in the paper

Abstract

The abstract is not reproduced here: the paper's license (none stated) does not allow it. Read it in the paper, at the publisher or on Europe PMC.

Repository

Its files are read in the Code ↔ Paper reader above, with 5 matches between paragraphs and lines of code.

khu-aims/EEG-To-Text

License: none: the authors keep all their rights
State: the link answers, verified on 26 September 2026
Evidence: files inventoried
Commit: 00a50d002d24ef999609fb3e9e344a8b3ba42066, 26 November 2025
Languages: Python (14), Shell (11)
Size: 35 files, 25 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, environment (environment.yml)
Not found: license file, CITATION.cff, tests, continuous integration, documentation
Tools: NumPy (12 files), PyTorch (9 files), Hugging Face Transformers (9 files), Matplotlib (7 files), h5py (2 files), scikit-learn (1 file), SciPy (1 file)
Availability: 1 check, the latest on 26 September 2026: the link answers
  • 26 September 2026: the link answers
26 files

Code availability statement

The paper has a code availability statement. Its license (none stated) does not allow reproducing it here; in short, from what the harvester recognized in it:

Read it in the paper: doi.org/10.1038/s41598-025-29587-x.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 25 scripts, each with its path and the digest of its content;
  • 5 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data availability statement

The paper has a data availability statement. Its license (none stated) does not allow reproducing it here; in short, from what the harvester recognized in it:

  • it says that the data are available on request

Read it in the paper: doi.org/10.1038/s41598-025-29587-x.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 27 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 6 authors, 2 keywords, 7 MeSH terms, 2 funders, 10 references.

Cite

This paper

Jo, H., Yang, Y., Han, J., Duan, Y., Xiong, H., & Lee, W. H. (2025). Evaluating EEG-to-text models through noise-based performance analysis. Scientific Reports, 16(1), 350. https://doi.org/10.1038/s41598-025-29587-x

BibTeX

@article{jo2025evaluating,
author = {Jo, Hyejeong and Yang, Yiqian and Han, Juhyeok and Duan, Yiqun and Xiong, Hui and Lee, Won Hee},
title = {{Evaluating EEG-to-text models through noise-based performance analysis}},
journal = {Scientific Reports},
year = {2025},
volume = {16},
number = {1},
pages = {350},
publisher = {Nature Publishing Group},
issn = {2045-2322},
doi = {10.1038/s41598-025-29587-x},
url = {https://doi.org/10.1038/s41598-025-29587-x},
pmcid = {PMC12770527}
}

RIS

TY - JOUR
AU - Jo, Hyejeong
AU - Yang, Yiqian
AU - Han, Juhyeok
AU - Duan, Yiqun
AU - Xiong, Hui
AU - Lee, Won Hee
TI - Evaluating EEG-to-text models through noise-based performance analysis
T2 - Scientific Reports
J2 - Sci Rep
PY - 2025
DA - 2025
VL - 16
IS - 1
SP - 350
SN - 2045-2322
PB - Nature Publishing Group
DO - 10.1038/s41598-025-29587-x
UR - https://doi.org/10.1038/s41598-025-29587-x
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41598-025-29587-x",
"type": "article-journal",
"title": "Evaluating EEG-to-text models through noise-based performance analysis",
"container-title": "Scientific Reports",
"author": [
{
"family": "Jo",
"given": "Hyejeong"
},
{
"family": "Yang",
"given": "Yiqian"
},
{
"family": "Han",
"given": "Juhyeok"
},
{
"family": "Duan",
"given": "Yiqun"
},
{
"family": "Xiong",
"given": "Hui"
},
{
"family": "Lee",
"given": "Won Hee"
}
],
"container-title-short": "Sci Rep",
"volume": "16",
"issue": "1",
"page": "350",
"DOI": "10.1038/s41598-025-29587-x",
"PMCID": "PMC12770527",
"ISSN": "2045-2322",
"publisher": "Nature Publishing Group",
"URL": "https://doi.org/10.1038/s41598-025-29587-x",
"language": "en",
"issued": {
"date-parts": [
[
2025
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1038/s41467-026-75455-1 [code]
Shared latent representations of speech production for cross-patient speech decoding.
Journal: Nature communications
In common: h5py, PyTorch, scikit-learn, 3 other tools, 3 references
[2] doi:10.1038/s41586-026-10658-6 [code]
An AI system to help scientists write expert-level empirical software.
Journal: Nature
In common: Hugging Face Transformers, h5py, PyTorch, 4 other tools, methods / tools
[3] doi:10.1038/s41467-026-72253-7 [code]
Spurious alignment between large language models and brains can emerge from non-robust methods and overlooked confounds.
Journal: Nature communications
In common: Hugging Face Transformers, h5py, PyTorch, 4 other tools, methods / tools
[4] doi:10.1162/imag.a.1299 [code]
A modular semantic-structural pipeline for visual decoding from primate spiking data via selective temporal integration.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: Hugging Face Transformers, h5py, PyTorch, 4 other tools, methods / tools
[5] doi:10.1016/j.isci.2026.117180 [code]
Developmental changes in similarity between neural representations of mental arithmetic and artificial neural networks.
Journal: iScience
In common: Hugging Face Transformers, h5py, PyTorch, 4 other tools
[6] doi:10.1038/s41467-026-76098-y [code]
A single computational objective can produce specialization of streams in visual cortex.
Journal: Nature communications
In common: Hugging Face Transformers, h5py, PyTorch, 4 other tools
[7] doi:10.1186/s12864-026-12965-8 [code]
Systematic evaluation of single-cell foundation model interpretability: attention-derived edge scores add no incremental value over gene-level features for perturbation-target prediction.
Journal: BMC genomics
In common: Hugging Face Transformers, h5py, PyTorch, 4 other tools
[8] doi:10.1038/s41467-026-74358-5 [code]
Brain-inspired spatial intelligence for embodied agents.
Journal: Nature communications
In common: Hugging Face Transformers, h5py, PyTorch, 4 other tools
[9] doi:10.1371/journal.pcbi.1014263 [code]
MIRAGE: Robust multi-modal architectures translate fMRI-to-image models from vision to mental imagery.
Journal: PLoS computational biology
In common: Hugging Face Transformers, h5py, PyTorch, 4 other tools
[10] doi:10.1038/s42003-026-10169-0 [code]
Shared representations in brains and models reveal a two-route cortical organization during scene perception.
Journal: Communications biology
In common: Hugging Face Transformers, h5py, PyTorch, 4 other tools

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.