Generalizable and explainable deep learning for brain MRI: a multi-cohort evaluation of 3D architectures for age and sex prediction.
The 2 matches · 1 of them tie a paragraph to a whole file, not to given lines: a weak match, whose lines are not tinted
- [1] § Methods › Model architectures ↔ trainers/train_reg.py, lines 100–139 · score 0.68 · DenseNet121, Swin Transformer, Monai, densely, patches, Window
- [2] § Methods › Model architectures ↔ architectures/sfcn_mod.py, the whole file · a weak match · score 0.61 · ReLU, activations, layers, global, dimensions, batch
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 · 279 lines · 9.6 KB · no license · 1 match
- #%%
- #Imports
- import pandas as pd
- import matplotlib.pyplot as plt
- import os
- import monai
- import numpy as np
- import torch
- import torch.nn as nn
- import matplotlib.pyplot as plt
- import dateutil
- dateutil.__version__
- import torch.nn.functional as F
- from torch.utils.data import Dataset, DataLoader
- from scipy import interp
- from collections import Counter
- import datetime
- import time
- import seaborn as sns
- from sklearn.utils.class_weight import compute_class_weight
- from tqdm import tqdm
- from sklearn.metrics import roc_curve, roc_auc_score, precision_recall_curve, average_precision_score
- from sklearn.metrics import confusion_matrix, f1_score, brier_score_loss
- from sklearn.model_selection import KFold, StratifiedKFold
- import random
- import sys
- sys.path.append('../dataloaders')
- sys.path.append('../architectures')
- import dataloader, dataloader_new
- import sfcn_mod, monai_swin
- #%%
- # Parameters
- # Basic parameters
- cohort = 'ukb'
- model_name = 'dense'
- method_name = 'supervised'
- column_name = 'age'
- task = 'regression'
- img_size = 180
- #Training parameters
- batch_size = 4
- num_epochs = 1000
- n_splits = 3
- nrows = None
- dev = "cuda:1"
- n_classes = 1
- n_channels = 1
- lr = 1e-03
- seed = 42
- best_val_loss = 10000
- # Set Paths
- tensor_dir = f'../../images/{cohort}/npy_{cohort}{img_size}'
- csv_train = f'../data/ukb/train/demographics.csv'
- unique_name = f"{column_name}_e{num_epochs}_n{nrows}_b{batch_size}_lr{lr}_s{n_splits}_im{img_size}"
- scores_train = f'../scores/{cohort}/{model_name}/train/{unique_name}'
- scores_val = f'../scores/{cohort}/{model_name}/val/{unique_name}'
- timelog_dir = f'../logs/timelog/{model_name}/'
- trainlog_dir = f'../logs/trainlog/{model_name}/'
- vallog_dir = f'../logs/vallog/{model_name}/'
- log_dir = f'../logs/aurocs/{model_name}/'
- save_model = f'../models/{model_name}/'
- fig_name = f"{unique_name}.png"
- # swin parameters
- patch_size = [8, 8, 8]
- window_size = [16, 16, 16]
- num_heads = [3,6,12,24]
- depths = [2,2,2,2]
- feature_size = 96
- # early stopping parameters
- patience = 10
- #Set Device
- if torch.cuda.is_available():
- torch.cuda.set_device(dev)
- #Set a random seed for PyTorch (for GPU and CPU operations)
- torch.manual_seed(42)
- random.seed(42)
- np.random.seed(42)
- #%%
- #Training dataset
- train_dataset = dataloader.BrainDataset(csv_train, tensor_dir, column_name, task='regression', num_rows = nrows)
- #%%
- # Training loop
- trainlog_file = os.path.join(trainlog_dir, f"{unique_name}.txt")
- total_time = 0
- with open(trainlog_file, "a") as log:
- log.write(f'Fold, Epoch, Training Loss, Validation Loss\n')
- # Initialize KFold
- skf = KFold(n_splits=n_splits, random_state=seed, shuffle=True)
- for fold, (train_ids, val_ids) in enumerate(skf.split(np.arange(len(train_dataset)))):
- print(f" Training samples: {train_ids}")
- print(f" Validation samples: {val_ids}")
- train_losses = []
- val_losses = []
- early_stop_counter = 0
- start_time = time.time()
- print(f"Starting Fold {fold + 1}")
- # Retrieve patient id lists for the fold
- train_eids = [train_dataset.annotations.eid[i] for i in train_ids]
- val_eids = [train_dataset.annotations.eid[i] for i in val_ids]
- # Retrieve labels lists for the fold
- train_labels = [train_dataset.annotations[column_name][i] for i in train_ids]
- val_labels = [train_dataset.annotations[column_name][i] for i in val_ids]
- # Check fold distribution
- train_label_distribution = Counter(train_labels)
- val_label_distribution = Counter(val_labels)
- print(f"Training set label distribution for Fold {fold + 1}: {train_label_distribution}")
- print(f"Validation set label distribution for Fold {fold + 1}: {val_label_distribution}")
- train_subset = torch.utils.data.Subset(train_dataset, train_ids)
- val_subset = torch.utils.data.Subset(train_dataset, val_ids)
- # Set dataloaders
- train_loader = DataLoader(train_subset, batch_size = batch_size, num_workers=8, drop_last = True)
- val_loader = DataLoader(val_subset, batch_size = batch_size, num_workers=8, drop_last = True)
- # Set Model
- #model = sfcn_mod.SFCN(input_size=img_size, output_dim=n_classes, task=task).to(dev)
- model = monai.networks.nets.DenseNet121(spatial_dims=3, in_channels= n_channels, out_channels = n_classes).to(dev)
- #model = monai_swin.SwinTransformer(in_chans = 1, embed_dim = feature_size, window_size = window_size, patch_size = patch_size, depths = depths, num_heads = num_heads, n_classes = n_classes).to(dev)#
- # Set Optimizer and Loss
- criterion = torch.nn.MSELoss().to(dev)
- #Define the optimizer with initial learning rate
- optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
- print(model)
- # Define the learning rate scheduler
- #scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.3)
- for epoch in range(num_epochs):
- train_outputs = []
- train_outputs_binary = []
- train_labels = []
- val_outputs = []
- val_outputs_binary = []
- val_labels = []
- train_table = []
- val_table = []
- train_eids = []
- val_eids = []
- # Training loop
- model.train()
- running_train_loss = 0.0
- for i, (eid, images, labels) in tqdm(enumerate(train_loader), total = len(train_loader)):
- images = images.to(dev)
- eid = eid
- train_eids.extend(eid)
- labels = labels.float().to(dev)
- optimizer.zero_grad()
- outputs = model(images).to(dev)
- train_outputs.extend(outputs.tolist())
- train_labels.extend(labels.tolist())
- loss = criterion(outputs, labels)
- loss.backward()
- optimizer.step()
- running_train_loss += loss.item()
- train_loss = running_train_loss / len(train_loader)
- train_losses.append(train_loss)
- # Validation loop
- model.eval()
- running_val_loss = 0.0
- with torch.no_grad():
- for j, (eid, images, labels) in tqdm(enumerate(val_loader), total = len(val_loader)):
- images = images.to(dev)
- eid = eid
- val_eids.extend(eid)
- labels = labels.float().to(dev)
- outputs = model(images).to(dev)
- #print(outputs.shape)
- #print(labels.shape)
- val_outputs.extend(outputs.tolist())
- val_labels.extend(labels.tolist())
- loss = criterion(outputs, labels)
- running_val_loss += loss.item()
- val_loss = running_val_loss / len(val_loader)
- val_losses.append(val_loss)
- print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')
- if val_loss < best_val_loss:
- print(f"Saving new model based on validation loss {val_loss:.4f}")
- best_val_loss = val_loss
- checkpoint = {"epoch": num_epochs, "state_dict": model.state_dict(), "optimizer": optimizer.state_dict()}
- # Save Model
- torch.save(checkpoint, os.path.join(save_model, f"{unique_name}_k{fold+1}_best.pth"))
- print(f'Model saved at {save_model}')
- best_val_labels = val_labels
- best_val_outputs = val_outputs
- best_val_outputs_binary = val_outputs_binary
- early_stop_counter = 0
- else:
- early_stop_counter += 1
- if early_stop_counter >= patience:
- print(f'Early stopping after {epoch + 1} epochs without improvement in validation loss for {patience} epochs')
- break
- # Update the learning rate
- #scheduler.step()
- # Optionally, print the current learning rate
- #current_lr = optimizer.param_groups[0]['lr']
- #print(f'Current Learning Rate: {current_lr}')
- trainlog_file = os.path.join(trainlog_dir, f"{unique_name}.txt")
- with open(trainlog_file, "a") as log:
- log.write(f'{fold + 1}, {epoch + 1}, {train_loss:.4f}, {val_loss:.4f} \n')
- # Save prediction scores into dictionaries
- train_data = {
- #'fold': fold + 1,
- 'eid': train_eids,
- 'label': train_labels,
- 'logits': train_outputs,
- }
- val_data = {
- #'fold': [fold + 1],
- 'eid': val_eids,
- 'label': best_val_labels,
- 'logits': best_val_outputs,
- }
- # Log Predictions into csvs
- df_train = pd.DataFrame(train_data)
- df_val = pd.DataFrame(val_data)
- df_train.to_csv(f'{scores_train}_k{fold+1}.csv', index=False)
- df_val.to_csv(f'{scores_val}_k{fold+1}.csv', index=False)
- print(f'Predictions saved!')
- #Log Loss
- vallog_file = os.path.join(vallog_dir, f"{unique_name}.txt")
- with open(vallog_file, "a") as log:
- log.write(f'Fold {fold + 1} completed. Best Validation Loss: {best_val_loss:.4f} \n')
- log.write(f'Early stopping after {epoch + 1} epochs without improvement in validation loss for {patience} epochs \n')
- # Log Time
- end_time = time.time()
- duration = end_time - start_time
- n_samples = len(train_dataset)
- total_time += duration
- norm_time = duration/n_samples
- timelog_file = os.path.join(timelog_dir, f"{unique_name}.txt")
- with open(timelog_file, "a") as log:
- log.write(f"Fold {fold + 1} - Duration: {duration} seconds - Start Time: {datetime.datetime.fromtimestamp(start_time)} - End Time: {datetime.datetime.fromtimestamp(end_time)} - model params: {sum(p.numel() for p in model.parameters())} \n")
- print(f"-------------------------------------Fold {fold +1} Saved------------------------------------------")
- break
- fold_time = total_time / n_splits
- print(f"Fold training time: {fold_time} seconds")
- # %%
train_reg.py at commit 00f5880, no license · at the source
Overview
- Else Kroener Fresenius Center for Digital Health, Faculty of Medicine, TUD Dresden University of Technology,Dresden, Germany
- Institute and Polyclinic for Diagnostic and Interventional Radiology, Faculty of Medicine and University Hospital Carl Gustav Carus Dresden, Technical University Dresden,Dresden, Germany
- Institute of Diagnostic and Interventional Neuroradiology, Faculty of Medicine and Carl Gustav Carus University Hospital, Technische Universität Dresden,Dresden, Germany
- Department of Diagnostic and Interventional Radiology, University Hospital Aachen,Aachen, Germany
- Department of Medicine I, Faculty of Medicine, TUD Dresden University of Technology,Dresden, Germany
- Medical Oncology, National Center for Tumor Diseases (NCT), University Hospital Heidelberg,Heidelberg, Germany
- Pathology & Data Analytics, Leeds Institute of Medical Research at St James’s, University of Leeds,Leeds, UK
Abstract
Deep learning (DL) methods increasingly outperform classical approaches in brain MRI analysis, yet their generalizability across independent imaging cohorts remains insufficiently evaluated. Because age and sex are fundamental neurobiological factors influencing brain structure and disease risk, this study systematically compares three three-dimensional architectures—Simple Fully Convolutional Network (SFCN), DenseNet121, and Swin Transformer—for age and sex prediction using T1-weighted MRI from four independent cohorts: UK Biobank (UKB, n = 47,390), Dallas Lifespan Brain Study (DLBS, n = 132), Parkinson’s Progression Markers Initiative (PPMI, n = 108 controls), and Information eXtraction from Images (IXI, n = 319). SFCN consistently demonstrated the most robust performance. For sex classification, it achieved an AUC of 1.00 [1.00–1.00] in the UKB internal test set and 0.85–0.91 across external cohorts. For age prediction, SFCN achieved a mean absolute error (MAE) of 2.66 years (r = 0.89) internally and 4.98–5.81 years (r = 0.55–0.70) externally. Pairwise DeLong and Wilcoxon tests with Bonferroni correction confirmed significantly better performance of SFCN compared with Swin Transformer in most cohorts (p < 0.017). No significant demographic subgroup biases were observed. Explainability analyses further showed task-specific and spatially consistent attention patterns across cohorts. These findings demonstrate that simpler convolutional architectures can generalize more reliably than more complex attention-based models in multi-cohort settings. The study highlights the importance of external validation and emphasizes potential trade-offs between model complexity, robustness, and interpretability for clinically relevant neuroimaging applications.
Supplementary Information: The online version contains supplementary material available at 10.1186/
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 2 matches between paragraphs and lines of code.
jrad9921/RadBrainDL
00f5880866ec2e5d51a682723ea6e46aa626edf3, 21 June 2025Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
7 files
- architectures/
sfcn_mod.py , Python, 59 lines, 1 match - dataloaders/
dataloader.py , Python, 54 lines - testers/
test_cls.py , Python, 118 lines - testers/
test_reg.py , Python, 108 lines - trainers/
train_cls.py , Python, 275 lines - trainers/
train_reg.py , Python, 279 lines, 1 match - README.md, Text, 42 lines
Code availability
The underlying code for this study is available on Github and can be accessed via this link https://
Reproduced under the paper's license (CC BY), from the paper cited above.
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;
- 2 matches between paragraphs of the paper and lines of the code (method lexical-v1);
- neither the text of the paper nor the code itself.
Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.
Data
Datasets cited
- openneuro:ds004856, at OpenNeuro; found in “Data availability”
- ukbiobank.ac.uk/
enable-your-research/ , at UK Biobank; found in “Data availability”apply-for-access
Data availability
This study utilized MRI data from the UK Biobank under Application Number 92261. Researchers can request access to the UK Biobank data through the official application process (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, 12 authors, 6 keywords, 1 funder, 73 references.
Cite
This paper
Juglan, R., Ligero, M., Carrero, Z. I., Rabasco Meneghetti, A., Lenz, T., Misera, L., Veldhuizen, G. P., Kuntke, P., Kitzler, H. H., Nebelung, S., Truhn, D., & Kather, J. N. (2026). Generalizable and explainable deep learning for brain MRI: a multi-cohort evaluation of 3D architectures for age and sex prediction. Brain informatics, 13(1), 31. https://
BibTeX
@article{juglan2026gener
author = {Juglan, Radhika and Ligero, Marta and Carrero, Zunamys I. and Rabasco Meneghetti, Asier and Lenz, Tim and Misera, Leo and Veldhuizen, Gregory Patrick and Kuntke, Paul and Kitzler, Hagen H. and Nebelung, Sven and Truhn, Daniel and Kather, Jakob Nikolas},
title = {{Generalizable and explainable deep learning for brain MRI: a multi-cohort evaluation of 3D architectures for age and sex prediction}},
journal = {Brain informatics},
year = {2026},
month = jul,
volume = {13},
number = {1},
pages = {31},
publisher = {Springer},
issn = {2198-4018},
doi = {10.1186/
url = {https://
pmid = {42406258},
pmcid = {PMC13342005}
}
RIS
TY - JOUR
AU - Juglan, Radhika
AU - Ligero, Marta
AU - Carrero, Zunamys I.
AU - Rabasco Meneghetti, Asier
AU - Lenz, Tim
AU - Misera, Leo
AU - Veldhuizen, Gregory Patrick
AU - Kuntke, Paul
AU - Kitzler, Hagen H.
AU - Nebelung, Sven
AU - Truhn, Daniel
AU - Kather, Jakob Nikolas
TI - Generalizable and explainable deep learning for brain MRI: a multi-cohort evaluation of 3D architectures for age and sex prediction
T2 - Brain informatics
J2 - Brain Inform
PY - 2026
DA - 2026/
VL - 13
IS - 1
SP - 31
SN - 2198-4018
PB - Springer
DO - 10.1186/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1186/
"type": "article-journal",
"title": "Generalizable and explainable deep learning for brain MRI: a multi-cohort evaluation of 3D architectures for age and sex prediction",
"container-title": "Brain informatics",
"author": [
{
"family": "Juglan",
"given": "Radhika"
},
{
"family": "Ligero",
"given": "Marta"
},
{
"family": "Carrero",
"given": "Zunamys I."
},
{
"family": "Rabasco Meneghetti",
"given": "Asier"
},
{
"family": "Lenz",
"given": "Tim"
},
{
"family": "Misera",
"given": "Leo"
},
{
"family": "Veldhuizen",
"given": "Gregory Patrick"
},
{
"family": "Kuntke",
"given": "Paul"
},
{
"family": "Kitzler",
"given": "Hagen H."
},
{
"family": "Nebelung",
"given": "Sven"
},
{
"family": "Truhn",
"given": "Daniel"
},
{
"family": "Kather",
"given": "Jakob Nikolas"
}
],
"container-title-short":
"volume": "13",
"issue": "1",
"page": "31",
"DOI": "10.1186/
"PMID": "42406258",
"PMCID": "PMC13342005",
"ISSN": "2198-4018",
"publisher": "Springer",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
7,
6
]
]
}
}
The tracing map gets a citation of its own once an author has validated it and it has a DOI.
Similar papers
The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.
- [1] doi:10.1162/imag.a.1164 [code]
- Bias and generalizability of brain age prediction models: A multi-cohort evaluation with anatomical and interpretability insights.Journal: Imaging neuroscience (Cambridge, Mass.)In common: MONAI, PyTorch, seaborn, 5 other tools, structural MRI / diffusion, 6 references
- [2] doi:10.1002/hbm.70425 [code]
- Brain Age Estimation on T2-FLAIR Scans for Application to Multiple Sclerosis.Journal: Human brain mappingIn common: MONAI, PyTorch, pandas, 2 other tools, structural MRI / diffusion, 7 references
- [3] doi:10.1038/s43856-026-01722-3 [code]
- Local and global patterns support medical imaging as a biomarker of ageing.Journal: Communications medicineIn common: PyTorch, seaborn, pandas, 3 other tools, 6 references
- [4] doi:10.1073/pnas.2519586123 [code]
- Personalized functional topography-based multisite brain age prediction modeling reveals divergent neurodevelopment in major depression.Journal: Proceedings of the National Academy of Sciences of the United States of AmericaIn common: scikit-learn, pandas, SciPy, 1 other tool, structural MRI / diffusion, 6 references
- [5] doi:10.1038/s41398-026-04078-3 [code]
- Brain age prediction in generalized anxiety disorder using a convolutional neural network.Journal: Translational psychiatryIn common: structural MRI / diffusion, 8 references
- [6] doi:10.1162/imag.a.1129
- Deep learning interpretability in neuroimaging: A comprehensive survey and methodological recommendations.Journal: Imaging neuroscience (Cambridge, Mass.)In common: 7 references
- [7] doi:10.1002/hbm.70627 [code]
- Investigating the Contribution of Molecular-Enriched Functional Connectivity to Brain-Age Analysis.Journal: Human brain mappingIn common: NumPy, structural MRI / diffusion, 6 references
- [8] doi:10.1162/imag.a.1242 [code]
- Stable individual differences dominate adult brain volume variation until later life.Journal: Imaging neuroscience (Cambridge, Mass.)In common: PyTorch, seaborn, pandas, 3 other tools, structural MRI / diffusion, 4 references
- [9] doi:10.1073/pnas.2516601123 [code]
- Unveiling the glymphatic system's role in brain aging: A comprehensive biomarker and modifiable intervention target.Journal: Proceedings of the National Academy of Sciences of the United States of AmericaIn common: seaborn, scikit-learn, pandas, 3 other tools, structural MRI / diffusion, 4 references
- [10] doi:10.1371/journal.pbio.3003856 [code]
- Aging and metabolism contribute separately to brain-body health.Journal: PLoS biologyIn common: PyTorch, seaborn, scikit-learn, 4 other tools, structural MRI / diffusion, 3 references
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, 6 scripts, and 2 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:c5a9720c5c03c08d…
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.
