OSCR

Integrating metacognitive mechanisms optimizes EEG generative models via hierarchical regularization.

Code ↔ Paper

The paper beside its authors' code: matches between them have not been computed for this paper yet.

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 · 530 lines · 20 KB · no license

  1. from __future__ import print_function, division
  2. import tensorflow as tf
  3. tf.compat.v1.enable_eager_execution()
  4. from keras.layers import Input, Dense, Reshape, Flatten, Dropout
  5. from keras.layers import BatchNormalization, Activation, ZeroPadding2D
  6. from keras.layers.advanced_activations import LeakyReLU
  7. from keras.layers.convolutional import UpSampling2D, Conv2D
  8. from keras.models import Sequential, Model
  9. from keras.optimizers import Adam
  10. from keras import regularizers
  11. import keras.backend as K
  12. import matplotlib.pyplot as plt
  13. import scipy.io as sio
  14. import sys
  15. import os
  16. import numpy as np
  17. from keras.optimizers import RMSprop, Adam
  18. from scipy.io import savemat
  19. from tensorflow import keras
  20. from keras import regularizers
  21. from tensorflow.keras.layers import Input, Conv1D, Flatten, Dense, Conv2DTranspose, Reshape, Lambda, LeakyReLU, ReLU, \
  22. Embedding, Concatenate, BatchNormalization
  23. from tensorflow.keras.layers import Input, Conv1D, Flatten, Dense, Conv2DTranspose, Reshape, Lambda, LeakyReLU, ReLU, \
  24. Embedding, Concatenate, BatchNormalization
  25. from tensorflow.keras.models import Model
  26. from tensorflow.keras import backend as K
  27. # from tensorflow import pad, maximum, random, int3
  28. from scipy.fftpack import fft, fftshift, ifft
  29. from scipy.fftpack import fftfreq
  30. from sklearn import preprocessing
  31. from tensorflow_core import maximum
  32. from tensorflow_core.python import pad
  33. from tensorflow_core.python.kernel_tests import random
  34. from torch import nn
  35. import torch
  36. from torch import nn
  37. Tensor = torch.FloatTensor
  38. from torch.autograd import Variable
  39. from sklearn.preprocessing import StandardScaler
  40. from sklearn.preprocessing import MinMaxScaler
  41. from scipy.stats import wasserstein_distance
  42. import numpy.linalg as LA
  43. from scipy.stats import wasserstein_distance
  44. import math
  45. from tensorflow import int32
  46. mm = MinMaxScaler()
  47. criterion_freq = nn.BCELoss()
  48. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  49. PATH = '生成代码\wavegan\\231\data2_231f.mat'
  50. data = sio.loadmat(PATH)
  51. train_data = data['eeg']
  52. #train_data = train_data.swapaxes(1, 2)
  53. train_data = train_data[:, :, :]
  54. all_data = np.zeros((2946, 231, 32))
  55. train_data = np.array(train_data)
  56. print(train_data.shape)
  57. for i in range(32):
  58. train_data1 = train_data[:, :, i:i + 1]
  59. newdata = np.squeeze(train_data1, axis=2)
  60. newdata = preprocessing.MaxAbsScaler().fit_transform(newdata)
  61. newdata = np.expand_dims(newdata, axis=2)
  62. print(newdata.shape)
  63. newdata = np.array(newdata)
  64. all_data[:, :, i:i + 1] = newdata
  65. print(all_data.shape)
  66. x = all_data
  67. X = []
  68. F7 = x[:,:,3:4]
  69. F4 = x[:,:,5:6]
  70. FC1= x[:,:,8:9]
  71. #C3 = x[:,:,12:13]
  72. P3 = x[:,:,21:22]
  73. Pz = x[:,:,22:23]
  74. P4 = x[:,:,23:24]
  75. #X = X + [F7, F4, P3, Pz, P4]
  76. X = X + [FC1]
  77. x = np.array(X)
  78. x = x.swapaxes(0, 3)
  79. x = np.squeeze(x, axis=0)
  80. X_train = x.reshape(2946, 231, 1)
  81. x = X_train
  82. print(x.shape)
  83. def gradient_penalty(self, batch_size, real_images, fake_images):
  84. """ Calculates the gradient penalty.
  85. This loss is calculated on an interpolated image
  86. and added to the discriminator loss.
  87. """
  88. # get the interplated image
  89. alpha = tf.random.normal([batch_size, 1, 1], 0.0, 1.0)
  90. diff = fake_images - real_images
  91. interpolated = real_images + alpha * diff
  92. with tf.GradientTape() as gp_tape:
  93. gp_tape.watch(interpolated)
  94. # 1. Get the discriminator output for this interpolated image.
  95. pred = self.discriminator(interpolated, training=True)
  96. # 2. Calculate the gradients w.r.t to this interpolated image.
  97. grads = gp_tape.gradient(pred, [interpolated])[0]
  98. # 3. Calcuate the norm of the gradients
  99. norm = tf.sqrt(tf.reduce_sum(tf.square(grads), axis=[1, 2]))
  100. gp = tf.reduce_mean((norm - 1.0) ** 2)
  101. return gp
  102. def apply_phaseshuffle(args):
  103. x, rad = args
  104. pad_type = 'reflect'
  105. b, x_len, nch = x.get_shape().as_list()
  106. phase = random.uniform([], minval=-rad, maxval=rad + 1, dtype=int32)
  107. pad_l = maximum(phase, 0)
  108. pad_r = maximum(-phase, 0)
  109. phase_start = pad_r
  110. x = pad(x, [[0, 0], [pad_l, pad_r], [0, 0]], mode=pad_type)
  111. x = x[:, phase_start:phase_start + x_len]
  112. x.set_shape([b, x_len, nch])
  113. return x
  114. def Conv1DTranspose(input_tensor, filters, kernel_size, strides=2, padding='same'
  115. , name='1DTConv', activation='relu'):
  116. x = Conv2DTranspose(filters=filters, kernel_size=(1, kernel_size), strides=(1, strides), padding=padding,
  117. name=name, activation=activation)(K.expand_dims(input_tensor, axis=1))
  118. x = K.squeeze(x, axis=1)
  119. return x
  120. def clip_layer(**kwargs):
  121. def layer_c(x):
  122. return tf.image.resize_with_crop_or_pad(x, 1, 231)
  123. return Lambda(layer_c, **kwargs)
  124. class GAN():
  125. def __init__(self, ):
  126. super(GAN, self).__init__()
  127. self.eeg_rows = 231
  128. self.eeg_cols = 1
  129. self.eeg_shape = (self.eeg_rows, self.eeg_cols)
  130. self.latent_dim = 231
  131. self.z_dim = 231
  132. self.batch_size = 128
  133. self.gp_weight = 4.0
  134. self.ap = 0.1
  135. # d_optimizer = keras.optimizers.Adam(learning_rate=0.0004)
  136. # g_optimizer = keras.optimizers.Adam(learning_rate=0.0004)
  137. d_optimizer = keras.optimizers.Adam(learning_rate=0.0004)
  138. g_optimizer = keras.optimizers.Adam(learning_rate=0.0004)
  139. # Build and compile the discriminator self.discriminator = self.build_discriminator(is_training=True)
  140. use_batch_norm = False
  141. self.phaseshuffle_samples = 0
  142. self.generator = self.generator(self.latent_dim, use_batch_norm=use_batch_norm)
  143. self.discriminator = self.discriminator(self.phaseshuffle_samples)
  144. self.d_optimizer = d_optimizer
  145. self.g_optimizer = g_optimizer
  146. self.d_loss_fn = self.discriminator_loss
  147. self.g_loss_fn = self.generator_loss
  148. self.d_steps = 5
  149. '''
  150. self.discriminator.compile(loss='binary_crossentropy',
  151. optimizer=tf.keras.optimizers.Adam(learning_rate=0.0004),
  152. metrics=['accuracy'])
  153. '''
  154. def discriminator_loss(self, real_img, fake_img):
  155. real_loss = tf.reduce_mean(real_img)
  156. fake_loss = tf.reduce_mean(fake_img)
  157. return fake_loss - real_loss
  158. # Define the loss functions to be used for generator
  159. def generator_loss(self, fake_img):
  160. return -tf.reduce_mean(fake_img)
  161. def gradient_penalty(self, batch_size, real_images, fake_images):
  162. """ Calculates the gradient penalty.
  163. This loss is calculated on an interpolated image
  164. and added to the discriminator loss.
  165. """
  166. # get the interplated image
  167. alpha = tf.random.normal([batch_size, 1, 1], 0.0, 1.0)
  168. diff = fake_images - real_images
  169. interpolated = real_images + alpha * diff
  170. with tf.GradientTape() as gp_tape:
  171. gp_tape.watch(interpolated)
  172. # 1. Get the discriminator output for this interpolated image.
  173. pred = self.discriminator(interpolated, training=True)
  174. # 2. Calculate the gradients w.r.t to this interpolated image.
  175. grads = gp_tape.gradient(pred, [interpolated])[0]
  176. # 3. Calcuate the norm of the gradients
  177. norm = tf.sqrt(tf.reduce_sum(tf.square(grads), axis=[1, 2]))
  178. gp = tf.reduce_mean((norm - 1.0) ** 2)
  179. return gp
  180. def compute_kappa(self, xq, y):
  181. C = []
  182. for i in range(33):
  183. t_a = tf.norm([xq[7 * i + 3] - xq[7 * i], y[7 * i + 3] - y[7 * i]])
  184. t_b = tf.norm([xq[7 * i + 6] - xq[7 * i + 3], y[7 * i + 6] - y[7 * i + 3]])
  185. P = tf.convert_to_tensor([xq[7 * i], xq[7 * i + 3], xq[7 * i + 6]], dtype=tf.float32)
  186. P = tf.reshape(P, [3, 1])
  187. Q = tf.convert_to_tensor([y[7 * i], y[7 * i + 3], y[7 * i + 6]], dtype=tf.float32)
  188. Q = tf.reshape(Q, [3, 1])
  189. M = tf.convert_to_tensor([
  190. [1, -t_a, t_a ** 2],
  191. [1, 0, 0],
  192. [1, t_b, t_b ** 2]
  193. ], dtype=tf.float32)
  194. a = tf.matmul(tf.linalg.inv(M), P)
  195. b = tf.matmul(tf.linalg.inv(M), Q)
  196. kappa = 2 * (a[2] * b[1] - b[2] * a[1]) / tf.pow(a[1] ** 2. + b[1] ** 2., 1.5)
  197. kappa = tf.abs(kappa)
  198. C.append(kappa)
  199. return tf.convert_to_tensor(C, dtype=tf.float32)
  200. def calculate_loss_bc(self, Y, Y2):
  201. # Compute frequency domain loss (e.g., mean squared error)
  202. criterion_loss = tf.keras.losses.BinaryCrossentropy(from_logits=True)
  203. loss = criterion_loss(Y, Y2)
  204. return loss
  205. def compute_fft(self, x, num_fft):
  206. # Compute FFT and return the absolute value
  207. fft_result = tf.abs(tf.signal.fft(tf.cast(x, tf.complex64)))
  208. return fft_result
  209. def ncosine_similarity(self, tensor1, tensor2, epsilon=1e-8):
  210. # Normalize tensors
  211. norm_tensor1 = tf.norm(tensor1, axis=-1, keepdims=True)
  212. norm_tensor2 = tf.norm(tensor2, axis=-1, keepdims=True)
  213. # Compute cosine similarity
  214. similarity = tf.reduce_sum(tensor1 * tensor2, axis=-1) / (norm_tensor1 * norm_tensor2 + epsilon)
  215. return similarity
  216. def anti_collapse_regularizer(self, z1, z2, fake_feats_z1, fake_feats_z2):
  217. # Compute cosine similarity
  218. cos_fake_feats = self.ncosine_similarity(fake_feats_z1, fake_feats_z2)
  219. cos_z = self.ncosine_similarity(z1, z2)
  220. # Compute regularizer
  221. an_regularizer = tf.reduce_mean((1 - cos_fake_feats) / (1 - cos_z))
  222. return an_regularizer
  223. def generator(self, z_dim,
  224. use_batch_norm=False
  225. ):
  226. generator_filters = [1024, 512, 256, 128, 64]
  227. generator_input = Input(shape=(231,), name='generator_input')
  228. x = generator_input
  229. x = Dense(240, name='generator_input_dense')(x)
  230. x = Reshape((12, 20), name='generator_input_reshape')(x)
  231. # if use_batch_norm == True:
  232. x = BatchNormalization()(x)
  233. x = ReLU()(x)
  234. # x = Concatenate()([x, label_em])
  235. for i in range(4):
  236. x = Conv1DTranspose(
  237. input_tensor=x
  238. , filters=generator_filters[i + 1]
  239. , kernel_size=25
  240. , strides=1
  241. , padding='same'
  242. , name=f'generator_Tconv_{i}'
  243. , activation='relu'
  244. )
  245. # if use_batch_norm == True:
  246. x = BatchNormalization()(x)
  247. #
  248. x = Conv1DTranspose(
  249. input_tensor=x
  250. , filters=1
  251. , kernel_size=25
  252. , strides=20
  253. , padding='same'
  254. , name='generator_Tconv_4'
  255. , activation='tanh'
  256. )
  257. #
  258. x = Dense(1, kernel_regularizer=regularizers.l2(0.01))(x)
  259. # x = Dense(1, activity_regularizer=regularizers.l1(0.01))(x)
  260. x = Reshape((1, 240, 1))(x)
  261. # x=np.expand_dims(x,axis=2)
  262. x = clip_layer()(x)
  263. # x=np.squeeze(x,2)
  264. x = Reshape((231, 1))(x)
  265. generator_output = x
  266. generator = Model([generator_input], generator_output, name='Generator')
  267. model = Model(inputs=generator_input, outputs=generator_output)
  268. model.summary()
  269. return generator
  270. def discriminator(self, phaseshuffle_samples):
  271. discriminator_filters = [64, 128, 256, 512, 1024, 2048]
  272. discriminator_input = Input(shape=(231, 1), name='discriminator_input')
  273. x = discriminator_input
  274. for i in range(4):
  275. x = Conv1D(
  276. filters=discriminator_filters[i]
  277. , kernel_size=25
  278. , strides=1
  279. , padding='same'
  280. , name=f'discriminator_conv_{i}'
  281. )(x)
  282. x = LeakyReLU(alpha=0.2)(x)
  283. if phaseshuffle_samples > 0:
  284. x = Lambda(apply_phaseshuffle)([x, phaseshuffle_samples])
  285. # layer 4, no phase shuffle
  286. x = Conv1D(
  287. filters=discriminator_filters[4]
  288. , kernel_size=25
  289. , strides=20
  290. , padding='same'
  291. , name=f'discriminator_conv_4'
  292. )(x)
  293. x = Flatten()(x)
  294. # x = Dense(1, kernel_regularizer=regularizers.l2(0.01),
  295. # activity_regularizer=regularizers.l1(0.01))(x)
  296. discriminator_output = Dense(1)(x)
  297. discriminator = Model([discriminator_input], discriminator_output, name='Discriminator')
  298. model = Model(inputs=discriminator_input, outputs=discriminator_output)
  299. model.summary()
  300. return discriminator
  301. def train(self, epochs, batch_size=128, sample_interval=2, ap=0.1):
  302. x_plot_loss_g = []
  303. y_plot_loss_g = []
  304. if not os.path.exists('hse-wavegan231-3R-1-FC1-2/'):
  305. os.makedirs('hse-wavegan231-3R-1-FC1-2/')
  306. for epoch in range(epochs):
  307. idx = np.random.randint(0, x.shape[0], batch_size)
  308. real_images = x[idx]
  309. d_steps = 5
  310. for i in range(d_steps):
  311. random_latent_vectors = tf.random.normal( shape=(batch_size, self.latent_dim))
  312. with tf.GradientTape() as tape:
  313. fake_images = self.generator(random_latent_vectors, training=True)
  314. fake_logits = self.discriminator(fake_images, training=True)
  315. # Get the logits for real images
  316. # real_logits = self.discriminator(real_images, training=True)
  317. real_images_32 = tf.cast(real_images, dtype=tf.float32)
  318. real_logits = self.discriminator(real_images_32, training=True)
  319. # Calculate discriminator loss using fake and real logits
  320. d_cost = self.d_loss_fn(real_img=real_logits, fake_img=fake_logits)
  321. # Calculate the gradient penalty
  322. # WS= wasserstein_distance(real_images, fake_images)
  323. # d_cost1=np.abs(d_cost)
  324. # log=math.log( d_cost1)
  325. gp = self.gradient_penalty(batch_size, real_images, fake_images)
  326. # Add the gradient penalty to the original discriminator loss
  327. d_loss = d_cost + gp * self.gp_weight
  328. # if np.abs(d_loss) > 0.5:
  329. # self.d_steps = 6
  330. # if np.abs(d_loss)<0.5:
  331. # self.d_steps=5
  332. # Get the gradients w.r.t the discriminator loss
  333. d_gradient = tape.gradient(d_loss, self.discriminator.trainable_variables)
  334. # Update the weights of the discriminator using the discriminator optimizer
  335. self.d_optimizer.apply_gradients(
  336. zip(d_gradient, self.discriminator.trainable_variables)
  337. )
  338. random_latent_vectors = tf.random.normal(shape=(batch_size, self.latent_dim))
  339. with tf.GradientTape() as tape:
  340. # Generate fake images using the generator
  341. generated_images = self.generator(random_latent_vectors, training=True)
  342. # b = generated_images.numpy()
  343. b=K.eval(generated_images)
  344. sio.savemat('hse-wavegan231-3R-1-FC1-2/%d.mat' % (epoch), {'eeg': b})
  345. # Get the discriminator logits for fake images
  346. gen_img_logits = self.discriminator(generated_images, training=True)
  347. # Calculate the generator loss
  348. # 频谱
  349. x1 = real_images[:, :, 0]
  350. x2 = generated_images[:, :, 0]
  351. Y = self.compute_fft(x1, num_fft=256)
  352. # Y = tf.convert_to_tensor(Y)
  353. Y2 = self.compute_fft(x2, num_fft=256)
  354. # Y2 = tf.Variable(Y2)
  355. SR = self.calculate_loss_bc(Y, Y2)
  356. lambda_sr = 1e-6
  357. # CR
  358. generated_images1 = generated_images[:, :, 0]
  359. generated_images1_np = K.eval(generated_images1)
  360. table = np.array(generated_images1_np)
  361. # generated_images1 = tf.squeeze(generated_images, axis=2)
  362. # table = np.array(generated_images1)
  363. y = np.array([np.sum(table[:, i]) / 128 for i in range(231)])
  364. xq = np.arange(231)
  365. C = self.compute_kappa(xq, y)
  366. # C = tf.Variable(C, dtype=tf.float32, trainable=True)
  367. # Preprocess real images
  368. real_images1 = real_images[:, :, 0]
  369. # real_images1 = tf.squeeze(real_images, axis=2)
  370. table1 = np.array(real_images1)
  371. y1 = np.array([np.sum(table1[:, i]) / 128 for i in range(231)])
  372. xq1 = np.arange(231)
  373. C1 = self.compute_kappa(xq1, y1)
  374. CR = self.calculate_loss_bc(C, C1)
  375. lambda_cr = 1e-5
  376. # 反陷入
  377. z1 = tf.random.normal(shape=(batch_size, self.latent_dim))
  378. z2 = tf.random.normal(shape=(batch_size, self.latent_dim))
  379. s1 = self.generator(z1, training=True)
  380. s2 = self.generator(z2, training=True)
  381. s1 = tf.squeeze(s1, axis=2)
  382. s2 = tf.squeeze(s2, axis=2)
  383. epsilon = 1e-10
  384. norm_s1 = tf.maximum(tf.norm(s1, axis=1, keepdims=True), epsilon)
  385. norm_s2 = tf.maximum(tf.norm(s2, axis=1, keepdims=True), epsilon)
  386. s1 = s1 / norm_s1
  387. s2 = s2 / norm_s2
  388. # ql=np.abs(C1-C)
  389. g_loss = self.g_loss_fn(gen_img_logits)
  390. AR = self.anti_collapse_regularizer(z1, z2, s1, s2)
  391. lambda_ar = 1e-3
  392. # loss_freq = wasserstein_distance(Y.detach(), Y2.detach())
  393. # loss_freq = loss_freq .numpy()
  394. # print(loss_freq)
  395. #########################################
  396. a1 = 0.6
  397. b1 = 1 - a1
  398. # print(wd)
  399. # g_loss = g_loss + 1 / anti_collapse_regularizer * lambda_freq2
  400. # g_loss = g_loss + a*lambda_freq*loss_freq+b*(lambda_freq1*loss_freq3+(1 / anti_collapse_regularizer* lambda_freq2))
  401. # g_loss = g_loss + a1*lambda_freq * loss_freq + b1*(1 / anti_collapse_regularizer)
  402. g_loss = g_loss + a1 * (1 / AR * lambda_ar) + b1 * (
  403. 0.5 * lambda_sr * SR + 0.5 * lambda_cr * CR)
  404. # Get the gradients w.r.t the generator loss
  405. # g_loss = self.g_loss_fn(gen_img_logits)
  406. gen_gradient = tape.gradient(g_loss, self.generator.trainable_variables)
  407. # Update the weights of the generator using the generator optimizer
  408. self.g_optimizer.apply_gradients(
  409. zip(gen_gradient, self.generator.trainable_variables)
  410. )
  411. d_loss = d_loss.numpy()
  412. g_loss = g_loss.numpy()
  413. x_plot_loss_g.append(d_loss)
  414. y_plot_loss_g.append(g_loss)
  415. # sio.savemat('wavegan231-3R-sy/loss.mat', {'d_loss': x_plot_loss_g, 'g_loss': y_plot_loss_g})
  416. print("epoch:%d [D loss: %f] [G loss: %f]" % (epoch, d_loss, g_loss))
  417. sio.savemat('hse-wavegan231-3R-1-FC1-2/loss.mat', {'d_loss': x_plot_loss_g, 'g_loss': y_plot_loss_g})
  418. # print(errors[-1])
  419. '''
  420. if epoch < 4000:
  421. x_plot_loss_g.append(epoch)
  422. y_plot_loss_g.append(g_loss)
  423. g_loss = 0
  424. x_plot_loss_d.append(epoch)
  425. y_plot_loss_d.append(d_loss)
  426. d_loss = 0
  427. plt.figure()
  428. plt.subplot(2, 1, 1)
  429. loss_plt_d = plt.plot(x_plot_loss_d, y_plot_loss_d, 'b-')
  430. plt.title('d_loss')
  431. plt.subplot(2, 1, 2)
  432. loss_plt_g = plt.plot(x_plot_loss_g, y_plot_loss_g, 'r-')
  433. plt.title('g_loss')
  434. plt.savefig('loss_wavegan-sin-1.png')
  435. sio.savemat('wavegan231-3R-lt2/loss.mat', {'d_loss': y_plot_loss_d, 'g_loss': y_plot_loss_g})
  436. '''
  437. if __name__ == '__main__':
  438. gan = GAN()
  439. gan.train(epochs=3000, batch_size=128)
  440. K.clear_session()

WAVEGAN-231eeg-3R-1.py at commit 9e2d7b3, no license · at the source

Overview

Authors: Miaomiao Yu1, Te Guo1,2, Shangen Han1, Na Xue3, Wanying Yang1, Junda Huang1, Hongyu Chen1, Cheng He1, Jinhong Ding3, Likun Xia1
ORCID iDs: Likun Xia
  1. Laboratory of Neural Computing and Intelligent Perception, College of Information Engineering, Capital Normal University, Beijing 100048, China
  2. Beijing University of Chemical Technology, Beijing 100029, China
  3. School of Psychology, Capital Normal University, Beijing 100048, China
Journal: iScience, volume 29, issue 6, article 115785
Dates: received 31 August 2025; accepted 15 April 2026; published online 16 April 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1016/j.isci.2026.115785 · PMID 42256276 · PMCID PMC13233779 · OpenAlex W7154625149
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: EEG (modality), human (organism), cognitive (subfield)
Methods: Spectral & time-frequency, Smoothing, state filtering, decompositions, Machine learning, Evoked potentials, Statistics
Keywords: health sciences, medicine, medical specialty, electrodiagnostic medicine
Topic: EEG and Brain-Computer Interfaces (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Citations: not cited yet (Europe PMC); 44 references in the paper

Abstract

Obtaining sufficient electroencephalography (EEG) signals for training deep neural networks (DNNs) in brain-computer interfaces (BCIs) is challenging due to individual differences in neural activity, which require large per-participant data to map signals to actions, while factors like movement artifacts often limit data collection. Existing advances mainly leverage generative models with various regularizers to produce sufficient EEG signals. However, selecting appropriate regularizers remains challenging. Inspired by metacognition, the human cognitive process that monitors and regulates learning and decision-making, we propose a metacognitive regulation module including three regularizers that explicitly capture EEG temporal dynamics and functional resolution, thereby improving both the diversity and similarity of generated data. Through extensive theoretical and empirical validation on two datasets, we demonstrate that our module: (1) significantly improves generative models for generating highly complex, realistic EEG activity; (2) improves generalization across different generative models; and (3) endows DNN models with enhanced human-like decision-making and adaptation capabilities.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repository

Its files are read in the Code ↔ Paper reader above.

Seanhanyy/Metacognitive-Regulation-Module

License: none: the authors keep all their rights
State: the link answers, verified on 29 September 2026
Evidence: files inventoried
Commit: 9e2d7b3fb9ec2240fe002b4977f6e1b26f860634, 4 April 2026
Languages: Python (23)
Size: 30 files, 23 scripts
Software Heritage: not archived
Found in: “Data and code availability”
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: Keras (23 files), NumPy (23 files), scikit-learn (23 files), SciPy (23 files), TensorFlow (23 files), PyTorch (21 files), Matplotlib (19 files)
Availability: 1 check, the latest on 29 September 2026: the link answers
  • 29 September 2026: the link answers
23 files

The paper's code and data availability statement is in the Data section.

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;
  • 23 scripts, each with its path and the digest of its content;
  • no match between paragraphs and code yet;
  • 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 and code availability

• Data: The Bi2015a dataset be reached at here.35 The perception of structure-from-motion (PSFM) are available at Science Data Bank: https://doi.org/10.57760/sciencedb.32593. • Code: Code is publicly available at https://github.com/Seanhanyy/Metacognitive-Regulation-Module. • Additional information: Any additional information required to reanalyze the data reported in this paper is available from the lead contact upon request.

Reproduced under the paper's license (CC BY), from the paper cited above.

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, 29 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 10 authors, 4 keywords, 1 funder, 24 references.

Cite

This paper

Yu, M., Guo, T., Han, S., Xue, N., Yang, W., Huang, J., Chen, H., He, C., Ding, J., & Xia, L. (2026). Integrating metacognitive mechanisms optimizes EEG generative models via hierarchical regularization. iScience, 29(6), 115785. https://doi.org/10.1016/j.isci.2026.115785

BibTeX

@article{yu2026integrating,
author = {Yu, Miaomiao and Guo, Te and Han, Shangen and Xue, Na and Yang, Wanying and Huang, Junda and Chen, Hongyu and He, Cheng and Ding, Jinhong and Xia, Likun},
title = {{Integrating metacognitive mechanisms optimizes EEG generative models via hierarchical regularization}},
journal = {iScience},
year = {2026},
month = apr,
volume = {29},
number = {6},
pages = {115785},
publisher = {Elsevier},
issn = {2589-0042},
doi = {10.1016/j.isci.2026.115785},
url = {https://doi.org/10.1016/j.isci.2026.115785},
pmid = {42256276},
pmcid = {PMC13233779}
}

RIS

TY - JOUR
AU - Yu, Miaomiao
AU - Guo, Te
AU - Han, Shangen
AU - Xue, Na
AU - Yang, Wanying
AU - Huang, Junda
AU - Chen, Hongyu
AU - He, Cheng
AU - Ding, Jinhong
AU - Xia, Likun
TI - Integrating metacognitive mechanisms optimizes EEG generative models via hierarchical regularization
T2 - iScience
J2 - iScience
PY - 2026
DA - 2026/04/16
VL - 29
IS - 6
SP - 115785
SN - 2589-0042
PB - Elsevier
DO - 10.1016/j.isci.2026.115785
UR - https://doi.org/10.1016/j.isci.2026.115785
LA - en
ER -

CSL-JSON

{
"id": "10.1016/j.isci.2026.115785",
"type": "article-journal",
"title": "Integrating metacognitive mechanisms optimizes EEG generative models via hierarchical regularization",
"container-title": "iScience",
"author": [
{
"family": "Yu",
"given": "Miaomiao"
},
{
"family": "Guo",
"given": "Te"
},
{
"family": "Han",
"given": "Shangen"
},
{
"family": "Xue",
"given": "Na"
},
{
"family": "Yang",
"given": "Wanying"
},
{
"family": "Huang",
"given": "Junda"
},
{
"family": "Chen",
"given": "Hongyu"
},
{
"family": "He",
"given": "Cheng"
},
{
"family": "Ding",
"given": "Jinhong"
},
{
"family": "Xia",
"given": "Likun"
}
],
"container-title-short": "iScience",
"volume": "29",
"issue": "6",
"page": "115785",
"DOI": "10.1016/j.isci.2026.115785",
"PMID": "42256276",
"PMCID": "PMC13233779",
"ISSN": "2589-0042",
"publisher": "Elsevier",
"URL": "https://doi.org/10.1016/j.isci.2026.115785",
"language": "en",
"issued": {
"date-parts": [
[
2026,
4,
16
]
]
}
}

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.3389/fpsyg.2026.1774068 [code]
Analysis of cognitive mechanisms in phoneme perception and pronunciation errors among Korean language learners.
Journal: Frontiers in psychology
In common: Keras, TensorFlow, PyTorch, 4 other tools, EEG, cognitive
[2] doi:10.1002/ana.78203 [code]
AI-Driven Mapping of Seizure Spread Patterns.
Journal: Annals of neurology
In common: Keras, TensorFlow, PyTorch, 4 other tools, EEG
[3] doi:10.1038/s41597-025-05174-7 [code]
A large-scale MEG and EEG dataset for object recognition in naturalistic scenes
Journal: n/a
In common: Keras, TensorFlow, PyTorch, 4 other tools, EEG
[4] doi:10.1038/s41598-026-52330-z [code]
SHAP analysis of an improved EEG-based mental workload classification framework: utilizing data augmentation and explainable AI.
Journal: Scientific reports
In common: Keras, TensorFlow, scikit-learn, 3 other tools, EEG, 1 reference
[5] doi:10.1038/s41467-026-75455-1 [code]
Shared latent representations of speech production for cross-patient speech decoding.
Journal: Nature communications
In common: Keras, TensorFlow, PyTorch, 4 other tools, cognitive
[6] doi:10.1523/eneuro.0023-26.2026 [code]
Real-Time Segmentation and Classification of Birdsong Syllables for Learning Experiments.
Journal: eNeuro
In common: Keras, TensorFlow, PyTorch, 4 other tools, cognitive
[7] doi:10.1038/s42003-026-10957-8 [code]
Brain defence by the extracellular matrix protein Cochlin.
Journal: Communications biology
In common: Keras, TensorFlow, PyTorch, 4 other tools
[8] doi:10.1371/journal.pcbi.1014615 [code]
Toward reliable machine learning models for neural circuit inference: A diagnostic study of CNNs on spike trains.
Journal: PLoS computational biology
In common: Keras, TensorFlow, PyTorch, 4 other tools
[9] doi:10.1371/journal.pcbi.1014571 [code]
SynAPSeg: A novel dataset and image analysis framework for deep learning-based synapse detection and quantification.
Journal: PLoS computational biology
In common: Keras, TensorFlow, PyTorch, 4 other tools
[10] doi:10.1093/nar/gkag706 [code]
scDifformer: diffusion-based post-training for virtual cell modeling across large-scale single-cell data.
Journal: Nucleic acids research
In common: Keras, TensorFlow, 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.