OSCR

NeXtSwin-X: dual-branch cross-attention fusion of ConvNeXt and swin transformer for accurate brain tumor classification from MRI and CT.

Code ↔ Paper

8 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 8 matches
  1. [1] § Datasets and methodology › Training and evaluation protocol ↔ Brain_Tumor_Classification_Nickparvar.ipynb, lines 319–440 · score 0.70 · AdamW, weight decay, head learning rates, Nickparvar, cross attention, ConvNeXt
  2. [2] § Datasets and methodology › Training and evaluation protocol ↔ Brain_Tumor_Classification_Ahmed.ipynb, lines 323–444 · score 0.68 · Cross Entropy Loss, Cosine Annealing, smoothing, scheduler, optimization, epochs
  3. [3] § Datasets and methodology › Training and evaluation protocol ↔ Brain_Tumor_Classification_BRISC.ipynb, lines 316–452 · score 0.68 · Cross Entropy Loss, Cosine Annealing, smoothing, scheduler, optimization, epochs
  4. [4] § Datasets and methodology › Training and evaluation protocol ↔ Brain_Tumor_Classification_Ahmed.ipynb, lines 323–444 · score 0.67 · AdamW, weight decay, head learning rates, cross attention, ConvNeXt, optimized
  5. [5] § Datasets and methodology › Data preprocessing and augmentation ↔ Brain_Tumor_Classification_Navoneel.ipynb, lines 25–88 · score 0.61 · random horizontal flips, random rotations, brightness, translations, MRI, transformations
  6. [6] § Datasets and methodology › Data preprocessing and augmentation ↔ Brain_Tumor_Classification_Nickparvar.ipynb, lines 24–89 · score 0.61 · random horizontal flips, random rotations, brightness, translations, MRI, transformations
  7. [7] § Datasets and methodology › The proposed dual-branch fusion architecture ↔ Brain_Tumor_Classification_BRISC.ipynb, lines 165–294 · score 0.55 · Layer Normalization, CNN features, linear, module, query, head
  8. [8] § Datasets and methodology › The proposed dual-branch fusion architecture ↔ Brain_Tumor_Classification_Navoneel.ipynb, lines 169–287 · score 0.55 · Layer Normalization, CNN features, linear, module, query, head

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

Jupyter notebook · 561 lines · 18 KB · MIT · 2 matches

  1. # %% [markdown]
  2. # ## Environment Setup
  3. # %%
  4. ! pip install kagglehub
  5. # %%
  6. import kagglehub
  7. path = kagglehub.dataset_download("masoudnickparvar/brain-tumor-mri-dataset")
  8. print("Path to dataset files:", path)
  9. # %%
  10. from google.colab import drive
  11. import os
  12. drive.mount('/content/drive')
  13. model_save_dir = '/content/drive/My Drive/Brain_Tumor_Nickparvar_Models'
  14. os.makedirs(model_save_dir, exist_ok=True)
  15. print(f"Model weights will be saved in: {model_save_dir}")
  16. # %% [markdown]
  17. # ## Data Loaders Setup
  18. # %%
  19. ! pip install timm ttach -q
  20. # %%
  21. import os
  22. import torch
  23. from torch.utils.data import DataLoader, WeightedRandomSampler, random_split
  24. from torchvision import transforms
  25. from torchvision.datasets import ImageFolder
  26. from torch.utils.data import Subset
  27. train_transform = transforms.Compose([
  28. transforms.Resize((224, 224)),
  29. transforms.RandomHorizontalFlip(p=0.5),
  30. transforms.RandomRotation(15),
  31. transforms.RandomAffine(0, translate=(0.1, 0.1)),
  32. transforms.ColorJitter(brightness=0.2, contrast=0.2),
  33. transforms.ToTensor(),
  34. transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
  35. ])
  36. val_test_transform = transforms.Compose([
  37. transforms.Resize((224, 224)),
  38. transforms.ToTensor(),
  39. transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
  40. ])
  41. base_dir = "/kaggle/input/brain-tumor-mri-dataset"
  42. train_dir = os.path.join(base_dir, "Training")
  43. test_dir = os.path.join(base_dir, "Testing")
  44. full_train_dataset = ImageFolder(train_dir, transform=train_transform)
  45. train_size = int(0.7 * len(full_train_dataset))
  46. val_size = int(0.2 * len(full_train_dataset))
  47. test_size = len(full_train_dataset) - train_size - val_size
  48. train_ds, val_ds, test_ds = random_split(
  49. full_train_dataset,
  50. [train_size, val_size, test_size],
  51. generator=torch.Generator().manual_seed(42)
  52. )
  53. val_ds = Subset(full_train_dataset, val_ds.indices)
  54. val_ds.dataset.transform = val_test_transform
  55. test_ds = Subset(full_train_dataset, test_ds.indices)
  56. test_ds.dataset.transform = val_test_transform
  57. train_targets = [full_train_dataset.targets[i] for i in train_ds.indices]
  58. class_counts = torch.bincount(torch.tensor(train_targets))
  59. class_weights = 1.0 / class_counts.float()
  60. sample_weights = [class_weights[label] for label in train_targets]
  61. sampler = WeightedRandomSampler(sample_weights, num_samples=len(sample_weights), replacement=True)
  62. train_loader = DataLoader(train_ds, batch_size=32, sampler=sampler, num_workers=2, pin_memory=True)
  63. val_loader = DataLoader(val_ds, batch_size=32, shuffle=False, num_workers=2, pin_memory=True)
  64. test_loader = DataLoader(test_ds, batch_size=32, shuffle=False, num_workers=2, pin_memory=True)
  65. print("Done setting up data loaders.")
  66. print(f"Total training images: {len(train_ds)}")
  67. print(f"Total validation images: {len(val_ds)}")
  68. print(f"Total test images: {len(test_ds)}")
  69. print(f"Classes: {full_train_dataset.classes}")
  70. # %% [markdown]
  71. # ## Exploratory Data Analysis (EDA)
  72. # %%
  73. import matplotlib.pyplot as plt
  74. import seaborn as sns
  75. import numpy as np
  76. plt.style.use('seaborn-v0_8-whitegrid')
  77. sns.set_context("talk")
  78. class_names = full_train_dataset.classes
  79. class_counts = np.bincount(full_train_dataset.targets)
  80. formatted_class_names = []
  81. for name in class_names:
  82. if name == 'notumor':
  83. formatted_class_names.append('No Tumor')
  84. else:
  85. formatted_class_names.append(name.capitalize())
  86. pie_colors = sns.color_palette("Set2", len(class_names))
  87. plt.figure(figsize=(12, 10))
  88. wedges, texts, autotexts = plt.pie(
  89. class_counts,
  90. labels=formatted_class_names,
  91. autopct='%1.1f%%',
  92. startangle=140,
  93. colors=pie_colors,
  94. textprops={'fontsize': 14},
  95. wedgeprops={'edgecolor': 'black', 'linewidth': 0.75}
  96. )
  97. plt.setp(autotexts, size=12, weight="bold", color="white")
  98. plt.title(
  99. 'Class Distribution in the Full Training Dataset',
  100. fontweight='bold',
  101. fontsize=20,
  102. pad=20
  103. )
  104. plt.axis('equal')
  105. plt.show()
  106. split_sizes = {
  107. 'Training': len(train_ds),
  108. 'Validation': len(val_ds),
  109. 'Test': len(test_ds)
  110. }
  111. bar_colors = sns.color_palette("Paired", len(split_sizes))
  112. plt.figure(figsize=(10, 7))
  113. ax = sns.barplot(
  114. x=list(split_sizes.keys()),
  115. y=list(split_sizes.values()),
  116. palette=bar_colors,
  117. edgecolor='black',
  118. linewidth=1.5
  119. )
  120. ax.set_title('Dataset Image Distribution Across Splits', fontsize=20, fontweight='bold', pad=20)
  121. ax.set_xlabel('Dataset Split', fontsize=16, fontweight='bold')
  122. ax.set_ylabel('Number of Images', fontsize=16, fontweight='bold')
  123. ax.tick_params(axis='x', labelsize=14)
  124. ax.tick_params(axis='y', labelsize=12)
  125. for i, (split, size) in enumerate(split_sizes.items()):
  126. ax.text(i, size + 50, f'{size:,}', ha='center', va='bottom', fontsize=14, fontweight='bold')
  127. plt.ylim(0, max(split_sizes.values()) * 1.15)
  128. sns.despine(top=True, right=True)
  129. plt.tight_layout()
  130. plt.show()
  131. # %% [markdown]
  132. # ## Model Architecture
  133. # %%
  134. import timm
  135. import torch
  136. import torch.nn as nn
  137. import torch.nn.functional as F
  138. # CNN-only
  139. class CNN_Only_Model(nn.Module):
  140. def __init__(self, num_classes=4, pretrained=True):
  141. super().__init__()
  142. self.backbone = timm.create_model(
  143. "convnext_base",
  144. pretrained=pretrained,
  145. num_classes=0
  146. )
  147. in_features = self.backbone.head.in_features
  148. self.classifier = nn.Linear(in_features, num_classes)
  149. def forward(self, x):
  150. feats = self.backbone(x)
  151. return self.classifier(feats)
  152. # Transformer-only
  153. class Transformer_Only_Model(nn.Module):
  154. def __init__(self, num_classes=4, pretrained=True):
  155. super().__init__()
  156. self.vit = timm.create_model(
  157. "swin_base_patch4_window7_224",
  158. pretrained=pretrained,
  159. num_classes=num_classes
  160. )
  161. def forward(self, x):
  162. return self.vit(x)
  163. # Dual-Branch
  164. class DualBranch_Model(nn.Module):
  165. def __init__(
  166. self,
  167. num_classes=4,
  168. fusion_dim=512,
  169. num_heads=8,
  170. dropout=0.1,
  171. pretrained=True,
  172. ):
  173. super().__init__()
  174. # CNN branch: ConvNeXt
  175. self.cnn_branch = timm.create_model(
  176. "convnext_base", pretrained=pretrained, num_classes=0
  177. )
  178. cnn_out = self.cnn_branch.head.in_features
  179. self.cnn_proj = nn.Linear(cnn_out, fusion_dim)
  180. # Transformer branch: Swin Transformer
  181. self.transformer_branch = timm.create_model(
  182. "swin_base_patch4_window7_224", pretrained=pretrained, num_classes=0
  183. )
  184. trans_out = self.transformer_branch.head.in_features
  185. self.trans_proj = nn.Linear(trans_out, fusion_dim)
  186. # Cross-Attention
  187. self.cross_attention = nn.MultiheadAttention(
  188. embed_dim=fusion_dim,
  189. num_heads=num_heads,
  190. dropout=dropout,
  191. batch_first=False
  192. )
  193. self.fusion_norm = nn.LayerNorm(fusion_dim)
  194. self.classifier = nn.Sequential(
  195. nn.Linear(fusion_dim, fusion_dim // 2),
  196. nn.ReLU(),
  197. nn.Dropout(0.5),
  198. nn.Linear(fusion_dim // 2, num_classes)
  199. )
  200. def forward(self, x):
  201. cnn_feats = self.cnn_branch(x)
  202. cnn_proj = self.cnn_proj(cnn_feats)
  203. trans_feats = self.transformer_branch(x)
  204. trans_proj = self.trans_proj(trans_feats)
  205. cnn_query = cnn_proj.unsqueeze(0)
  206. trans_kv = trans_proj.unsqueeze(0)
  207. attn_output, _ = self.cross_attention(
  208. query=cnn_query,
  209. key=trans_kv,
  210. value=trans_kv
  211. )
  212. attn_output = attn_output.squeeze(0)
  213. fused_features = self.fusion_norm(cnn_proj + attn_output)
  214. out_main = self.classifier(fused_features)
  215. return out_main
  216. # ResNet Model
  217. class ResNet_Model(nn.Module):
  218. def __init__(self, num_classes=4, pretrained=True):
  219. super().__init__()
  220. self.backbone = timm.create_model(
  221. "resnet50",
  222. pretrained=pretrained,
  223. num_classes=num_classes
  224. )
  225. def forward(self, x):
  226. return self.backbone(x)
  227. # EfficientNetV2 Model
  228. class EfficientNetV2_Model(nn.Module):
  229. def __init__(self, num_classes=4, pretrained=True):
  230. super().__init__()
  231. self.backbone = timm.create_model(
  232. "tf_efficientnetv2_b3",
  233. pretrained=pretrained,
  234. num_classes=num_classes
  235. )
  236. def forward(self, x):
  237. return self.backbone(x)
  238. # %%
  239. from sklearn.metrics import confusion_matrix
  240. import seaborn as sns
  241. import matplotlib.pyplot as plt
  242. def plot_confusion_matrix(labels, preds, class_names, model_name):
  243. formatted_class_names = []
  244. for name in class_names:
  245. if name == 'notumor':
  246. formatted_class_names.append('No Tumor')
  247. else:
  248. formatted_class_names.append(name.capitalize())
  249. cm = confusion_matrix(labels, preds)
  250. plt.figure(figsize=(9, 7))
  251. heatmap = sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
  252. xticklabels=formatted_class_names, yticklabels=formatted_class_names)
  253. plt.title(f'Confusion Matrix - {model_name} (Test Set)', fontsize=16)
  254. plt.xlabel('Predicted Label', fontsize=12)
  255. plt.ylabel('True Label', fontsize=12)
  256. plt.xticks(rotation=45, ha="right")
  257. plt.yticks(rotation=0)
  258. plt.tight_layout()
  259. plt.show()
  260. # %% [markdown]
  261. # ## Training and Evaluation Loop
  262. # %%
  263. import time
  264. import torch
  265. import torch.nn as nn
  266. import torch.optim as optim
  267. from torch.optim.lr_scheduler import CosineAnnealingLR
  268. from torch.cuda.amp import GradScaler, autocast
  269. from torch.utils.data import DataLoader
  270. from tqdm import tqdm
  271. import ttach as tta
  272. from sklearn.metrics import classification_report
  273. import pandas as pd
  274. from sklearn.exceptions import UndefinedMetricWarning
  275. import warnings
  276. warnings.filterwarnings("ignore", category=UndefinedMetricWarning)
  277. def evaluate_model(model, dataloader, device, class_names):
  278. model.eval()
  279. all_labels, all_preds = [], []
  280. with torch.no_grad():
  281. for images, labels in dataloader:
  282. images, labels = images.to(device, non_blocking=True), labels.to(device, non_blocking=True)
  283. with torch.cuda.amp.autocast():
  284. outputs = model(images)
  285. _, predicted = torch.max(outputs, 1)
  286. all_labels.extend(labels.cpu().numpy())
  287. all_preds.extend(predicted.cpu().numpy())
  288. report = classification_report(all_labels, all_preds, target_names=class_names, output_dict=True, zero_division=0)
  289. return report, all_labels, all_preds
  290. def train_and_evaluate(
  291. model, model_name, train_loader, val_loader, test_loader,
  292. device, class_names, num_epochs=12, transformer_lr=1e-5,
  293. cnn_lr=3e-5, head_lr=1e-4, weight_decay=1e-4,
  294. ):
  295. print(f"\n{'='*35}\n Starting Training for: {model_name}\n{'='*35}")
  296. model.to(device)
  297. criterion = nn.CrossEntropyLoss(label_smoothing=0.1)
  298. if 'Dual_Branch' in model_name:
  299. param_groups = [
  300. {'params': model.transformer_branch.parameters(), 'lr': transformer_lr},
  301. {'params': model.cnn_branch.parameters(), 'lr': cnn_lr},
  302. {'params': model.cnn_proj.parameters(), 'lr': head_lr},
  303. {'params': model.trans_proj.parameters(), 'lr': head_lr},
  304. {'params': model.cross_attention.parameters(), 'lr': head_lr},
  305. {'params': model.fusion_norm.parameters(), 'lr': head_lr},
  306. {'params': model.classifier.parameters(), 'lr': head_lr},
  307. ]
  308. optimizer = optim.AdamW(param_groups, weight_decay=weight_decay)
  309. print(f"Using differential LRs: Transformer={transformer_lr}, CNN={cnn_lr}, Head={head_lr}")
  310. else:
  311. single_lr = cnn_lr if ('ConvNeXt' in model_name or 'ResNet' in model_name or 'EfficientNet' in model_name) else transformer_lr
  312. optimizer = optim.AdamW(model.parameters(), lr=single_lr, weight_decay=weight_decay)
  313. print(f"Using single LR: {single_lr}")
  314. scheduler = CosineAnnealingLR(optimizer, T_max=num_epochs, eta_min=1e-6)
  315. scaler = GradScaler()
  316. best_val_acc = 0.0
  317. base_save_path = "/content/drive/My Drive/Brain_Tumor_Nickparvar_Models"
  318. best_model_save_path = f"{base_save_path}/best_{model_name}.pth"
  319. last_model_save_path = f"{base_save_path}/last_{model_name}.pth"
  320. start_time = time.time()
  321. for epoch in range(num_epochs):
  322. model.train()
  323. running_loss = 0.0
  324. train_bar = tqdm(train_loader, desc=f"Epoch {epoch+1}/{num_epochs} [Train]", leave=False)
  325. for images, labels in train_bar:
  326. images, labels = images.to(device, non_blocking=True), labels.to(device, non_blocking=True)
  327. optimizer.zero_grad(set_to_none=True)
  328. with autocast():
  329. outputs = model(images)
  330. loss = criterion(outputs, labels)
  331. scaler.scale(loss).backward()
  332. scaler.step(optimizer)
  333. scaler.update()
  334. running_loss += loss.item()
  335. val_report, _, _ = evaluate_model(model, val_loader, device, class_names)
  336. val_acc = val_report['accuracy'] * 100
  337. scheduler.step()
  338. print(f"Epoch {epoch+1:02d} | Train Loss: {running_loss/len(train_loader):.4f} | "
  339. f"Val Acc: {val_acc:.2f}% | Val F1: {val_report['weighted avg']['f1-score']:.4f} | "
  340. f"LR: {scheduler.get_last_lr()[0]:.2e}")
  341. if val_acc > best_val_acc:
  342. best_val_acc = val_acc
  343. torch.save(model.state_dict(), best_model_save_path)
  344. print(f" -> New best model saved to Drive with Val Acc: {best_val_acc:.2f}%")
  345. training_time = time.time() - start_time
  346. print(f"\nTraining for {model_name} finished in {training_time/60:.2f} minutes.")
  347. torch.save(model.state_dict(), last_model_save_path)
  348. print(f"Saved final model state to '{last_model_save_path}'")
  349. print(f"Loading best model from '{best_model_save_path}' for final evaluation...")
  350. model.load_state_dict(torch.load(best_model_save_path, map_location=device))
  351. print("\nCalculating metrics for the BEST model on all data splits...")
  352. val_metrics, _, _ = evaluate_model(model, val_loader, device, class_names)
  353. test_normal_metrics, test_labels, test_preds = evaluate_model(model, test_loader, device, class_names)
  354. tta_model = tta.ClassificationTTAWrapper(model, tta.aliases.hflip_transform())
  355. test_tta_metrics, _, _ = evaluate_model(tta_model, test_loader, device, class_names)
  356. final_results = {
  357. 'Validation': val_metrics,
  358. 'Test (Normal)': test_normal_metrics,
  359. 'Test (TTA)': test_tta_metrics,
  360. 'Test_Labels_Preds': (test_labels, test_preds)
  361. }
  362. return final_results
  363. # %% [markdown]
  364. # ## Model Training
  365. # %%
  366. import warnings
  367. warnings.filterwarnings("ignore", category=FutureWarning)
  368. warnings.filterwarnings("ignore", category=UserWarning)
  369. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  370. num_classes = len(full_train_dataset.classes)
  371. class_names = full_train_dataset.classes
  372. epochs = 10
  373. weight_decay = 1e-2
  374. convnext_lr = 1e-5
  375. swin_lr = 3e-5
  376. resnet_lr = 3e-5
  377. efficientnet_lr = 3e-5
  378. dual_transformer_lr = 6e-5
  379. dual_cnn_lr = 1e-5
  380. dual_head_lr = 1e-4
  381. all_model_results = {}
  382. model_builders = {
  383. "Dual_Branch_Swin_ConvNeXt": lambda: DualBranch_Model(num_classes=num_classes),
  384. "Swin_Transformer_Only": lambda: Transformer_Only_Model(num_classes=num_classes),
  385. "ConvNeXt_Only": lambda: CNN_Only_Model(num_classes=num_classes),
  386. "ResNet50": lambda: ResNet_Model(num_classes=num_classes),
  387. "EfficientNetV2_B3": lambda: EfficientNetV2_Model(num_classes=num_classes),
  388. }
  389. for name, builder in model_builders.items():
  390. try:
  391. model_instance = torch.compile(builder())
  392. print(f"\n=== Running experiment: {name} (Compiled) ===")
  393. except Exception:
  394. print(f"\n=== Running experiment: {name} (Not Compiled) ===")
  395. model_instance = builder()
  396. if 'Dual_Branch' in name:
  397. lr_params = {'transformer_lr': dual_transformer_lr, 'cnn_lr': dual_cnn_lr, 'head_lr': dual_head_lr}
  398. elif 'Swin' in name:
  399. lr_params = {'cnn_lr': swin_lr, 'transformer_lr': swin_lr, 'head_lr': swin_lr}
  400. elif 'ConvNeXt' in name:
  401. lr_params = {'cnn_lr': convnext_lr, 'transformer_lr': convnext_lr, 'head_lr': convnext_lr}
  402. elif 'ResNet' in name:
  403. lr_params = {'cnn_lr': resnet_lr, 'transformer_lr': resnet_lr, 'head_lr': resnet_lr}
  404. else:
  405. lr_params = {'cnn_lr': efficientnet_lr, 'transformer_lr': efficientnet_lr, 'head_lr': efficientnet_lr}
  406. detailed_results = train_and_evaluate(
  407. model=model_instance,
  408. model_name=name,
  409. train_loader=train_loader,
  410. val_loader=val_loader,
  411. test_loader=test_loader,
  412. device=device,
  413. class_names=class_names,
  414. num_epochs=epochs,
  415. weight_decay=weight_decay,
  416. **lr_params
  417. )
  418. all_model_results[name] = detailed_results
  419. del model_instance
  420. torch.cuda.empty_cache()
  421. # %% [markdown]
  422. # ## Confusion Matrix Visualization
  423. # %%
  424. print("\n\n" + "="*60)
  425. print(" MODEL CONFUSION MATRICES")
  426. print("="*60)
  427. for model_name, results in all_model_results.items():
  428. if 'Test_Labels_Preds' in results:
  429. labels, preds = results['Test_Labels_Preds']
  430. plot_confusion_matrix(labels, preds, class_names, model_name)
  431. # %% [markdown]
  432. # ## Results Summary
  433. # %%
  434. import pandas as pd
  435. print("\n\n" + "="*60)
  436. print(" COMPREHENSIVE MODEL PERFORMANCE REPORT")
  437. print("="*60)
  438. report_data = []
  439. for model_name, results in all_model_results.items():
  440. for split_name, metrics in results.items():
  441. if split_name == 'Test_Labels_Preds':
  442. continue
  443. weighted_avg = metrics['weighted avg']
  444. report_data.append({
  445. 'Model': model_name,
  446. 'Split': split_name,
  447. 'Accuracy': metrics['accuracy'] * 100,
  448. 'F1-Score': weighted_avg['f1-score'],
  449. 'Precision': weighted_avg['precision'],
  450. 'Recall': weighted_avg['recall']
  451. })
  452. df_report = pd.DataFrame(report_data)
  453. df_report = df_report.set_index(['Model', 'Split'])
  454. pd.options.display.float_format = '{:,.4f}'.format
  455. df_report['Accuracy'] = df_report['Accuracy'].map('{:.2f}%'.format)
  456. print(df_report.to_string())
  457. print("\n" + "="*60)
  458. print("Analysis Complete.")

Brain_Tumor_Classification_Nickparvar.ipynb at commit d76ba08, under MIT · at the source

Overview

Authors: Arash Nasr Esfahani1, Amirreza Jalili1, Hedieh Sajedi1
  1. Department of Computer Science, School of Mathematics, Statistics and Computer Science, College of Science, University of Tehran, Tehran, Iran
Institutions: University of Tehran (Iran)
Journal: Scientific reports, volume 16, issue 1, article 19959
Dates: received 25 December 2025; accepted 20 April 2026; published online 25 April 2026
Type: Research article · Language: English
License: CC BY-NC-ND
Identifiers: DOI 10.1038/s41598-026-50158-1 · PMID 42034796 · PMCID PMC13319430 · OpenAlex W7155649263
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: structural MRI / diffusion (modality), other (modality), other condition (population)
Methods: Machine learning
Keywords: Brain Tumor Classification, Medical Image Processing, Deep Learning, Convolutional Neural Network (CNN), Vision Transformer (ViT), Hybrid Models, Cross-Attention, Transfer Learning, Magnetic Resonance Imaging (MRI), Computed Tomography (CT), Computational biology and bioinformatics, Engineering, Mathematics and computing
Topic: Brain Tumor Detection and Classification (Neurology, Neuroscience), according to OpenAlex
Citations: not cited yet (Europe PMC); 32 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 8 matches between paragraphs and lines of code.

ArashNasrEsfahani/NeXtSwin-X

License: MIT
State: the link answers, verified on 30 September 2026
Evidence: files inventoried
Commit: d76ba083a8a9d1b93a8cefecd412c3549dce33ea, 3 October 2025
Languages: Jupyter (6)
Size: 10 files, 6 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, license file, 6 notebooks
Not found: CITATION.cff, environment file, tests, continuous integration, documentation
Tools: Matplotlib (6 files), NumPy (6 files), pandas (6 files), PyTorch (6 files), scikit-learn (6 files), seaborn (6 files)
Availability: 1 check, the latest on 30 September 2026: the link answers
  • 30 September 2026: the link answers
8 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-50158-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;
  • 6 scripts, each with its path and the digest of its content;
  • 8 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

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

  • no repository, dataset or request procedure was recognized in it

Read it in the paper: doi.org/10.1038/s41598-026-50158-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, 30 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 3 authors, 13 keywords, 18 references.

Cite

This paper

Esfahani, A. N., Jalili, A., & Sajedi, H. (2026). NeXtSwin-X: dual-branch cross-attention fusion of ConvNeXt and swin transformer for accurate brain tumor classification from MRI and CT. Scientific reports, 16(1), 19959. https://doi.org/10.1038/s41598-026-50158-1

BibTeX

@article{esfahani2026nextswin,
author = {Esfahani, Arash Nasr and Jalili, Amirreza and Sajedi, Hedieh},
title = {{NeXtSwin-X: dual-branch cross-attention fusion of ConvNeXt and swin transformer for accurate brain tumor classification from MRI and CT}},
journal = {Scientific reports},
year = {2026},
month = apr,
volume = {16},
number = {1},
pages = {19959},
publisher = {Nature Publishing Group},
issn = {2045-2322},
doi = {10.1038/s41598-026-50158-1},
url = {https://doi.org/10.1038/s41598-026-50158-1},
pmid = {42034796},
pmcid = {PMC13319430}
}

RIS

TY - JOUR
AU - Esfahani, Arash Nasr
AU - Jalili, Amirreza
AU - Sajedi, Hedieh
TI - NeXtSwin-X: dual-branch cross-attention fusion of ConvNeXt and swin transformer for accurate brain tumor classification from MRI and CT
T2 - Scientific reports
J2 - Sci Rep
PY - 2026
DA - 2026/04/25
VL - 16
IS - 1
SP - 19959
SN - 2045-2322
PB - Nature Publishing Group
DO - 10.1038/s41598-026-50158-1
UR - https://doi.org/10.1038/s41598-026-50158-1
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41598-026-50158-1",
"type": "article-journal",
"title": "NeXtSwin-X: dual-branch cross-attention fusion of ConvNeXt and swin transformer for accurate brain tumor classification from MRI and CT",
"container-title": "Scientific reports",
"author": [
{
"family": "Esfahani",
"given": "Arash Nasr"
},
{
"family": "Jalili",
"given": "Amirreza"
},
{
"family": "Sajedi",
"given": "Hedieh"
}
],
"container-title-short": "Sci Rep",
"volume": "16",
"issue": "1",
"page": "19959",
"DOI": "10.1038/s41598-026-50158-1",
"PMID": "42034796",
"PMCID": "PMC13319430",
"ISSN": "2045-2322",
"publisher": "Nature Publishing Group",
"URL": "https://doi.org/10.1038/s41598-026-50158-1",
"language": "en",
"issued": {
"date-parts": [
[
2026,
4,
25
]
]
}
}

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/jimaging12060233 [code]
Brain Tumor Classification in MRI Images Using Combined Transfer Learning and Convolutional Neural Networks.
Journal: Journal of imaging
In common: seaborn, scikit-learn, pandas, 2 other tools, kaggle.com/datasets/ahmedhamada0, structural MRI / diffusion, other condition
[2] doi:10.3389/fncom.2026.1798561
Bridging modalities: a deep learning framework for brain tumor classification via CT-MRI integration and model fusion.
Journal: Frontiers in computational neuroscience
In common: kaggle.com/datasets/murtozalikhon, other, structural MRI / diffusion, other condition, 1 reference
[3] doi:10.1038/s41598-026-45675-y [code]
Multi-class classification of brain tumor using a ResNet101 backbone integrated with multi-scale deformable attention module and advanced data augmentations.
Journal: Scientific reports
In common: PyTorch, seaborn, scikit-learn, 3 other tools, structural MRI / diffusion, other condition, 1 reference
[4] doi:10.21037/qims-2026-0792 [code]
An nnU-Net-based framework with adaptive feature representation for 3D brain tumor segmentation.
Journal: Quantitative imaging in medicine and surgery
In common: PyTorch, seaborn, scikit-learn, 3 other tools, structural MRI / diffusion, other condition, 1 reference
[5] doi:10.3389/frai.2026.1771088 [code]
Few-shot deployment of pretrained MRI transformers in brain imaging tasks.
Journal: Frontiers in artificial intelligence
In common: PyTorch, seaborn, scikit-learn, 3 other tools, structural MRI / diffusion, 1 reference
[6] doi:10.3389/fmed.2026.1875760 [code]
Adaptive multi-stage domain unlearning for white-matter lesion segmentation.
Journal: Frontiers in medicine
In common: PyTorch, seaborn, scikit-learn, 3 other tools, structural MRI / diffusion, 1 reference
[7] doi:10.1186/s40708-026-00316-y [code]
Generalizable and explainable deep learning for brain MRI: a multi-cohort evaluation of 3D architectures for age and sex prediction.
Journal: Brain informatics
In common: PyTorch, seaborn, scikit-learn, 3 other tools, structural MRI / diffusion, 1 reference
[8] doi:10.1038/s41746-026-02713-3 [code]
Learning like a radiologist: a medical vision-language model for radiological image analysis via curriculum learning.
Journal: NPJ digital medicine
In common: PyTorch, pandas, NumPy, kaggle.com/datasets/ahmedhamada0
[9] doi:10.1186/s12938-026-01555-0 [code]
Incorporating normal periventricular changes for enhanced pathological white matter hyperintensity segmentation: on multiclass deep learning approaches.
Journal: Biomedical engineering online
In common: seaborn, scikit-learn, pandas, 2 other tools, structural MRI / diffusion, 1 reference
[10] doi:10.3389/fmed.2026.1810860
Lightweight deep learning for medical imaging using MobileNetV2-based brain pathology classification with Grad-CAM interpretability.
Journal: Frontiers in medicine
In common: kaggle.com/datasets/trainingdatapro, other

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.