OSCR

Self-Supervised Stacked Masked Denoising Autoencoder (S<sup>2</sup>MDAE) for Brain MRI Denoising and Feature Learning.

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] § 2. Methods › 2.1. StackedMDAE Network Architecture › 2.1.4. Classifier Head ↔ new.py, lines 243–294 · score 0.65 · AdaptiveAvgPool2d, ReLU, MDAE blocks, Flatten, Dropout, Linear
  2. [2] § 2. Methods › 2.1. StackedMDAE Network Architecture › 2.1.3. MDAE Block Design ↔ new.py, lines 243–294 · score 0.62 · ReLU, MDAE block, S2MDAE, latent, encoding, dropout
  3. [3] § 2. Methods › 2.1. StackedMDAE Network Architecture › 2.1.4. Classifier Head ↔ new_one.py, lines 147–178 · score 0.57 · AdaptiveAvgPool2d, ReLU, Flatten, Dropout, Linear, MDAE
  4. [4] § 2. Methods › 2.2. Two-Phase Training Strategy › 2.2.1. Pre-Training Phase ↔ new.py, lines 316–369 · score 0.54 · ReduceLROnPlateau, training loss, scheduler, optimizer, reconstruction, blocks
  5. [5] § 3. Experiment › 3.1. Experimental Setup › 3.1.3. Implementation Details ↔ SimCLR.py, lines 52–64 · score 0.52 · random horizontal flipping, grayscale, resized, trained

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 · 734 lines · 25 KB · no license · 3 matches

  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. import torch.optim as optim
  5. from torch.utils.data import DataLoader, Dataset
  6. from torchvision import transforms, models
  7. from torchvision.utils import save_image
  8. import os
  9. import numpy as np
  10. from PIL import Image
  11. import matplotlib.pyplot as plt
  12. from sklearn.model_selection import train_test_split
  13. from sklearn.metrics import classification_report, confusion_matrix
  14. import time
  15. import copy
  16. import random
  17. # 设置设备
  18. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  19. print(f"使用设备: {device}")
  20. # 超参数配置
  21. class Config:
  22. # 数据参数
  23. data_path = r"E:\数据集\脑部影像\飞桨\Brain Tumor MRI Dataset_baiban" # 替换为实际路径
  24. batch_size = 16 # 减小批次大小以适应不同尺寸
  25. patch_size = 16
  26. num_workers = 2
  27. # 模型参数
  28. latent_dim = 128
  29. hidden_dims = [64, 128, 256] # 每层的隐藏维度
  30. dropout_rate = 0.1
  31. # 训练参数
  32. num_epochs_pretrain = 30
  33. num_epochs_finetune = 50
  34. learning_rate_pretrain = 1e-5
  35. learning_rate_finetune = 5e-6
  36. weight_decay = 1e-5
  37. # 噪声和掩码参数
  38. mask_ratio = 0.75 # 掩码比例
  39. noise_std = 0.1 # 高斯噪声标准差
  40. # 图像处理参数
  41. target_size = 224 # 统一调整到的尺寸
  42. # 保存路径
  43. save_dir = r"E:\数据集\脑部影像\飞桨\Brain Tumor MRI Dataset_baiban_new"
  44. model_dir = "./models"
  45. config = Config()
  46. # 创建保存目录
  47. os.makedirs(config.save_dir, exist_ok=True)
  48. os.makedirs(config.model_dir, exist_ok=True)
  49. # 自定义数据集类
  50. class BrainMRIDataset(Dataset):
  51. def __init__(self, root_dir, transform=None, is_train=True, add_noise=True):
  52. self.root_dir = root_dir
  53. self.transform = transform
  54. self.add_noise = add_noise
  55. self.classes = ['glioma', 'meningioma', 'notumor', 'pituitary']
  56. self.class_to_idx = {cls_name: i for i, cls_name in enumerate(self.classes)}
  57. self.image_paths = []
  58. self.labels = []
  59. # 遍历目录收集图像路径和标签
  60. for cls_name in self.classes:
  61. cls_dir = os.path.join(root_dir, cls_name)
  62. if os.path.exists(cls_dir):
  63. for img_name in os.listdir(cls_dir):
  64. if img_name.endswith(('.png', '.jpg', '.jpeg')):
  65. self.image_paths.append(os.path.join(cls_dir, img_name))
  66. self.labels.append(self.class_to_idx[cls_name])
  67. print(f"在 {root_dir} 中找到 {len(self.image_paths)} 张图像")
  68. def __len__(self):
  69. return len(self.image_paths)
  70. def __getitem__(self, idx):
  71. img_path = self.image_paths[idx]
  72. image = Image.open(img_path).convert('L') # 转换为灰度图
  73. # 调整图像大小
  74. image = image.resize((config.target_size, config.target_size))
  75. # 应用转换
  76. if self.transform:
  77. image_tensor = self.transform(image)
  78. else:
  79. image_tensor = transforms.ToTensor()(image)
  80. # 添加噪声(如果启用)
  81. clean_image = image_tensor.clone()
  82. if self.add_noise:
  83. noise = torch.randn_like(clean_image) * config.noise_std
  84. noisy_image = clean_image + noise
  85. noisy_image = torch.clamp(noisy_image, 0, 1)
  86. else:
  87. noisy_image = clean_image.clone()
  88. return noisy_image, clean_image, self.labels[idx]
  89. # 数据增强和转换
  90. train_transform = transforms.Compose([
  91. transforms.RandomHorizontalFlip(),
  92. transforms.RandomRotation(10),
  93. transforms.ToTensor(),
  94. ])
  95. val_transform = transforms.Compose([
  96. transforms.ToTensor(),
  97. ])
  98. # 创建数据加载器
  99. print("正在创建数据集...")
  100. train_dataset = BrainMRIDataset(
  101. root_dir=os.path.join(config.data_path, "train"),
  102. transform=train_transform,
  103. add_noise=True
  104. )
  105. val_dataset = BrainMRIDataset(
  106. root_dir=os.path.join(config.data_path, "val"),
  107. transform=val_transform,
  108. add_noise=True
  109. )
  110. print("正在创建数据加载器...")
  111. train_loader = DataLoader(
  112. train_dataset,
  113. batch_size=config.batch_size,
  114. shuffle=True,
  115. num_workers=config.num_workers
  116. )
  117. val_loader = DataLoader(
  118. val_dataset,
  119. batch_size=config.batch_size,
  120. shuffle=False,
  121. num_workers=config.num_workers
  122. )
  123. # 编码器块
  124. class EncoderBlock(nn.Module):
  125. def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1):
  126. super(EncoderBlock, self).__init__()
  127. self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding)
  128. self.bn = nn.BatchNorm2d(out_channels)
  129. self.relu = nn.ReLU(inplace=True)
  130. self.dropout = nn.Dropout2d(config.dropout_rate)
  131. def forward(self, x):
  132. x = self.conv(x)
  133. x = self.bn(x)
  134. x = self.relu(x)
  135. x = self.dropout(x)
  136. return x
  137. # 解码器块
  138. class DecoderBlock(nn.Module):
  139. def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, output_padding=0):
  140. super(DecoderBlock, self).__init__()
  141. self.conv_transpose = nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding,
  142. output_padding)
  143. self.bn = nn.BatchNorm2d(out_channels)
  144. self.relu = nn.ReLU(inplace=True)
  145. self.dropout = nn.Dropout2d(config.dropout_rate)
  146. def forward(self, x):
  147. x = self.conv_transpose(x)
  148. x = self.bn(x)
  149. x = self.relu(x)
  150. x = self.dropout(x)
  151. return x
  152. # 单个掩码去噪自编码器块
  153. class MDAE_Block(nn.Module):
  154. def __init__(self, in_channels, latent_dim):
  155. super(MDAE_Block, self).__init__()
  156. self.in_channels = in_channels
  157. self.latent_dim = latent_dim
  158. # 编码器
  159. self.encoder = nn.Sequential(
  160. EncoderBlock(in_channels, 64),
  161. EncoderBlock(64, 128),
  162. EncoderBlock(128, latent_dim),
  163. )
  164. # 可学习的掩码token
  165. self.mask_token = nn.Parameter(torch.randn(1, latent_dim, 1, 1))
  166. # 解码器
  167. self.decoder = nn.Sequential(
  168. DecoderBlock(latent_dim, 128),
  169. DecoderBlock(128, 64),
  170. nn.Conv2d(64, in_channels, kernel_size=3, stride=1, padding=1),
  171. nn.Sigmoid() # 输出在0-1之间
  172. )
  173. def forward(self, x, mask=None):
  174. batch_size, _, h, w = x.shape
  175. # 如果没有提供掩码,创建一个全1的掩码
  176. if mask is None:
  177. mask = torch.ones(batch_size, 1, h, w, device=x.device)
  178. # 应用掩码
  179. masked_x = x * mask
  180. # 编码
  181. encoded = self.encoder(masked_x)
  182. # 准备解码器输入:用mask_token填充被掩码的位置
  183. _, c, eh, ew = encoded.shape
  184. mask_token_expanded = self.mask_token.expand(batch_size, -1, eh, ew)
  185. # 调整掩码大小以匹配编码后的特征
  186. resized_mask = F.interpolate(mask, size=(eh, ew), mode='nearest')
  187. decoder_input = encoded * resized_mask + mask_token_expanded * (1 - resized_mask)
  188. # 解码
  189. reconstructed = self.decoder(decoder_input)
  190. reconstructed = F.interpolate(reconstructed, size=(h, w), mode='bilinear', align_corners=False)
  191. return reconstructed, encoded
  192. # 堆叠的S²MDAE模型
  193. class StackedMDAE(nn.Module):
  194. def __init__(self, hidden_dims, num_classes=4):
  195. super(StackedMDAE, self).__init__()
  196. self.hidden_dims = hidden_dims
  197. self.num_classes = num_classes
  198. # 创建多个MDAE块
  199. self.blocks = nn.ModuleList()
  200. in_channels = 1 # 输入是灰度图像
  201. for i, latent_dim in enumerate(hidden_dims):
  202. self.blocks.append(MDAE_Block(in_channels, latent_dim))
  203. in_channels = latent_dim # 下一层的输入是当前层的潜在维度
  204. # 分类头
  205. self.classifier = nn.Sequential(
  206. nn.AdaptiveAvgPool2d(1),
  207. nn.Flatten(),
  208. nn.Linear(hidden_dims[-1], 512),
  209. nn.ReLU(inplace=True),
  210. nn.Dropout(config.dropout_rate),
  211. nn.Linear(512, num_classes)
  212. )
  213. def forward(self, x, masks=None):
  214. if masks is None:
  215. masks = [None] * len(self.blocks)
  216. reconstructions = []
  217. features = []
  218. # 逐层前向传播
  219. for i, block in enumerate(self.blocks):
  220. recon, feat = block(x, masks[i])
  221. reconstructions.append(recon)
  222. features.append(feat)
  223. x = feat # 下一层的输入是当前层的特征
  224. # 分类
  225. cls_output = self.classifier(features[-1])
  226. return reconstructions, features, cls_output
  227. def encode(self, x):
  228. """提取特征用于下游任务"""
  229. features = []
  230. for i, block in enumerate(self.blocks):
  231. _, feat = block.encoder(x)
  232. features.append(feat)
  233. x = feat
  234. return features
  235. # 生成随机掩码
  236. def generate_mask(batch_size, height, width, mask_ratio=0.75):
  237. """生成随机二进制掩码"""
  238. num_pixels = height * width
  239. num_mask = int(num_pixels * mask_ratio)
  240. masks = []
  241. for _ in range(batch_size):
  242. # 创建全1掩码
  243. mask = torch.ones(1, height, width, device=device)
  244. # 随机选择要掩码的位置
  245. mask_indices = torch.randperm(num_pixels, device=device)[:num_mask]
  246. # 将选中的位置设置为0
  247. mask.view(-1)[mask_indices] = 0
  248. masks.append(mask)
  249. return torch.stack(masks)
  250. # 训练函数 - 预训练阶段
  251. def pretrain(model, train_loader, val_loader, optimizer, criterion, num_epochs):
  252. model.train()
  253. best_loss = float('inf')
  254. train_losses = []
  255. val_losses = []
  256. # 添加学习率调度器
  257. scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
  258. optimizer, mode='min', factor=0.5, patience=3
  259. )
  260. for epoch in range(num_epochs):
  261. epoch_start_time = time.time()
  262. running_loss = 0.0
  263. # 训练阶段
  264. for i, (noisy_imgs, clean_imgs, _) in enumerate(train_loader):
  265. noisy_imgs = noisy_imgs.to(device)
  266. clean_imgs = clean_imgs.to(device)
  267. # 为每一层生成掩码 - 使用输入图像的大小
  268. masks = []
  269. h, w = noisy_imgs.shape[2], noisy_imgs.shape[3]
  270. for _ in range(len(model.blocks)):
  271. mask = generate_mask(noisy_imgs.size(0), h, w, config.mask_ratio)
  272. masks.append(mask)
  273. # 前向传播
  274. optimizer.zero_grad()
  275. reconstructions, features, _ = model(noisy_imgs, masks)
  276. # 计算重建损失
  277. loss = 0
  278. for j, recon in enumerate(reconstructions):
  279. mask = masks[j]
  280. resized_mask = F.interpolate(mask, size=recon.shape[2:], mode='nearest')
  281. # 确保目标与重建输出的通道数相同
  282. if j == 0:
  283. # 扩展原始图像的通道数以匹配重建输出
  284. expanded_clean_imgs = clean_imgs.expand_as(recon)
  285. target = expanded_clean_imgs
  286. else:
  287. # 后续层应与前一层的特征比较
  288. target = features[j - 1]
  289. if target.shape[1] != recon.shape[1]:
  290. # 如果通道数不匹配,使用1x1卷积调整
  291. if not hasattr(model, f'adaptor_{j}'):
  292. setattr(model, f'adaptor_{j}',
  293. nn.Conv2d(target.shape[1], recon.shape[1], 1).to(device))
  294. adaptor = getattr(model, f'adaptor_{j}')
  295. target = adaptor(target)
  296. # 调整目标大小以匹配重建输出
  297. if target.shape[2:] != recon.shape[2:]:
  298. target = F.interpolate(target, size=recon.shape[2:], mode='nearest')
  299. # 只计算被掩码区域的MSE损失
  300. mask_loss = criterion(recon * (1 - resized_mask), target * (1 - resized_mask))
  301. loss += mask_loss
  302. # 检查梯度范数
  303. loss.backward()
  304. total_norm = 0
  305. for p in model.parameters():
  306. if p.grad is not None:
  307. param_norm = p.grad.data.norm(2)
  308. total_norm += param_norm.item() ** 2
  309. total_norm = total_norm ** (1. / 2)
  310. # 如果梯度范数过大,跳过这个批次的更新
  311. if total_norm > 100:
  312. print(f'Skipping batch due to large gradient: {total_norm:.4f}')
  313. optimizer.zero_grad()
  314. continue
  315. # 梯度裁剪
  316. torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
  317. optimizer.step()
  318. running_loss += loss.item()
  319. if i % 10 == 0:
  320. print(
  321. f'Epoch [{epoch + 1}/{num_epochs}], Step [{i + 1}/{len(train_loader)}], Loss: {loss.item():.4f}, Grad Norm: {total_norm:.4f}')
  322. # 验证阶段
  323. val_loss = 0.0
  324. model.eval()
  325. with torch.no_grad():
  326. for noisy_imgs, clean_imgs, _ in val_loader:
  327. noisy_imgs = noisy_imgs.to(device)
  328. clean_imgs = clean_imgs.to(device)
  329. # 为每一层生成掩码 - 使用输入图像的大小
  330. masks = []
  331. h, w = noisy_imgs.shape[2], noisy_imgs.shape[3]
  332. for _ in range(len(model.blocks)):
  333. mask = generate_mask(noisy_imgs.size(0), h, w, config.mask_ratio)
  334. masks.append(mask)
  335. reconstructions, features, _ = model(noisy_imgs, masks)
  336. # 计算验证损失
  337. batch_val_loss = 0
  338. for j, recon in enumerate(reconstructions):
  339. mask = masks[j]
  340. resized_mask = F.interpolate(mask, size=recon.shape[2:], mode='nearest')
  341. if j == 0:
  342. expanded_clean_imgs = clean_imgs.expand_as(recon)
  343. target = expanded_clean_imgs
  344. else:
  345. target = features[j - 1]
  346. if target.shape[1] != recon.shape[1]:
  347. if not hasattr(model, f'adaptor_{j}'):
  348. setattr(model, f'adaptor_{j}',
  349. nn.Conv2d(target.shape[1], recon.shape[1], 1).to(device))
  350. adaptor = getattr(model, f'adaptor_{j}')
  351. target = adaptor(target)
  352. if target.shape[2:] != recon.shape[2:]:
  353. target = F.interpolate(target, size=recon.shape[2:], mode='nearest')
  354. batch_val_loss += criterion(recon * (1 - resized_mask), target * (1 - resized_mask)).item()
  355. val_loss += batch_val_loss
  356. # 计算平均损失
  357. avg_train_loss = running_loss / len(train_loader)
  358. avg_val_loss = val_loss / len(val_loader)
  359. train_losses.append(avg_train_loss)
  360. val_losses.append(avg_val_loss)
  361. # 更新学习率
  362. scheduler.step(avg_val_loss)
  363. current_lr = optimizer.param_groups[0]['lr']
  364. print(f'Current learning rate: {current_lr:.2e}')
  365. epoch_time = time.time() - epoch_start_time
  366. print(f'Epoch [{epoch + 1}/{num_epochs}] completed in {epoch_time:.2f}s')
  367. print(f'Training Loss: {avg_train_loss:.4f}, Validation Loss: {avg_val_loss:.4f}')
  368. # 保存最佳模型
  369. if avg_val_loss < best_loss:
  370. best_loss = avg_val_loss
  371. torch.save(model.state_dict(), os.path.join(config.model_dir, 'best_pretrain_model.pth'))
  372. print('Best model saved!')
  373. # 保存一些重建样本用于可视化
  374. if epoch % 5 == 0:
  375. model.eval()
  376. with torch.no_grad():
  377. noisy_imgs, clean_imgs, _ = next(iter(val_loader))
  378. noisy_imgs = noisy_imgs.to(device)
  379. clean_imgs = clean_imgs.to(device)
  380. # 为每一层生成掩码 - 使用输入图像的大小
  381. masks = []
  382. h, w = noisy_imgs.shape[2], noisy_imgs.shape[3]
  383. for _ in range(len(model.blocks)):
  384. mask = generate_mask(noisy_imgs.size(0), h, w, config.mask_ratio)
  385. masks.append(mask)
  386. reconstructions, _, _ = model(noisy_imgs, masks)
  387. # 保存输入、噪声、重建和原始图像
  388. save_image(torch.cat([
  389. noisy_imgs[:8],
  390. reconstructions[0][:8],
  391. clean_imgs[:8]
  392. ]), os.path.join(config.save_dir, f'reconstruction_epoch_{epoch + 1}.png'), nrow=8)
  393. # 绘制损失曲线
  394. plt.figure(figsize=(10, 5))
  395. plt.plot(train_losses, label='Training Loss')
  396. plt.plot(val_losses, label='Validation Loss')
  397. plt.xlabel('Epochs')
  398. plt.ylabel('Loss')
  399. plt.legend()
  400. plt.savefig(os.path.join(config.save_dir, 'pretrain_loss_curve.png'))
  401. plt.close()
  402. return train_losses, val_losses
  403. # 训练函数 - 微调阶段
  404. def finetune(model, train_loader, val_loader, optimizer, criterion, num_epochs):
  405. model.train()
  406. best_acc = 0.0
  407. train_losses = []
  408. val_losses = []
  409. train_accs = []
  410. val_accs = []
  411. for epoch in range(num_epochs):
  412. epoch_start_time = time.time()
  413. running_loss = 0.0
  414. correct = 0
  415. total = 0
  416. # 训练阶段
  417. for i, (noisy_imgs, clean_imgs, labels) in enumerate(train_loader):
  418. clean_imgs = clean_imgs.to(device)
  419. labels = labels.to(device)
  420. # 前向传播
  421. optimizer.zero_grad()
  422. _, _, cls_output = model(clean_imgs)
  423. # 计算分类损失
  424. loss = criterion(cls_output, labels)
  425. # 反向传播和优化
  426. loss.backward()
  427. torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
  428. optimizer.step()
  429. running_loss += loss.item()
  430. # 计算准确率
  431. _, predicted = torch.max(cls_output.data, 1)
  432. total += labels.size(0)
  433. correct += (predicted == labels).sum().item()
  434. if i % 10 == 0:
  435. acc = 100 * correct / total
  436. print(
  437. f'Epoch [{epoch + 1}/{num_epochs}], Step [{i + 1}/{len(train_loader)}], Loss: {loss.item():.4f}, Acc: {acc:.2f}%')
  438. # 验证阶段
  439. val_loss = 0.0
  440. val_correct = 0
  441. val_total = 0
  442. model.eval()
  443. with torch.no_grad():
  444. for _, clean_imgs, labels in val_loader:
  445. clean_imgs = clean_imgs.to(device)
  446. labels = labels.to(device)
  447. _, _, cls_output = model(clean_imgs)
  448. # 计算验证损失
  449. val_loss += criterion(cls_output, labels).item()
  450. # 计算验证准确率
  451. _, predicted = torch.max(cls_output.data, 1)
  452. val_total += labels.size(0)
  453. val_correct += (predicted == labels).sum().item()
  454. # 计算平均损失和准确率
  455. avg_train_loss = running_loss / len(train_loader)
  456. avg_val_loss = val_loss / len(val_loader)
  457. train_acc = 100 * correct / total
  458. val_acc = 100 * val_correct / val_total
  459. train_losses.append(avg_train_loss)
  460. val_losses.append(avg_val_loss)
  461. train_accs.append(train_acc)
  462. val_accs.append(val_acc)
  463. epoch_time = time.time() - epoch_start_time
  464. print(f'Epoch [{epoch + 1}/{num_epochs}] completed in {epoch_time:.2f}s')
  465. print(f'Training Loss: {avg_train_loss:.4f}, Training Acc: {train_acc:.2f}%')
  466. print(f'Validation Loss: {avg_val_loss:.4f}, Validation Acc: {val_acc:.2f}%')
  467. # 保存最佳模型
  468. if val_acc > best_acc:
  469. best_acc = val_acc
  470. torch.save(model.state_dict(), os.path.join(config.model_dir, 'best_finetune_model.pth'))
  471. print('Best model saved!')
  472. # 绘制损失和准确率曲线
  473. plt.figure(figsize=(12, 5))
  474. plt.subplot(1, 2, 1)
  475. plt.plot(train_losses, label='Training Loss')
  476. plt.plot(val_losses, label='Validation Loss')
  477. plt.xlabel('Epochs')
  478. plt.ylabel('Loss')
  479. plt.legend()
  480. plt.subplot(1, 2, 2)
  481. plt.plot(train_accs, label='Training Accuracy')
  482. plt.plot(val_accs, label='Validation Accuracy')
  483. plt.xlabel('Epochs')
  484. plt.ylabel('Accuracy (%)')
  485. plt.legend()
  486. plt.savefig(os.path.join(config.save_dir, 'finetune_curves.png'))
  487. plt.close()
  488. return train_losses, val_losses, train_accs, val_accs
  489. # 评估函数
  490. def evaluate_model(model, test_loader):
  491. model.eval()
  492. all_preds = []
  493. all_labels = []
  494. with torch.no_grad():
  495. for _, clean_imgs, labels in test_loader:
  496. clean_imgs = clean_imgs.to(device)
  497. labels = labels.to(device)
  498. _, _, cls_output = model(clean_imgs)
  499. _, preds = torch.max(cls_output, 1)
  500. all_preds.extend(preds.cpu().numpy())
  501. all_labels.extend(labels.cpu().numpy())
  502. # 计算评估指标
  503. print("Classification Report:")
  504. print(classification_report(all_labels, all_preds, target_names=train_dataset.classes,digits=5))
  505. # 绘制混淆矩阵
  506. cm = confusion_matrix(all_labels, all_preds)
  507. plt.figure(figsize=(8, 6))
  508. plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)
  509. plt.title('Confusion Matrix')
  510. plt.colorbar()
  511. tick_marks = np.arange(len(train_dataset.classes))
  512. plt.xticks(tick_marks, train_dataset.classes, rotation=45)
  513. plt.yticks(tick_marks, train_dataset.classes)
  514. # 在矩阵中显示数值
  515. thresh = cm.max() / 2.
  516. for i in range(cm.shape[0]):
  517. for j in range(cm.shape[1]):
  518. plt.text(j, i, format(cm[i, j], 'd'),
  519. ha="center", va="center",
  520. color="white" if cm[i, j] > thresh else "black")
  521. plt.tight_layout()
  522. plt.ylabel('True label')
  523. plt.xlabel('Predicted label')
  524. plt.savefig(os.path.join(config.save_dir, 'confusion_matrix.png'))
  525. plt.close()
  526. return all_preds, all_labels
  527. # 主函数
  528. def main():
  529. # 初始化模型
  530. model = StackedMDAE(config.hidden_dims, num_classes=4).to(device)
  531. print(f"模型参数量: {sum(p.numel() for p in model.parameters()):,}")
  532. # 在模型定义后添加权重初始化
  533. def init_weights(m):
  534. if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):
  535. nn.init.xavier_uniform_(m.weight)
  536. if m.bias is not None:
  537. nn.init.constant_(m.bias, 0)
  538. elif isinstance(m, nn.BatchNorm2d):
  539. nn.init.constant_(m.weight, 1)
  540. nn.init.constant_(m.bias, 0)
  541. elif isinstance(m, nn.Linear):
  542. nn.init.xavier_uniform_(m.weight)
  543. nn.init.constant_(m.bias, 0)
  544. model.apply(init_weights)
  545. # 定义损失函数和优化器
  546. reconstruction_criterion = nn.MSELoss()
  547. classification_criterion = nn.CrossEntropyLoss()
  548. pretrain_optimizer = optim.Adam(
  549. model.parameters(),
  550. lr=config.learning_rate_pretrain,
  551. weight_decay=config.weight_decay
  552. )
  553. # 预训练阶段
  554. print("开始预训练阶段...")
  555. pretrain_losses = pretrain(
  556. model, train_loader, val_loader,
  557. pretrain_optimizer, reconstruction_criterion,
  558. config.num_epochs_pretrain
  559. )
  560. # 加载最佳预训练模型
  561. model.load_state_dict(torch.load(os.path.join(config.model_dir, 'best_pretrain_model.pth')))
  562. print("预训练完成,加载最佳模型进行微调")
  563. # 微调阶段
  564. print("开始微调阶段...")
  565. finetune_optimizer = optim.Adam(
  566. model.parameters(),
  567. lr=config.learning_rate_finetune,
  568. weight_decay=config.weight_decay
  569. )
  570. finetune_losses = finetune(
  571. model, train_loader, val_loader,
  572. finetune_optimizer, classification_criterion,
  573. config.num_epochs_finetune
  574. )
  575. # 加载最佳微调模型
  576. model.load_state_dict(torch.load(os.path.join(config.model_dir, 'best_finetune_model.pth')))
  577. print("微调完成,加载最佳模型进行评估")
  578. # 评估模型
  579. evaluate_model(model, val_loader)
  580. print("训练和评估完成!")
  581. if __name__ == "__main__":
  582. main()

new.py at commit 98c17f9, no license · at the source

Overview

Authors: Rui Li1, Puyu Zhang1, Chenglin Wen2, Guoxi Sun1
ORCID iDs: Rui Li, Puyu Zhang
  1. College of Electronic Information Engineering, Guangdong University of Petrochemical Technology, Maoming 525000, China; (R.L.); (P.Z.)
  2. Provincial Key Laboratory of Petrochemical Equipment Fault Diagnosis, Guangdong University of Petrochemical Technology, Maoming 525000, China
Journal: Sensors (Basel, Switzerland), volume 26, issue 17, article 5388
Dates: received 25 June 2026; accepted 19 August 2026; published online 26 August 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.3390/s26175388 · PMID 42740007 · PMCID PMC13568421 · OpenAlex W7204237095
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: structural MRI / diffusion (modality), human (organism), methods / tools (subfield)
Methods: Connectivity, Machine learning
Keywords: self-supervised learning, masked image modeling, denoising autoencoder, feature learning, brain MRI
MeSH: Brain*, Image Processing, Computer-Assisted*, Magnetic Resonance Imaging*, Algorithms, Autoencoder, Convolutional Neural Networks, Humans, Signal-To-Noise Ratio (* major topic)
Topic: Brain Tumor Detection and Classification (Neurology, Neuroscience), according to OpenAlex
Funding: National Key Research and Development Program of China (2023YFB4704000, 2023YFB4704005); Postgraduate Science and Technology Innovation Program of Guangdong University of Petrochemical Technology (2024KJCX043)
Citations: not cited yet (Europe PMC); 26 references in the paper

Abstract

Medical-image annotation is costly and limits the use of fully supervised learning. This study proposes the Self-Supervised Stacked Masked Denoising Autoencoder (S2MDAE) for four-class brain MRI classification. During pre-training, three convolutional encoder–decoder blocks perform layer-wise masked reconstruction under a 75% mask ratio and Gaussian corruption; the pretrained encoder stack is then fine-tuned for classification. On the primary dataset, S2MDAE achieved 87.207% Accuracy, while ablation studies supported the contributions of pre-training, masking, noise injection, and layer-wise reconstruction. Representation analysis further showed increased class separability in deeper blocks after fine-tuning. Without retraining, external evaluation on a duplicate-screened independent dataset achieved 67.254% Accuracy and 66.009% Macro-F1, indicating partial transfer under domain shift. These findings support the task-specific value of the proposed framework while showing that broader clinical generalization requires further validation.

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

Repository

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

limou66/S2MDAE

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: 98c17f9503b02d82428e4d45c8ed8b10bfcdf6a2, 17 July 2026
Languages: Python (4)
Size: 6 files, 4 scripts
Software Heritage: not archived
Found in: “Data Availability Statement”
Holds: README
Not found: license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: Matplotlib (4 files), NumPy (4 files), Pillow (4 files), PyTorch (4 files), scikit-learn (4 files)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
5 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;
  • 4 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

Datasets cited

Data Availability Statement

Third-party datasets were analyzed in this study. The primary dataset, referred to in this article as the Brain Tumor MRI Dataset, was obtained from the Baidu AI Studio dataset platform. The dataset is not readily available through a dataset-specific persistent link because such a link could not be identified. The Baidu AI Studio dataset portal is available at https://aistudio.baidu.com/datasetoverview (accessed on 24 June 2026), and access to the original dataset is subject to the platform’s continued availability and access conditions. Further inquiries regarding the primary dataset should be directed to the first author (R.L.). The external evaluation dataset, Brain Tumor MRI Dataset (Glioma, Meningioma, Pituitary, No Tumor), Version 4, is openly available in Mendeley Data at https://doi.org/10.17632/zwr4ntf94j.4. No new patient data were collected or generated in this study. The source code used for model implementation and evaluation is openly available on GitHub at https://github.com/limou66/S2MDAE (accessed on 24 June 2026).

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

Recorded: type, language, journal, volume, issue, pages, dates, 4 authors, 5 keywords, 8 MeSH terms, 2 funders, 15 references.

Cite

This paper

Li, R., Zhang, P., Wen, C., & Sun, G. (2026). Self-Supervised Stacked Masked Denoising Autoencoder (S&lt;sup&gt;2&lt;/sup&gt;MDAE) for Brain MRI Denoising and Feature Learning. Sensors (Basel, Switzerland), 26(17), 5388. https://doi.org/10.3390/s26175388

BibTeX

@article{li2026self,
author = {Li, Rui and Zhang, Puyu and Wen, Chenglin and Sun, Guoxi},
title = {{Self-Supervised Stacked Masked Denoising Autoencoder (S\&lt;sup\&gt;2\&lt;/sup\&gt;MDAE) for Brain MRI Denoising and Feature Learning}},
journal = {Sensors (Basel, Switzerland)},
year = {2026},
month = aug,
volume = {26},
number = {17},
pages = {5388},
publisher = {Multidisciplinary Digital Publishing Institute (MDPI)},
issn = {1424-8220},
doi = {10.3390/s26175388},
url = {https://doi.org/10.3390/s26175388},
pmid = {42740007},
pmcid = {PMC13568421}
}

RIS

TY - JOUR
AU - Li, Rui
AU - Zhang, Puyu
AU - Wen, Chenglin
AU - Sun, Guoxi
TI - Self-Supervised Stacked Masked Denoising Autoencoder (S&lt;sup&gt;2&lt;/sup&gt;MDAE) for Brain MRI Denoising and Feature Learning
T2 - Sensors (Basel, Switzerland)
J2 - Sensors (Basel)
PY - 2026
DA - 2026/08/26
VL - 26
IS - 17
SP - 5388
SN - 1424-8220
PB - Multidisciplinary Digital Publishing Institute (MDPI)
DO - 10.3390/s26175388
UR - https://doi.org/10.3390/s26175388
LA - en
ER -

CSL-JSON

{
"id": "10.3390/s26175388",
"type": "article-journal",
"title": "Self-Supervised Stacked Masked Denoising Autoencoder (S&lt;sup&gt;2&lt;/sup&gt;MDAE) for Brain MRI Denoising and Feature Learning",
"container-title": "Sensors (Basel, Switzerland)",
"author": [
{
"family": "Li",
"given": "Rui"
},
{
"family": "Zhang",
"given": "Puyu"
},
{
"family": "Wen",
"given": "Chenglin"
},
{
"family": "Sun",
"given": "Guoxi"
}
],
"container-title-short": "Sensors (Basel)",
"volume": "26",
"issue": "17",
"page": "5388",
"DOI": "10.3390/s26175388",
"PMID": "42740007",
"PMCID": "PMC13568421",
"ISSN": "1424-8220",
"publisher": "Multidisciplinary Digital Publishing Institute (MDPI)",
"URL": "https://doi.org/10.3390/s26175388",
"language": "en",
"issued": {
"date-parts": [
[
2026,
8,
26
]
]
}
}

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.3390/jimaging12070276 [code]
Hyperelastic Regularization for Near-Diffeomorphic Transformer-Based Brain MRI Registration.
Journal: Journal of imaging
In common: Pillow, PyTorch, scikit-learn, 2 other tools, methods / tools, structural MRI / diffusion
[2] doi:10.7554/elife.110588 [code]
Opening the black box toward a modular approach to spike sorting.
Journal: eLife
In common: Pillow, PyTorch, scikit-learn, 2 other tools, methods / tools
[3] doi:10.1038/s41598-026-61605-4 [code]
Learning precise segmentation of neurofibrillary tangles from rapid manual point annotations.
Journal: Scientific reports
In common: Pillow, PyTorch, scikit-learn, 2 other tools, methods / tools
[4] doi:10.1038/s41592-026-03194-8 [code]
Beyond benchmarking: an expert-guided consensus approach to spatially aware clustering.
Journal: Nature methods
In common: Pillow, PyTorch, scikit-learn, 2 other tools, methods / tools
[5] doi:10.1093/bioinformatics/btag540 [code]
Deciphering spatial heterogeneity by multimodal spatial transcriptomics modelling with SpatialModal.
Journal: Bioinformatics (Oxford, England)
In common: Pillow, PyTorch, scikit-learn, 2 other tools, methods / tools
[6] doi:10.1007/s12021-026-09803-3 [code]
NeuroFusion: A Unified Framework for Generalized Visual Stimulus Decoding from fMRI Across Datasets and Subjects.
Journal: Neuroinformatics
In common: Pillow, PyTorch, scikit-learn, 2 other tools, methods / tools
[7] doi:10.1186/s13059-026-04125-8 [code]
MLMarker: a machine learning framework for tissue inference and biomarker discovery.
Journal: Genome biology
In common: Pillow, PyTorch, scikit-learn, 2 other tools, methods / tools
[8] doi:10.1371/journal.pcbi.1013499 [code]
VesiclePy: A machine learning vesicle analysis toolbox for volume electron microscopy.
Journal: PLoS computational biology
In common: Pillow, PyTorch, scikit-learn, 2 other tools, methods / tools
[9] doi:10.1371/journal.pone.0347867 [code]
LiteFeatNet: A parameter-efficient and performance-centric deep learning model for multi-ocular disease identification using intermediate feature reduction from fundus images.
Journal: PloS one
In common: Pillow, PyTorch, scikit-learn, 2 other tools, methods / tools
[10] doi:10.1186/s13244-026-02365-7 [code]
Super-resolution MRI and 2.5D deep learning for intratumoral-peritumoral radiomics in preoperative prediction of rectal cancer perineural invasion.
Journal: Insights into imaging
In common: Pillow, PyTorch, scikit-learn, 2 other tools, structural MRI / diffusion

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.