OSCR

GACNet: A graph attention-based neural network for electroencephalography localization via contrastive learning.

Code ↔ Paper

2 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 2 matches
  1. [1] § Proposed method › Supervised contrastive and regression joint optimization ↔ main.py, lines 478–540 · score 0.56 · regression head, supervised contrastive loss, optimized, encoder, training, model
  2. [2] § Proposed method › Spatio-temporal representation module › Pre-processing module ↔ main.py, lines 205–309 · score 0.50 · ReLU, MLP, global, layer, Pre, weights

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 · 673 lines · 26 KB · no license · 2 matches

  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. # from torch.utils.data import Dataset, DataLoader
  5. from sklearn.cluster import KMeans
  6. import numpy as np
  7. import random
  8. from helper_functions import split
  9. from EEGEyeNet import EEGEyeNetDataset
  10. # from torch.utils.data import DataLoader, Subset
  11. from torch_geometric.data import Batch
  12. from torch_geometric.data import Data, DataLoader
  13. from einops import rearrange
  14. from torch.optim.lr_scheduler import ReduceLROnPlateau
  15. from losses import SupConLoss
  16. from tqdm import tqdm
  17. from torch_geometric.nn import GCNConv, global_mean_pool, BatchNorm, global_add_pool, GATConv, ChebConv, GCN2Conv, ARMAConv, GATv2Conv
  18. import csv
  19. def set_seed(seed=42):
  20. random.seed(seed)
  21. np.random.seed(seed)
  22. torch.manual_seed(seed)
  23. torch.cuda.manual_seed(seed)
  24. torch.cuda.manual_seed_all(seed) # for multi-GPU
  25. torch.backends.cudnn.deterministic = True
  26. torch.backends.cudnn.benchmark = False
  27. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  28. def compute_correlation_matrix1(data):
  29. correlation_matrices = np.corrcoef(data.T)
  30. # mean_correlation_matrix = np.mean(correlation_matrices, axis=0)
  31. return correlation_matrices
  32. def compute_correlation_matrix(data):
  33. correlation_matrices = [np.corrcoef(data[i].T) for i in range(data.shape[0])]
  34. mean_correlation_matrix = np.mean(correlation_matrices, axis=0)
  35. return mean_correlation_matrix
  36. def create_graph_from_correlation0(correlation_matrix):
  37. num_channels = correlation_matrix.shape[0]
  38. edge_index = []
  39. edge_attr = []
  40. for i in range(num_channels):
  41. for j in range(num_channels):
  42. if i != j:
  43. value = sorted([i, j])
  44. edge_index.append(value)
  45. edge_index = np.asarray(edge_index)
  46. edge_index = np.unique(edge_index, axis = 0)
  47. for idx in edge_index:
  48. m, n = idx
  49. edge_attr.append([correlation_matrix[m,n]])
  50. # edge_attr = np.asarray(edge_attr)
  51. return edge_index
  52. def create_graph_from_correlation(data, edge_index, correlation_matrix, threshold=0.86):
  53. edge_index = np.asarray(edge_index)
  54. edge_index = torch.tensor(edge_index, dtype=torch.long).t().contiguous()
  55. if edge_index.size(1) == 0:
  56. raise ValueError("Không có cạnh nào được tạo ra. Kiểm tra ma trận tương quan và ngưỡng.")
  57. return edge_index
  58. class PreNorm(nn.Module):
  59. def __init__(self, dim, fn):
  60. super().__init__()
  61. self.norm = nn.LayerNorm(dim)
  62. self.fn = fn
  63. def forward(self, x, **kwargs):
  64. return self.fn(self.norm(x), **kwargs)
  65. class FeedForward(nn.Module):
  66. def __init__(self, dim, hidden_dim, dropout = 0.):
  67. super().__init__()
  68. self.net = nn.Sequential(
  69. nn.Linear(dim, hidden_dim),
  70. nn.GELU(),
  71. nn.Dropout(dropout),
  72. nn.Linear(hidden_dim, dim),
  73. nn.Dropout(dropout)
  74. )
  75. def forward(self, x):
  76. return self.net(x)
  77. class Attention(nn.Module):
  78. def __init__(self, dim, heads=8, dim_head=64, dropout=0.):
  79. super().__init__()
  80. inner_dim = dim_head * heads
  81. project_out = not (heads == 1 and dim_head == dim)
  82. self.heads = heads
  83. self.scale = dim_head ** -0.5
  84. self.attend = nn.Softmax(dim=-1)
  85. self.dropout = nn.Dropout(dropout)
  86. self.to_qkv = nn.Linear(dim, inner_dim * 3, bias=False)
  87. self.to_out = nn.Sequential(
  88. nn.Linear(inner_dim, dim),
  89. nn.Dropout(dropout)
  90. ) if project_out else nn.Identity()
  91. def forward(self, x):
  92. qkv = self.to_qkv(x).chunk(3, dim=-1)
  93. q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h=self.heads), qkv)
  94. dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale
  95. attn = self.attend(dots)
  96. attn = self.dropout(attn)
  97. out = torch.matmul(attn, v)
  98. out = rearrange(out, 'b h n d -> b n (h d)')
  99. return self.to_out(out)
  100. def drop_path(x, drop_prob: float = 0., training: bool = False, scale_by_keep: bool = True):
  101. """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
  102. This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
  103. the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
  104. See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
  105. changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
  106. 'survival rate' as the argument.
  107. """
  108. if drop_prob == 0. or not training:
  109. return x
  110. keep_prob = 1 - drop_prob
  111. shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
  112. random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
  113. if keep_prob > 0.0 and scale_by_keep:
  114. random_tensor.div_(keep_prob)
  115. return x * random_tensor
  116. class DropPath(nn.Module):
  117. """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
  118. """
  119. def __init__(self, drop_prob: float = 0., scale_by_keep: bool = True):
  120. super(DropPath, self).__init__()
  121. self.drop_prob = drop_prob
  122. self.scale_by_keep = scale_by_keep
  123. def forward(self, x):
  124. return drop_path(x, self.drop_prob, self.training, self.scale_by_keep)
  125. def extra_repr(self):
  126. return f'drop_prob={round(self.drop_prob,3):0.3f}'
  127. #
  128. #
  129. # class EEGDataset(Dataset):
  130. # def __init__(self, eeg, coords, labels):
  131. # self.eeg = eeg
  132. # self.coords = coords
  133. # self.labels = labels
  134. #
  135. # def __len__(self):
  136. # return len(self.eeg)
  137. #
  138. # def __getitem__(self, idx):
  139. # signal = self.eeg[idx] # [129, 500]
  140. # label = self.labels[idx]
  141. # coord = self.coords[idx]
  142. #
  143. # # Normalize từng sample
  144. # signal = (signal - signal.mean()) / (signal.std() + 1e-6)
  145. #
  146. # return torch.tensor(signal), torch.tensor(label), torch.tensor(coord)
  147. # class LoRALinear(nn.Module):
  148. # def __init__(self, in_features, out_features, r=4, alpha=1.0):
  149. # super().__init__()
  150. # self.weight = nn.Parameter(torch.randn(out_features, in_features))
  151. # self.r = r
  152. # self.alpha = alpha
  153. # self.A = nn.Parameter(torch.randn(r, in_features))
  154. # self.B = nn.Parameter(torch.randn(out_features, r))
  155. #
  156. # def forward(self, x):
  157. # base = F.linear(x, self.weight)
  158. # # self.A = torch.permute(self.A, (0, 2, 1))
  159. # # print(x.shape)
  160. # # print(self.A.T.shape)
  161. # lora = F.linear(x, self.A)
  162. # lora = F.linear(lora, self.B)
  163. # return base + self.alpha * lora
  164. class BiLSTMEncoder(nn.Module):
  165. def __init__(self, input_size=40, hidden_size=500, proj_dim=512, num_layers=2):
  166. super().__init__()
  167. # self.lstm = nn.LSTM(
  168. # input_size=input_size,
  169. # hidden_size=hidden_size,
  170. # num_layers=num_layers,
  171. # batch_first=False,
  172. # bidirectional=True
  173. # )
  174. self.linear0 = nn.Sequential(torch.nn.Linear(500, 128, bias=True), nn.ReLU(),
  175. # torch.nn.Dropout(p=0.1),
  176. torch.nn.Linear(128, 256, bias=True), nn.ReLU(),
  177. # torch.nn.Dropout(p=0.1),
  178. torch.nn.Linear(256, 500, bias=True))
  179. self.conv11 = nn.Conv1d(in_channels=input_size, out_channels=64, kernel_size=3, padding=1)
  180. self.conv21 = nn.Conv1d(in_channels=64, out_channels=input_size, kernel_size=3, padding=1)
  181. self.bn11 = nn.BatchNorm1d(input_size)
  182. dim_all = 500
  183. depth = 2 # best=8
  184. heads = 8 # best=8s
  185. dim_head = 8
  186. mlp_dim = 8
  187. dropout = 0.1
  188. drop_path = 0.1
  189. self.layers1 = nn.Sequential(*[])
  190. # self.layers = nn.Sequential(*[])
  191. self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
  192. for _ in range(depth):
  193. self.layers1.append(nn.Sequential(*[
  194. PreNorm(dim_all, Attention(dim_all, heads=heads, dim_head=dim_head, dropout=dropout)),
  195. PreNorm(dim_all, FeedForward(dim_all, mlp_dim, dropout=dropout))
  196. ]))
  197. self.lstm = nn.LSTM(hidden_size, hidden_size, num_layers, batch_first=False, bidirectional=True)
  198. # self.projector = nn.Sequential(
  199. # nn.Linear(input_size * 2*hidden_size, proj_dim),
  200. # nn.ReLU(),
  201. # nn.Linear(proj_dim, proj_dim)
  202. # )
  203. # self.conv1 = GCNConv(dim_all * 2, dim_all, improved=True, cached=True, normalize=False)
  204. #
  205. # self.conv2 = GCNConv(dim_all, dim_all * 2, improved=True, cached=True, normalize=False)
  206. #
  207. # self.conv2_bn = BatchNorm(dim_all * 2, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  208. self.conv1 = GATv2Conv(500 * 2, 128, heads=4, concat=True, dropout=0.)
  209. self.conv2 = GATv2Conv(512, 250, heads=4, concat=True, dropout=0.)
  210. # self.conv2 = GATv2Conv(512, 500 * 2, heads=4, concat=False, dropout=0.)
  211. self.conv2_bn = BatchNorm(dim_all * 2, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  212. # self.projection = nn.Sequential(
  213. # LoRALinear(dim_all * 2, 128),
  214. # nn.ReLU(),
  215. # LoRALinear(128, dim_all*2)
  216. # )
  217. def forward(self, x, edge_index, batch):
  218. # x: [B, C=129, T=500] → transpose thành [B, T, C]
  219. # x = x.transpose(1, 2) # [B, 500, 129]
  220. # print(x.shape)
  221. batch_size = x.shape[0]
  222. x = self.linear0(x)
  223. # print(x.shape)
  224. x = F.leaky_relu(self.conv11(x))
  225. x = F.leaky_relu(self.bn11(self.conv21(x)))
  226. for atten, ff in self.layers1:
  227. x_ = atten(x)
  228. x = x + self.drop_path(x_)
  229. x = x + self.drop_path(ff(x))
  230. x, (hn, _) = self.lstm(x) # hn: [num_layers*2, B, hidden]
  231. x = x.contiguous().view(-1, x.size(-1))
  232. # x_c = x.clone()
  233. x = F.relu(self.conv1(x, edge_index=edge_index))
  234. # x = F.dropout(x, p=0.1, training=self.training)
  235. # x = F.leaky_relu(self.conv2(x, edge_index, edge_weight=edge_attr))
  236. # x = F.leaky_relu(self.conv3(x, edge_index, edge_weight=edge_attr))
  237. # x = F.leaky_relu(self.conv2(x, edge_index))
  238. # x = F.leaky_relu(self.conv2_bn(self.conv2(x, edge_index, edge_weight=edge_attr) + x))
  239. x = F.relu(self.conv2_bn(self.conv2(x, edge_index=edge_index)))
  240. # x = F.leaky_relu(self.conv2_bn(self.conv4(x, edge_index, edge_weight=edge_attr)))
  241. # x = F.leaky_relu(global_add_pool(x, batch=batch))
  242. x = global_add_pool(x, batch=batch)
  243. # print(output.shape)
  244. # Ghép hướng tiến và lùi ở layer cuối cùng
  245. # h_forward = hn[-2] # [B, hidden]
  246. # h_backward = hn[-1]
  247. # h_final = torch.cat([h_forward, h_backward], dim=1) # [B, hidden*2]
  248. # # print(h_final.shape)
  249. # a
  250. # x = x.view(batch_size, -1, x.size(-1))
  251. # z = self.projector(output) # [B, proj_dim]
  252. # x = self.projection(x)
  253. return F.normalize(x, dim=1)
  254. # return F.normalize(x, p=2, dim=2)
  255. class RegressionHead(nn.Module):
  256. def __init__(self, encoder):
  257. super().__init__()
  258. self.encoder = encoder
  259. # self.mlp = torch.nn.Sequential(torch.nn.Linear(1000, 1000, bias=True), nn.ReLU(),
  260. # # torch.nn.Dropout(p=0.1),
  261. # torch.nn.Linear(1000, 512, bias=True), nn.ReLU(),
  262. # torch.nn.Linear(512, 2, bias=True))
  263. # self.mlp = nn.Sequential(
  264. # nn.Linear(1000, 256),
  265. # nn.BatchNorm1d(256),
  266. # nn.ReLU(),
  267. # nn.Linear(256, 128),
  268. # nn.BatchNorm1d(128),
  269. # nn.ReLU(),
  270. # nn.Linear(128, 2)
  271. # )
  272. # self.mlp = nn.Sequential(
  273. # nn.Linear(1000, 512),
  274. # nn.BatchNorm1d(512),
  275. # nn.ReLU(),
  276. # nn.Linear(512, 256),
  277. # nn.BatchNorm1d(256),
  278. # nn.ReLU(),
  279. # nn.Linear(256, 2)#1305,1423#best
  280. # )
  281. self.mlp = nn.Sequential(
  282. # torch.nn.Linear(1000, 1000), nn.ReLU(),
  283. nn.Linear(1000, 512),
  284. nn.BatchNorm1d(512),
  285. nn.ReLU(),
  286. nn.Linear(512, 2)
  287. # nn.BatchNorm1d(256),
  288. # nn.ReLU(),
  289. # nn.Linear(256, 2) # 1305,1423
  290. )
  291. self.mlp.apply(lambda x: nn.init.xavier_normal_(x.weight, gain=1) if type(x) == nn.Linear else None)
  292. def forward(self, x, edge_index, batch):
  293. with torch.no_grad():
  294. features_ = self.encoder(x, edge_index, batch)
  295. features = features_.view(features_.size(0), -1)
  296. return self.mlp(features), F.normalize(features_, dim=1)
  297. def sliding_window(data, window_size=32, stride=24):
  298. windows = []
  299. for i in range(0, len(data) - window_size + 1, stride):
  300. windows.append(data[i:i + window_size])
  301. return windows
  302. def supervised_contrastive_loss(features, labels, temperature=0.07):#0.07
  303. device = features.device
  304. labels = labels.contiguous().view(-1, 1)
  305. mask = torch.eq(labels, labels.T).float().to(device)
  306. anchor_dot_contrast = torch.div(torch.matmul(features, features.T), temperature)
  307. logits_max, _ = torch.max(anchor_dot_contrast, dim=1, keepdim=True)
  308. logits = anchor_dot_contrast - logits_max.detach()
  309. logits_mask = torch.ones_like(mask) - torch.eye(mask.shape[0]).to(device)
  310. mask = mask * logits_mask
  311. exp_logits = torch.exp(logits) * logits_mask
  312. log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True) + 1e-6)
  313. mean_log_prob_pos = (mask * log_prob).sum(1) / (mask.sum(1) + 1e-6)
  314. loss = -mean_log_prob_pos.mean()
  315. return loss
  316. EEGEyeNet = EEGEyeNetDataset('/data/oanh/Position_task_with_dots_synchronised_min.npz')
  317. train_indices, val_indices, test_indices = split(EEGEyeNet.trainY[:,0],0.7,0.15,0.15) # indices for the training set
  318. print('Before remove: ', train_indices.shape)
  319. indices_to_remove = list(range(9127, 9522))
  320. train_indices = np.delete(train_indices, indices_to_remove, axis=0)
  321. print('After remove: ', train_indices.shape)
  322. data_get_edge = np.delete(EEGEyeNet.trainX, indices_to_remove, axis=0)
  323. data_get_cluster = np.delete(EEGEyeNet.trainY, indices_to_remove, axis=0)
  324. correlation_matrix = compute_correlation_matrix(data_get_edge)
  325. print('correlation_matrix: ',correlation_matrix.shape)
  326. edge_index_00 = create_graph_from_correlation0(correlation_matrix)
  327. edge_index_0 = edge_index_00
  328. data = EEGEyeNet.trainX[:, :, :]
  329. labels = EEGEyeNet.trainY[:, 1:]
  330. eye_coords = labels
  331. num_clusters = 25
  332. kmeans = KMeans(n_clusters=num_clusters, random_state=42)
  333. # labels_true = kmeans.fit_predict(eye_coords)
  334. labels_true = np.load('/home/oem/oanh/GCN/fillter_by_cluster/contrastive_learning/labels_true_12k.npy')
  335. # np.save("labels_true.npy", labels_true)
  336. # Chuẩn bị danh sách các đối tượng Data của PyG
  337. graph_data_list = []
  338. print('----Number of edge is: ', edge_index_0.shape)
  339. for i in range(data.shape[0]):
  340. x = torch.tensor(data[i], dtype=torch.float) # Mỗi kênh là một nút trong đồ thị
  341. # print(labels[i])
  342. # print(x.shape)
  343. correlation_matrix = compute_correlation_matrix1(x)
  344. # print('correlation_matrix: ', correlation_matrix.shape)
  345. # a
  346. edge_index = create_graph_from_correlation(x, edge_index_0, correlation_matrix, 0.86)
  347. # print(edge_index)
  348. # edge_index, edge_attr = create_graph_from_correlation_test(correlation_matrix, 0.86)
  349. # print('correlation_matrix: ', correlation_matrix.shape)
  350. # a
  351. # edge_index, edge_attr = create_graph_from_correlation(x, correlation_matrix, 0.86)
  352. # print(edge_index.shape)
  353. graph_data = Data(x=x.T, edge_index=edge_index,edge_att=labels_true[i], y=labels[i])
  354. graph_data_list.append(graph_data)
  355. # print(graph_data_list[0].x.shape)
  356. train_data, val_data, test_data = [graph_data_list[index] for index in train_indices], [graph_data_list[index] for
  357. index in val_indices], [graph_data_list[index] for index in test_indices]
  358. eeg_dataset_train = sliding_window(train_data, 128, 128)
  359. eeg_dataset_val = sliding_window(val_data, 128, 128)
  360. eeg_dataset_test = sliding_window(test_data, 128, 128)
  361. # train = Subset(EEGEyeNet, indices=train_indices)
  362. # val = Subset(EEGEyeNet, indices=val_indices)
  363. # test = Subset(EEGEyeNet, indices=test_indices)
  364. train_loader = DataLoader(eeg_dataset_train, batch_size=1, shuffle=False)
  365. val_loader = DataLoader(eeg_dataset_val, batch_size=1, shuffle=False)
  366. test_loader = DataLoader(eeg_dataset_test, batch_size=1, shuffle=False)
  367. # x = np.concatenate((x[:9127, :, :], x[9523:, :, :]), axis=0)
  368. # eeg_data = np.random.randn(N, C, T).astype(np.float32)
  369. # eeg_data = np.transpose(x, (0, 2, 1)).astype(np.float32)
  370. encoder = BiLSTMEncoder().cuda()
  371. lr0 = 0.0003
  372. # lr0 = 0.0007
  373. optimizer = torch.optim.Adam(encoder.parameters(), lr=lr0)
  374. # train_dataset = EEGDataset(eeg_data, eye_coords, labels)
  375. batch_size = 64
  376. # train_loader = DataLoader(train, batch_size=batch_size)
  377. # val_loader = DataLoader(val, batch_size=batch_size)
  378. # test_loader = DataLoader(test, batch_size=batch_size)
  379. # train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
  380. torch.cuda.empty_cache()
  381. scheduler_0 = ReduceLROnPlateau(optimizer, mode='min', factor=0.1, patience=5, min_lr=1e-6, verbose=True)
  382. criterion = SupConLoss(temperature=0.007)
  383. # for param in encoder.encoder.parameters():
  384. # param.requires_grad = False
  385. set_seed(42)
  386. for epoch in range(100):
  387. encoder.train()
  388. total_loss = 0
  389. for i, batch in tqdm(enumerate(train_loader)):
  390. batch = Batch.from_data_list(batch)
  391. num_graphs = batch.num_graphs
  392. # print(batch.x.shape[0])
  393. # print(num_graphs)
  394. num_nodes_per_graph = batch.x.shape[0] // num_graphs
  395. x = batch.x.view(num_graphs, num_nodes_per_graph, -1).to(device)
  396. batch = batch.to(device)
  397. # y_batch = torch.tensor(np.asarray(batch.y)).to(device).float()
  398. label = torch.tensor(np.asarray(batch.edge_att)).to(device).float()
  399. out = encoder(x, batch.edge_index, batch.batch) # [B, D]
  400. # print(out.shape, label.shape)
  401. loss = supervised_contrastive_loss(out, label)
  402. # loss = criterion(out, label)
  403. optimizer.zero_grad()
  404. loss.backward()
  405. optimizer.step()
  406. total_loss += loss.item()
  407. print(f"Epoch {epoch} - SupCon Loss: {total_loss / len(train_loader):.4f}")
  408. value_train_loss = total_loss / len(train_loader)
  409. # scheduler_0.step(train_loss)
  410. encoder.eval()
  411. total_val_loss = 0
  412. with torch.no_grad():
  413. for i, batch in tqdm(enumerate(test_loader)):
  414. batch = Batch.from_data_list(batch)
  415. num_graphs = batch.num_graphs
  416. # print(batch.x.shape[0])
  417. # print(num_graphs)
  418. num_nodes_per_graph = batch.x.shape[0] // num_graphs
  419. x = batch.x.view(num_graphs, num_nodes_per_graph, -1).to(device)
  420. batch = batch.to(device)
  421. # y_batch = torch.tensor(np.asarray(batch.y)).to(device).float()
  422. label = torch.tensor(np.asarray(batch.edge_att)).to(device).float()
  423. out = encoder(x, batch.edge_index, batch.batch) # [B, D]
  424. # print(out.shape, label.shape)
  425. loss = supervised_contrastive_loss(out, label)
  426. # loss = criterion(out, label)
  427. # optimizer.zero_grad()
  428. # loss.backward()
  429. # optimizer.step()
  430. total_val_loss += loss.item()
  431. print(f"====Epoch {epoch} - SupCon Val Loss: {total_val_loss / len(test_loader):.4f}")
  432. valid_loss_encoder = total_val_loss / len(test_loader)
  433. scheduler_0.step(value_train_loss)
  434. lr = 0.0005
  435. set_seed(42)
  436. reg_model = RegressionHead(encoder).cuda()
  437. optimizer = torch.optim.Adam(reg_model.parameters(), lr=lr)
  438. mse = nn.MSELoss()
  439. scheduler = ReduceLROnPlateau(optimizer, mode='min', factor=0.1, patience=5, min_lr=1e-6, verbose=True)
  440. loss_all = []
  441. def count_parameters(model):
  442. return sum(p.numel() for p in model.parameters() if p.requires_grad)
  443. param = count_parameters(reg_model)
  444. param1 = count_parameters(encoder)
  445. print('Number of parameters: ', param + param1)
  446. # print('Number of parameters: ', param2)
  447. for epoch in range(100):
  448. print('Epoch-{0} lr: {1}'.format(epoch, optimizer.param_groups[0]['lr']))
  449. loss_3 = []
  450. loss_3.append(epoch)
  451. reg_model.train()
  452. total_loss = 0
  453. epoch_loss = 0
  454. for i, batch in tqdm(enumerate(train_loader)):
  455. # Chuyển batch vào thiết bị (CPU hoặc GPU)
  456. # print(batch)
  457. batch = Batch.from_data_list(batch)
  458. # print(batch)
  459. num_graphs = batch.num_graphs
  460. # print(batch.x.shape[0])
  461. # print(num_graphs)
  462. num_nodes_per_graph = batch.x.shape[0] // num_graphs
  463. x = batch.x.view(num_graphs, num_nodes_per_graph, -1).to(device)
  464. batch = batch.to(device)
  465. label = torch.tensor(np.asarray(batch.edge_att)).to(device).float()
  466. y_batch = torch.tensor(np.asarray(batch.y)).to(device).float()
  467. optimizer.zero_grad()
  468. # edge_index = edge_index.to(torch.device('cuda' if torch.cuda.is_available() else 'cpu'))
  469. # edge_attr = edge_attr.to(torch.device('cuda' if torch.cuda.is_available() else 'cpu'))
  470. outputs, feature = reg_model(x, batch.edge_index, batch.batch)
  471. # feature = encoder(x, batch.edge_index, batch.batch)
  472. y_batch = y_batch.view(-1, 2)
  473. outputs = outputs.view(-1, 2)
  474. loss = mse(outputs, y_batch)
  475. loss_cluster = supervised_contrastive_loss(feature, label)
  476. loss = loss + loss_cluster
  477. # loss_encoder = supervised_contrastive_loss(feature, y_batch)
  478. # loss = loss_mse*0.6 + loss_encoder*0.4
  479. # print(outputs)
  480. loss.backward()
  481. optimizer.step()
  482. epoch_loss += loss.item()
  483. # print(f"Epoch {epoch + 1}, Loss: {epoch_loss / len(data_loader)}")
  484. print(f"Epoch {epoch + 1}, Training Loss: {epoch_loss / len(train_loader)}")
  485. train_loss = epoch_loss / len(train_loader)
  486. loss_3.append(train_loss)
  487. # Đánh giá mô hình
  488. val_loss = 0
  489. reg_model.eval()
  490. with torch.no_grad():
  491. for i, batch in enumerate(val_loader):
  492. batch = Batch.from_data_list(batch)
  493. num_graphs = batch.num_graphs
  494. num_nodes_per_graph = batch.x.shape[0] // num_graphs
  495. x = batch.x.view(num_graphs, num_nodes_per_graph, -1).to(device)
  496. batch = batch.to(device)
  497. label = torch.tensor(np.asarray(batch.edge_att)).to(device).float()
  498. y_batch = torch.tensor(np.asarray(batch.y)).to(device)
  499. outputs, feature = reg_model(x, batch.edge_index, batch.batch)
  500. y_batch = y_batch.view(-1, 2)
  501. outputs = outputs.view(-1, 2)
  502. loss = mse(outputs, y_batch)
  503. loss_cluster = supervised_contrastive_loss(feature, label)
  504. loss = loss + loss_cluster
  505. val_loss += loss.item()
  506. print(f"Epoch {epoch + 1}, Val Loss: {val_loss / len(val_loader)}")
  507. valid_loss = val_loss / len(val_loader)
  508. loss_3.append(valid_loss)
  509. # Đánh giá mô hình
  510. test_loss = 0
  511. reg_model.eval()
  512. with torch.no_grad():
  513. for i, batch in enumerate(test_loader):
  514. batch = Batch.from_data_list(batch)
  515. num_graphs = batch.num_graphs
  516. num_nodes_per_graph = batch.x.shape[0] // num_graphs
  517. x = batch.x.view(num_graphs, num_nodes_per_graph, -1).to(device)
  518. batch = batch.to(device)
  519. y_batch = torch.tensor(np.asarray(batch.y)).to(device)
  520. outputs, _ = reg_model(x, batch.edge_index, batch.batch)
  521. y_batch = y_batch.view(-1, 2)
  522. outputs = outputs.view(-1, 2)
  523. loss = mse(outputs, y_batch)
  524. test_loss += loss.item()
  525. print(f"==================Epoch {epoch + 1}, Test Loss: {test_loss / len(test_loader)}")
  526. test_loss_value = test_loss / len(test_loader)
  527. loss_3.append(test_loss_value)
  528. loss_all.append(loss_3)
  529. test1_loss = test_loss_value
  530. if epoch == 0:
  531. loss_min = test1_loss
  532. # else:
  533. if loss_min > test1_loss or epoch ==99 :
  534. # if epoch == 99 :
  535. # loss_all.append(loss_3)
  536. loss_min = test1_loss
  537. loss = int(loss_min)
  538. torch.save(reg_model.state_dict(),
  539. '/home/oem/oanh/GCN/fillter_by_cluster/contrastive_learning/weights/2_loss_proposal_biLSTM_GAT_{}_{}_length_128_SupCon_40channel.pt'.format(epoch, loss))
  540. # print(f"=============Epoch {epoch} - Test MSE Loss: {total_loss_test / len(test_loader):.4f}")
  541. scheduler.step(valid_loss)
  542. num_channels = 40
  543. fields = ['Epoch_channel_{}'.format(str(num_channels)), 'Train_losses', 'Val_losses', 'Test_losses']
  544. # epochs = range(n_epoch)
  545. with open('csv/Supcon_best_284.csv'.format(batch_size), 'a') as f:
  546. # using csv.writer method from CSV package
  547. write = csv.writer(f)
  548. write.writerow(fields)
  549. write.writerows(loss_all)

main.py at commit fd41dbd, no license · at the source

Overview

Authors: Thi-Oanh Ha1, Huong-Giang Doan2, Hieyong Jeong1
ORCID iDs: Thi-Oanh Ha
  1. Department of AI, Chonnam National University,Gwangju, 61186 Korea
  2. Faculty of Control and Automation, Electric Power University,Hanoi, Vietnam
Institutions: Chonnam National University (South Korea); Electric Power University (Vietnam)
Journal: Scientific reports, volume 16, issue 1, article 16492
Dates: received 26 October 2025; accepted 3 April 2026; published online 6 April 2026
Type: Research article · Language: English
License: CC BY-NC-ND
Identifiers: DOI 10.1038/s41598-026-47945-1 · PMID 41942678 · PMCID PMC13216620 · OpenAlex W7150783066
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: EEG (modality)
Methods: Machine learning, Physiology & signal measures, Connectivity, Smoothing, state filtering, decompositions
Keywords: EEG signal, Long short term memory, Convolution neural network, Graph attention network, Graph convolution network, Self-attention, Supervised contrastive learning, Computational biology and bioinformatics, Engineering, Mathematics and computing, Neuroscience
Topic: EEG and Brain-Computer Interfaces (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Citations: not cited yet (Europe PMC); 62 references in the paper

Abstract

The abstract is not reproduced here: the paper's license (CC BY-NC-ND) 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 2 matches between paragraphs and lines of code.

timeseriessignal/GACNet

License: none: the authors keep all their rights
State: the link answers, verified on 29 September 2026
Evidence: files inventoried
Commit: fd41dbdd3fc2f6e7a58006659460af03898b99ea, 31 July 2025
Languages: Python (4)
Size: 11 files, 4 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, environment (requirements.txt)
Not found: license file, CITATION.cff, tests, continuous integration, documentation
Tools: NumPy (4 files), PyTorch (3 files), scikit-learn (2 files), PyTorch Geometric (1 file), SciPy (1 file)
Availability: 1 check, the latest on 29 September 2026: the link answers
  • 29 September 2026: the link answers
5 files

Code availability statement

The paper has a code availability statement. Its license (CC BY-NC-ND) 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-026-47945-1.

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;
  • 4 scripts, each with its path and the digest of its content;
  • 2 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.

Code and data availability statement

The paper has a code and data availability statement. Its license (CC BY-NC-ND) 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-026-47945-1.

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, 3 authors, 11 keywords, 2 funders, 33 references.

Cite

This paper

Ha, T.-O., Doan, H.-G., & Jeong, H. (2026). GACNet: A graph attention-based neural network for electroencephalography localization via contrastive learning. Scientific reports, 16(1), 16492. https://doi.org/10.1038/s41598-026-47945-1

BibTeX

@article{ha2026gacnet,
author = {Ha, Thi-Oanh and Doan, Huong-Giang and Jeong, Hieyong},
title = {{GACNet: A graph attention-based neural network for electroencephalography localization via contrastive learning}},
journal = {Scientific reports},
year = {2026},
month = apr,
volume = {16},
number = {1},
pages = {16492},
publisher = {Nature Publishing Group},
issn = {2045-2322},
doi = {10.1038/s41598-026-47945-1},
url = {https://doi.org/10.1038/s41598-026-47945-1},
pmid = {41942678},
pmcid = {PMC13216620}
}

RIS

TY - JOUR
AU - Ha, Thi-Oanh
AU - Doan, Huong-Giang
AU - Jeong, Hieyong
TI - GACNet: A graph attention-based neural network for electroencephalography localization via contrastive learning
T2 - Scientific reports
J2 - Sci Rep
PY - 2026
DA - 2026/04/06
VL - 16
IS - 1
SP - 16492
SN - 2045-2322
PB - Nature Publishing Group
DO - 10.1038/s41598-026-47945-1
UR - https://doi.org/10.1038/s41598-026-47945-1
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41598-026-47945-1",
"type": "article-journal",
"title": "GACNet: A graph attention-based neural network for electroencephalography localization via contrastive learning",
"container-title": "Scientific reports",
"author": [
{
"family": "Ha",
"given": "Thi-Oanh"
},
{
"family": "Doan",
"given": "Huong-Giang"
},
{
"family": "Jeong",
"given": "Hieyong"
}
],
"container-title-short": "Sci Rep",
"volume": "16",
"issue": "1",
"page": "16492",
"DOI": "10.1038/s41598-026-47945-1",
"PMID": "41942678",
"PMCID": "PMC13216620",
"ISSN": "2045-2322",
"publisher": "Nature Publishing Group",
"URL": "https://doi.org/10.1038/s41598-026-47945-1",
"language": "en",
"issued": {
"date-parts": [
[
2026,
4,
6
]
]
}
}

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.1371/journal.pone.0347671 [code]
RMETNet: A cross-subject motor imagery EEG signal classification model based on TSLANet and riemannian geometry features.
Journal: PloS one
In common: PyTorch Geometric, PyTorch, scikit-learn, 2 other tools, EEG, 2 references
[2] doi:10.1371/journal.pone.0351872 [code]
Decoding visual object recognition from EEG signals.
Journal: PloS one
In common: PyTorch Geometric, PyTorch, scikit-learn, 2 other tools, EEG, 1 reference
[3] doi:10.1093/bib/bbag298 [code]
Empowering multifaceted analysis of spatial transcriptomics data with RGAST.
Journal: Briefings in bioinformatics
In common: PyTorch Geometric, PyTorch, scikit-learn, 2 other tools, 1 reference
[4] doi:10.1186/s13634-026-01330-2 [code]
Leednet: a lightweight network for event detection in EEG signals.
Journal: Journal on advances in signal processing
In common: PyTorch, scikit-learn, SciPy, 1 other tool, EEG, 2 references
[5] doi:10.3389/fnins.2026.1874302 [code]
Architecture-data matching for EEG-EMG decoding: compact deep models match classical spectral decoders on the WAY-EEG-GAL grasp-and-lift dataset.
Journal: Frontiers in neuroscience
In common: PyTorch, scikit-learn, SciPy, 1 other tool, EEG, 2 references
[6] doi:10.1038/s41746-026-02778-0 [code]
Trust-gated synthetic EEG augmentation reduces performance drops when generalizing to new patients.
Journal: NPJ digital medicine
In common: PyTorch, scikit-learn, SciPy, 1 other tool, EEG, 2 references
[7] doi:10.3390/s26103065 [code]
Subject-Wise Depression Screening from Eight-Channel Resting-State EEG Using Asymmetry-Aware Spectral Features and Connectivity Ablation.
Journal: Sensors (Basel, Switzerland)
In common: PyTorch, scikit-learn, SciPy, 1 other tool, EEG, 2 references
[8] doi:10.1002/hbm.70528 [code]
Explainable AI Insights Into EEG Classification and Its Alignment to Neural Correlates.
Journal: Human brain mapping
In common: PyTorch, scikit-learn, SciPy, 1 other tool, EEG, 2 references
[9] doi:10.3390/s26051730 [code]
SFE-GAT: Structure-Feature Evolution Graph Attention Network for Motor Imagery Decoding.
Journal: Sensors (Basel, Switzerland)
In common: PyTorch Geometric, PyTorch, SciPy, 1 other tool, EEG, 1 reference
[10] doi:10.1007/s00234-026-04103-8 [code]
Enhanced detection of subtle cortical abnormalities in focal epilepsy using 7 T MRI surface-based models and graph neural networks.
Journal: Neuroradiology
In common: PyTorch Geometric, PyTorch, scikit-learn, 2 other tools, EEG

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.