Self-Supervised Stacked Masked Denoising Autoencoder (S<sup>2</sup>MDAE) for Brain MRI Denoising and Feature Learning.
The 5 matches
- [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. 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] § 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] § 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] § 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
- import torch
- import torch.nn as nn
- import torch.nn.functional as F
- import torch.optim as optim
- from torch.utils.data import DataLoader, Dataset
- from torchvision import transforms, models
- from torchvision.utils import save_image
- import os
- import numpy as np
- from PIL import Image
- import matplotlib.pyplot as plt
- from sklearn.model_selection import train_test_split
- from sklearn.metrics import classification_report, confusion_matrix
- import time
- import copy
- import random
- # 设置设备
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
- print(f"使用设备: {device}")
- # 超参数配置
- class Config:
- # 数据参数
- data_path = r"E:\数据集\脑部影像\飞桨\Brain Tumor MRI Dataset_baiban" # 替换为实际路径
- batch_size = 16 # 减小批次大小以适应不同尺寸
- patch_size = 16
- num_workers = 2
- # 模型参数
- latent_dim = 128
- hidden_dims = [64, 128, 256] # 每层的隐藏维度
- dropout_rate = 0.1
- # 训练参数
- num_epochs_pretrain = 30
- num_epochs_finetune = 50
- learning_rate_pretrain = 1e-5
- learning_rate_finetune = 5e-6
- weight_decay = 1e-5
- # 噪声和掩码参数
- mask_ratio = 0.75 # 掩码比例
- noise_std = 0.1 # 高斯噪声标准差
- # 图像处理参数
- target_size = 224 # 统一调整到的尺寸
- # 保存路径
- save_dir = r"E:\数据集\脑部影像\飞桨\Brain Tumor MRI Dataset_baiban_new"
- model_dir = "./models"
- config = Config()
- # 创建保存目录
- os.makedirs(config.save_dir, exist_ok=True)
- os.makedirs(config.model_dir, exist_ok=True)
- # 自定义数据集类
- class BrainMRIDataset(Dataset):
- def __init__(self, root_dir, transform=None, is_train=True, add_noise=True):
- self.root_dir = root_dir
- self.transform = transform
- self.add_noise = add_noise
- self.classes = ['glioma', 'meningioma', 'notumor', 'pituitary']
- self.class_to_idx = {cls_name: i for i, cls_name in enumerate(self.classes)}
- self.image_paths = []
- self.labels = []
- # 遍历目录收集图像路径和标签
- for cls_name in self.classes:
- cls_dir = os.path.join(root_dir, cls_name)
- if os.path.exists(cls_dir):
- for img_name in os.listdir(cls_dir):
- if img_name.endswith(('.png', '.jpg', '.jpeg')):
- self.image_paths.append(os.path.join(cls_dir, img_name))
- self.labels.append(self.class_to_idx[cls_name])
- print(f"在 {root_dir} 中找到 {len(self.image_paths)} 张图像")
- def __len__(self):
- return len(self.image_paths)
- def __getitem__(self, idx):
- img_path = self.image_paths[idx]
- image = Image.open(img_path).convert('L') # 转换为灰度图
- # 调整图像大小
- image = image.resize((config.target_size, config.target_size))
- # 应用转换
- if self.transform:
- image_tensor = self.transform(image)
- else:
- image_tensor = transforms.ToTensor()(image)
- # 添加噪声(如果启用)
- clean_image = image_tensor.clone()
- if self.add_noise:
- noise = torch.randn_like(clean_image) * config.noise_std
- noisy_image = clean_image + noise
- noisy_image = torch.clamp(noisy_image, 0, 1)
- else:
- noisy_image = clean_image.clone()
- return noisy_image, clean_image, self.labels[idx]
- # 数据增强和转换
- train_transform = transforms.Compose([
- transforms.RandomHorizontalFlip(),
- transforms.RandomRotation(10),
- transforms.ToTensor(),
- ])
- val_transform = transforms.Compose([
- transforms.ToTensor(),
- ])
- # 创建数据加载器
- print("正在创建数据集...")
- train_dataset = BrainMRIDataset(
- root_dir=os.path.join(config.data_path, "train"),
- transform=train_transform,
- add_noise=True
- )
- val_dataset = BrainMRIDataset(
- root_dir=os.path.join(config.data_path, "val"),
- transform=val_transform,
- add_noise=True
- )
- print("正在创建数据加载器...")
- train_loader = DataLoader(
- train_dataset,
- batch_size=config.batch_size,
- shuffle=True,
- num_workers=config.num_workers
- )
- val_loader = DataLoader(
- val_dataset,
- batch_size=config.batch_size,
- shuffle=False,
- num_workers=config.num_workers
- )
- # 编码器块
- class EncoderBlock(nn.Module):
- def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1):
- super(EncoderBlock, self).__init__()
- self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding)
- self.bn = nn.BatchNorm2d(out_channels)
- self.relu = nn.ReLU(inplace=True)
- self.dropout = nn.Dropout2d(config.dropout_rate)
- def forward(self, x):
- x = self.conv(x)
- x = self.bn(x)
- x = self.relu(x)
- x = self.dropout(x)
- return x
- # 解码器块
- class DecoderBlock(nn.Module):
- def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, output_padding=0):
- super(DecoderBlock, self).__init__()
- self.conv_transpose = nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding,
- output_padding)
- self.bn = nn.BatchNorm2d(out_channels)
- self.relu = nn.ReLU(inplace=True)
- self.dropout = nn.Dropout2d(config.dropout_rate)
- def forward(self, x):
- x = self.conv_transpose(x)
- x = self.bn(x)
- x = self.relu(x)
- x = self.dropout(x)
- return x
- # 单个掩码去噪自编码器块
- class MDAE_Block(nn.Module):
- def __init__(self, in_channels, latent_dim):
- super(MDAE_Block, self).__init__()
- self.in_channels = in_channels
- self.latent_dim = latent_dim
- # 编码器
- self.encoder = nn.Sequential(
- EncoderBlock(in_channels, 64),
- EncoderBlock(64, 128),
- EncoderBlock(128, latent_dim),
- )
- # 可学习的掩码token
- self.mask_token = nn.Parameter(torch.randn(1, latent_dim, 1, 1))
- # 解码器
- self.decoder = nn.Sequential(
- DecoderBlock(latent_dim, 128),
- DecoderBlock(128, 64),
- nn.Conv2d(64, in_channels, kernel_size=3, stride=1, padding=1),
- nn.Sigmoid() # 输出在0-1之间
- )
- def forward(self, x, mask=None):
- batch_size, _, h, w = x.shape
- # 如果没有提供掩码,创建一个全1的掩码
- if mask is None:
- mask = torch.ones(batch_size, 1, h, w, device=x.device)
- # 应用掩码
- masked_x = x * mask
- # 编码
- encoded = self.encoder(masked_x)
- # 准备解码器输入:用mask_token填充被掩码的位置
- _, c, eh, ew = encoded.shape
- mask_token_expanded = self.mask_token.expand(batch_size, -1, eh, ew)
- # 调整掩码大小以匹配编码后的特征
- resized_mask = F.interpolate(mask, size=(eh, ew), mode='nearest')
- decoder_input = encoded * resized_mask + mask_token_expanded * (1 - resized_mask)
- # 解码
- reconstructed = self.decoder(decoder_input)
- reconstructed = F.interpolate(reconstructed, size=(h, w), mode='bilinear', align_corners=False)
- return reconstructed, encoded
- # 堆叠的S²MDAE模型
- class StackedMDAE(nn.Module):
- def __init__(self, hidden_dims, num_classes=4):
- super(StackedMDAE, self).__init__()
- self.hidden_dims = hidden_dims
- self.num_classes = num_classes
- # 创建多个MDAE块
- self.blocks = nn.ModuleList()
- in_channels = 1 # 输入是灰度图像
- for i, latent_dim in enumerate(hidden_dims):
- self.blocks.append(MDAE_Block(in_channels, latent_dim))
- in_channels = latent_dim # 下一层的输入是当前层的潜在维度
- # 分类头
- self.classifier = nn.Sequential(
- nn.AdaptiveAvgPool2d(1),
- nn.Flatten(),
- nn.Linear(hidden_dims[-1], 512),
- nn.ReLU(inplace=True),
- nn.Dropout(config.dropout_rate),
- nn.Linear(512, num_classes)
- )
- def forward(self, x, masks=None):
- if masks is None:
- masks = [None] * len(self.blocks)
- reconstructions = []
- features = []
- # 逐层前向传播
- for i, block in enumerate(self.blocks):
- recon, feat = block(x, masks[i])
- reconstructions.append(recon)
- features.append(feat)
- x = feat # 下一层的输入是当前层的特征
- # 分类
- cls_output = self.classifier(features[-1])
- return reconstructions, features, cls_output
- def encode(self, x):
- """提取特征用于下游任务"""
- features = []
- for i, block in enumerate(self.blocks):
- _, feat = block.encoder(x)
- features.append(feat)
- x = feat
- return features
- # 生成随机掩码
- def generate_mask(batch_size, height, width, mask_ratio=0.75):
- """生成随机二进制掩码"""
- num_pixels = height * width
- num_mask = int(num_pixels * mask_ratio)
- masks = []
- for _ in range(batch_size):
- # 创建全1掩码
- mask = torch.ones(1, height, width, device=device)
- # 随机选择要掩码的位置
- mask_indices = torch.randperm(num_pixels, device=device)[:num_mask]
- # 将选中的位置设置为0
- mask.view(-1)[mask_indices] = 0
- masks.append(mask)
- return torch.stack(masks)
- # 训练函数 - 预训练阶段
- def pretrain(model, train_loader, val_loader, optimizer, criterion, num_epochs):
- model.train()
- best_loss = float('inf')
- train_losses = []
- val_losses = []
- # 添加学习率调度器
- scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
- optimizer, mode='min', factor=0.5, patience=3
- )
- for epoch in range(num_epochs):
- epoch_start_time = time.time()
- running_loss = 0.0
- # 训练阶段
- for i, (noisy_imgs, clean_imgs, _) in enumerate(train_loader):
- noisy_imgs = noisy_imgs.to(device)
- clean_imgs = clean_imgs.to(device)
- # 为每一层生成掩码 - 使用输入图像的大小
- masks = []
- h, w = noisy_imgs.shape[2], noisy_imgs.shape[3]
- for _ in range(len(model.blocks)):
- mask = generate_mask(noisy_imgs.size(0), h, w, config.mask_ratio)
- masks.append(mask)
- # 前向传播
- optimizer.zero_grad()
- reconstructions, features, _ = model(noisy_imgs, masks)
- # 计算重建损失
- loss = 0
- for j, recon in enumerate(reconstructions):
- mask = masks[j]
- resized_mask = F.interpolate(mask, size=recon.shape[2:], mode='nearest')
- # 确保目标与重建输出的通道数相同
- if j == 0:
- # 扩展原始图像的通道数以匹配重建输出
- expanded_clean_imgs = clean_imgs.expand_as(recon)
- target = expanded_clean_imgs
- else:
- # 后续层应与前一层的特征比较
- target = features[j - 1]
- if target.shape[1] != recon.shape[1]:
- # 如果通道数不匹配,使用1x1卷积调整
- if not hasattr(model, f'adaptor_{j}'):
- setattr(model, f'adaptor_{j}',
- nn.Conv2d(target.shape[1], recon.shape[1], 1).to(device))
- adaptor = getattr(model, f'adaptor_{j}')
- target = adaptor(target)
- # 调整目标大小以匹配重建输出
- if target.shape[2:] != recon.shape[2:]:
- target = F.interpolate(target, size=recon.shape[2:], mode='nearest')
- # 只计算被掩码区域的MSE损失
- mask_loss = criterion(recon * (1 - resized_mask), target * (1 - resized_mask))
- loss += mask_loss
- # 检查梯度范数
- loss.backward()
- total_norm = 0
- for p in model.parameters():
- if p.grad is not None:
- param_norm = p.grad.data.norm(2)
- total_norm += param_norm.item() ** 2
- total_norm = total_norm ** (1. / 2)
- # 如果梯度范数过大,跳过这个批次的更新
- if total_norm > 100:
- print(f'Skipping batch due to large gradient: {total_norm:.4f}')
- optimizer.zero_grad()
- continue
- # 梯度裁剪
- torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
- optimizer.step()
- running_loss += loss.item()
- if i % 10 == 0:
- print(
- f'Epoch [{epoch + 1}/{num_epochs}], Step [{i + 1}/{len(train_loader)}], Loss: {loss.item():.4f}, Grad Norm: {total_norm:.4f}')
- # 验证阶段
- val_loss = 0.0
- model.eval()
- with torch.no_grad():
- for noisy_imgs, clean_imgs, _ in val_loader:
- noisy_imgs = noisy_imgs.to(device)
- clean_imgs = clean_imgs.to(device)
- # 为每一层生成掩码 - 使用输入图像的大小
- masks = []
- h, w = noisy_imgs.shape[2], noisy_imgs.shape[3]
- for _ in range(len(model.blocks)):
- mask = generate_mask(noisy_imgs.size(0), h, w, config.mask_ratio)
- masks.append(mask)
- reconstructions, features, _ = model(noisy_imgs, masks)
- # 计算验证损失
- batch_val_loss = 0
- for j, recon in enumerate(reconstructions):
- mask = masks[j]
- resized_mask = F.interpolate(mask, size=recon.shape[2:], mode='nearest')
- if j == 0:
- expanded_clean_imgs = clean_imgs.expand_as(recon)
- target = expanded_clean_imgs
- else:
- target = features[j - 1]
- if target.shape[1] != recon.shape[1]:
- if not hasattr(model, f'adaptor_{j}'):
- setattr(model, f'adaptor_{j}',
- nn.Conv2d(target.shape[1], recon.shape[1], 1).to(device))
- adaptor = getattr(model, f'adaptor_{j}')
- target = adaptor(target)
- if target.shape[2:] != recon.shape[2:]:
- target = F.interpolate(target, size=recon.shape[2:], mode='nearest')
- batch_val_loss += criterion(recon * (1 - resized_mask), target * (1 - resized_mask)).item()
- val_loss += batch_val_loss
- # 计算平均损失
- avg_train_loss = running_loss / len(train_loader)
- avg_val_loss = val_loss / len(val_loader)
- train_losses.append(avg_train_loss)
- val_losses.append(avg_val_loss)
- # 更新学习率
- scheduler.step(avg_val_loss)
- current_lr = optimizer.param_groups[0]['lr']
- print(f'Current learning rate: {current_lr:.2e}')
- epoch_time = time.time() - epoch_start_time
- print(f'Epoch [{epoch + 1}/{num_epochs}] completed in {epoch_time:.2f}s')
- print(f'Training Loss: {avg_train_loss:.4f}, Validation Loss: {avg_val_loss:.4f}')
- # 保存最佳模型
- if avg_val_loss < best_loss:
- best_loss = avg_val_loss
- torch.save(model.state_dict(), os.path.join(config.model_dir, 'best_pretrain_model.pth'))
- print('Best model saved!')
- # 保存一些重建样本用于可视化
- if epoch % 5 == 0:
- model.eval()
- with torch.no_grad():
- noisy_imgs, clean_imgs, _ = next(iter(val_loader))
- noisy_imgs = noisy_imgs.to(device)
- clean_imgs = clean_imgs.to(device)
- # 为每一层生成掩码 - 使用输入图像的大小
- masks = []
- h, w = noisy_imgs.shape[2], noisy_imgs.shape[3]
- for _ in range(len(model.blocks)):
- mask = generate_mask(noisy_imgs.size(0), h, w, config.mask_ratio)
- masks.append(mask)
- reconstructions, _, _ = model(noisy_imgs, masks)
- # 保存输入、噪声、重建和原始图像
- save_image(torch.cat([
- noisy_imgs[:8],
- reconstructions[0][:8],
- clean_imgs[:8]
- ]), os.path.join(config.save_dir, f'reconstruction_epoch_{epoch + 1}.png'), nrow=8)
- # 绘制损失曲线
- plt.figure(figsize=(10, 5))
- plt.plot(train_losses, label='Training Loss')
- plt.plot(val_losses, label='Validation Loss')
- plt.xlabel('Epochs')
- plt.ylabel('Loss')
- plt.legend()
- plt.savefig(os.path.join(config.save_dir, 'pretrain_loss_curve.png'))
- plt.close()
- return train_losses, val_losses
- # 训练函数 - 微调阶段
- def finetune(model, train_loader, val_loader, optimizer, criterion, num_epochs):
- model.train()
- best_acc = 0.0
- train_losses = []
- val_losses = []
- train_accs = []
- val_accs = []
- for epoch in range(num_epochs):
- epoch_start_time = time.time()
- running_loss = 0.0
- correct = 0
- total = 0
- # 训练阶段
- for i, (noisy_imgs, clean_imgs, labels) in enumerate(train_loader):
- clean_imgs = clean_imgs.to(device)
- labels = labels.to(device)
- # 前向传播
- optimizer.zero_grad()
- _, _, cls_output = model(clean_imgs)
- # 计算分类损失
- loss = criterion(cls_output, labels)
- # 反向传播和优化
- loss.backward()
- torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
- optimizer.step()
- running_loss += loss.item()
- # 计算准确率
- _, predicted = torch.max(cls_output.data, 1)
- total += labels.size(0)
- correct += (predicted == labels).sum().item()
- if i % 10 == 0:
- acc = 100 * correct / total
- print(
- f'Epoch [{epoch + 1}/{num_epochs}], Step [{i + 1}/{len(train_loader)}], Loss: {loss.item():.4f}, Acc: {acc:.2f}%')
- # 验证阶段
- val_loss = 0.0
- val_correct = 0
- val_total = 0
- model.eval()
- with torch.no_grad():
- for _, clean_imgs, labels in val_loader:
- clean_imgs = clean_imgs.to(device)
- labels = labels.to(device)
- _, _, cls_output = model(clean_imgs)
- # 计算验证损失
- val_loss += criterion(cls_output, labels).item()
- # 计算验证准确率
- _, predicted = torch.max(cls_output.data, 1)
- val_total += labels.size(0)
- val_correct += (predicted == labels).sum().item()
- # 计算平均损失和准确率
- avg_train_loss = running_loss / len(train_loader)
- avg_val_loss = val_loss / len(val_loader)
- train_acc = 100 * correct / total
- val_acc = 100 * val_correct / val_total
- train_losses.append(avg_train_loss)
- val_losses.append(avg_val_loss)
- train_accs.append(train_acc)
- val_accs.append(val_acc)
- epoch_time = time.time() - epoch_start_time
- print(f'Epoch [{epoch + 1}/{num_epochs}] completed in {epoch_time:.2f}s')
- print(f'Training Loss: {avg_train_loss:.4f}, Training Acc: {train_acc:.2f}%')
- print(f'Validation Loss: {avg_val_loss:.4f}, Validation Acc: {val_acc:.2f}%')
- # 保存最佳模型
- if val_acc > best_acc:
- best_acc = val_acc
- torch.save(model.state_dict(), os.path.join(config.model_dir, 'best_finetune_model.pth'))
- print('Best model saved!')
- # 绘制损失和准确率曲线
- plt.figure(figsize=(12, 5))
- plt.subplot(1, 2, 1)
- plt.plot(train_losses, label='Training Loss')
- plt.plot(val_losses, label='Validation Loss')
- plt.xlabel('Epochs')
- plt.ylabel('Loss')
- plt.legend()
- plt.subplot(1, 2, 2)
- plt.plot(train_accs, label='Training Accuracy')
- plt.plot(val_accs, label='Validation Accuracy')
- plt.xlabel('Epochs')
- plt.ylabel('Accuracy (%)')
- plt.legend()
- plt.savefig(os.path.join(config.save_dir, 'finetune_curves.png'))
- plt.close()
- return train_losses, val_losses, train_accs, val_accs
- # 评估函数
- def evaluate_model(model, test_loader):
- model.eval()
- all_preds = []
- all_labels = []
- with torch.no_grad():
- for _, clean_imgs, labels in test_loader:
- clean_imgs = clean_imgs.to(device)
- labels = labels.to(device)
- _, _, cls_output = model(clean_imgs)
- _, preds = torch.max(cls_output, 1)
- all_preds.extend(preds.cpu().numpy())
- all_labels.extend(labels.cpu().numpy())
- # 计算评估指标
- print("Classification Report:")
- print(classification_report(all_labels, all_preds, target_names=train_dataset.classes,digits=5))
- # 绘制混淆矩阵
- cm = confusion_matrix(all_labels, all_preds)
- plt.figure(figsize=(8, 6))
- plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)
- plt.title('Confusion Matrix')
- plt.colorbar()
- tick_marks = np.arange(len(train_dataset.classes))
- plt.xticks(tick_marks, train_dataset.classes, rotation=45)
- plt.yticks(tick_marks, train_dataset.classes)
- # 在矩阵中显示数值
- thresh = cm.max() / 2.
- for i in range(cm.shape[0]):
- for j in range(cm.shape[1]):
- plt.text(j, i, format(cm[i, j], 'd'),
- ha="center", va="center",
- color="white" if cm[i, j] > thresh else "black")
- plt.tight_layout()
- plt.ylabel('True label')
- plt.xlabel('Predicted label')
- plt.savefig(os.path.join(config.save_dir, 'confusion_matrix.png'))
- plt.close()
- return all_preds, all_labels
- # 主函数
- def main():
- # 初始化模型
- model = StackedMDAE(config.hidden_dims, num_classes=4).to(device)
- print(f"模型参数量: {sum(p.numel() for p in model.parameters()):,}")
- # 在模型定义后添加权重初始化
- def init_weights(m):
- if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):
- nn.init.xavier_uniform_(m.weight)
- if m.bias is not None:
- nn.init.constant_(m.bias, 0)
- elif isinstance(m, nn.BatchNorm2d):
- nn.init.constant_(m.weight, 1)
- nn.init.constant_(m.bias, 0)
- elif isinstance(m, nn.Linear):
- nn.init.xavier_uniform_(m.weight)
- nn.init.constant_(m.bias, 0)
- model.apply(init_weights)
- # 定义损失函数和优化器
- reconstruction_criterion = nn.MSELoss()
- classification_criterion = nn.CrossEntropyLoss()
- pretrain_optimizer = optim.Adam(
- model.parameters(),
- lr=config.learning_rate_pretrain,
- weight_decay=config.weight_decay
- )
- # 预训练阶段
- print("开始预训练阶段...")
- pretrain_losses = pretrain(
- model, train_loader, val_loader,
- pretrain_optimizer, reconstruction_criterion,
- config.num_epochs_pretrain
- )
- # 加载最佳预训练模型
- model.load_state_dict(torch.load(os.path.join(config.model_dir, 'best_pretrain_model.pth')))
- print("预训练完成,加载最佳模型进行微调")
- # 微调阶段
- print("开始微调阶段...")
- finetune_optimizer = optim.Adam(
- model.parameters(),
- lr=config.learning_rate_finetune,
- weight_decay=config.weight_decay
- )
- finetune_losses = finetune(
- model, train_loader, val_loader,
- finetune_optimizer, classification_criterion,
- config.num_epochs_finetune
- )
- # 加载最佳微调模型
- model.load_state_dict(torch.load(os.path.join(config.model_dir, 'best_finetune_model.pth')))
- print("微调完成,加载最佳模型进行评估")
- # 评估模型
- evaluate_model(model, val_loader)
- print("训练和评估完成!")
- if __name__ == "__main__":
- main()
new.py at commit 98c17f9, no license · at the source
Overview
- College of Electronic Information Engineering, Guangdong University of Petrochemical Technology, Maoming 525000, China; (R.L.); (P.Z.)
- Provincial Key Laboratory of Petrochemical Equipment Fault Diagnosis, Guangdong University of Petrochemical Technology, Maoming 525000, China
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
98c17f9503b02d82428e4d45c8ed8b10bfcdf6a2, 17 July 2026Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
5 files
- MAE.py, Python, 597 lines
- SimCLR.py, Python, 497 lines, 1 match
- new.py, Python, 734 lines, 3 matches
- new_one.py, Python, 396 lines, 1 match
- README.md, Text, 2 lines
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
- doi:10.17632/
zwr4ntf94j.4 , at the source; found in “Data Availability Statement”
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://
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&
BibTeX
@article{li2026self,
author = {Li, Rui and Zhang, Puyu and Wen, Chenglin and Sun, Guoxi},
title = {{Self-Supervised Stacked Masked Denoising Autoencoder (S\&
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/
url = {https://
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&
T2 - Sensors (Basel, Switzerland)
J2 - Sensors (Basel)
PY - 2026
DA - 2026/
VL - 26
IS - 17
SP - 5388
SN - 1424-8220
PB - Multidisciplinary Digital Publishing Institute (MDPI)
DO - 10.3390/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.3390/
"type": "article-journal",
"title": "Self-Supervised Stacked Masked Denoising Autoencoder (S&
"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":
"volume": "26",
"issue": "17",
"page": "5388",
"DOI": "10.3390/
"PMID": "42740007",
"PMCID": "PMC13568421",
"ISSN": "1424-8220",
"publisher": "Multidisciplinary Digital Publishing Institute (MDPI)",
"URL": "https://
"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 imagingIn 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: eLifeIn 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 reportsIn 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 methodsIn 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: NeuroinformaticsIn 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 biologyIn 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 biologyIn 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 oneIn 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 imagingIn 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.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 1 repository of the authors' code, each at its verified commit and with its license, 4 scripts, and 5 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:2b6a27e2dbc04a95…
Add the badge to its README
The badge links the code to this page. Copy one of these into the README of the paper's code: only you decide where it goes, and nothing is changed for you.
Markdown
[, paste the snippet at the top, then “Commit changes…” and, to review it first, “Create a new branch and start a pull request”. You open the pull request; OSCR asks for no permission.
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.
