OSCR

Cross-Site Generalization of CNN-Based $$ {B}_1^{+} $$ Mapping in UHF MRI.

Code ↔ Paper

2 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 2 matches
  1. [1] § Methods › MRI Data Acquisition and Data Processing ↔ Train_Complex_Model_Save_Model.ipynb, lines 40–122 · score 0.63 · imaginary parts, localizer images, Tx channels, split, magnitude, training
  2. [2] § Methods › MRI Data Acquisition and Data Processing ↔ Train_Complex_Model_Save_Model.ipynb, lines 603–744 · score 0.54 · trainable parameters, ADAM, epoch, batch, optimizer, validation

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 · 762 lines · 24 KB · no license · 2 matches

  1. # %% [markdown]
  2. # # Packages
  3. # %%
  4. ! git clone https://github.com/soumickmj/pytorch-complex.git
  5. ! mv /content/pytorch-complex/* .
  6. !pip install torchinfo
  7. # %%
  8. # Import necessary libraries
  9. import os
  10. import time
  11. import numpy as np
  12. import matplotlib.pyplot as plt
  13. import h5py
  14. import torch
  15. import torch.optim as optim
  16. import torch.nn as nn
  17. import torch.nn.functional as F
  18. import torch.optim.lr_scheduler as lr_scheduler
  19. from torch.utils.data import Dataset, TensorDataset, random_split, SubsetRandomSampler, ConcatDataset, DataLoader
  20. from sklearn.model_selection import KFold, train_test_split
  21. from skimage.metrics import structural_similarity as ssim
  22. from torchinfo import summary
  23. # Import custom complex number support for PyTorch
  24. import torchcomplex
  25. from torchcomplex import nn
  26. # %%
  27. device = "cuda" # if torch.cuda.is_available() else "cpu"
  28. device = torch.device('cuda:0')
  29. # %%
  30. # %% [markdown]
  31. # # Data Import
  32. # %%
  33. def process_training_data(train_file_path):
  34. """
  35. Load training data from an HDF5 (.mat) file and convert
  36. real/imaginary channel pairs into complex-valued arrays.
  37. Parameters
  38. ----------
  39. train_file_path : str
  40. Path to the training HDF5 file.
  41. Returns
  42. -------
  43. x_ : np.ndarray
  44. Complex-valued localizer training data.
  45. y_ : np.ndarray
  46. Complex-valued input (target) training data.
  47. """
  48. # ------------------------------------------------------------
  49. # Load data
  50. # ------------------------------------------------------------
  51. with h5py.File(train_file_path, "r") as train_file:
  52. # "x" data (localizer)
  53. localizer_data_train = train_file["lvLovalizerSave"][:, :, :, :].astype(np.float32)
  54. # "y" data (input / target)
  55. input_data_train = train_file["lvSaveDataInput"][:, :, :, :].astype(np.float32)
  56. print("\nOriginal Shapes:")
  57. print("Training Input Data Shape:", input_data_train.shape)
  58. print("Training Localizer Data Shape:", localizer_data_train.shape)
  59. # ------------------------------------------------------------
  60. # Move channel axis: axis 2 -> last
  61. # ------------------------------------------------------------
  62. localizer_data_train = np.moveaxis(localizer_data_train, 2, -1)
  63. input_data_train = np.moveaxis(input_data_train, 2, -1)
  64. print("\nAfter Moving Axis:")
  65. print("Training Input Data Shape:", input_data_train.shape)
  66. print("Training Localizer Data Shape:", localizer_data_train.shape)
  67. # ------------------------------------------------------------
  68. # Remove magnitude channel (localizer with all Tx channels on)
  69. # ------------------------------------------------------------
  70. localizer_data_train = np.delete(localizer_data_train, 0, axis=1)
  71. print("\nAfter Deleting Magnitude Value:")
  72. print("Training Localizer Data Shape:", localizer_data_train.shape)
  73. # ------------------------------------------------------------
  74. # Split real / imaginary parts
  75. # ------------------------------------------------------------
  76. # Localizer
  77. localizer_real_train = localizer_data_train[:, ::2, :, :]
  78. localizer_imag_train = localizer_data_train[:, 1::2, :, :]
  79. # Input / target
  80. input_real_train = input_data_train[:, ::2, :, :]
  81. input_imag_train = input_data_train[:, 1::2, :, :]
  82. # ------------------------------------------------------------
  83. # Combine into complex-valued arrays
  84. # ------------------------------------------------------------
  85. x_ = localizer_real_train + 1j * localizer_imag_train
  86. y_ = input_real_train + 1j * input_imag_train
  87. print("\nComplex Training Data Shapes:")
  88. print("Complex Training Localizer Data Shape:", x_.shape)
  89. print("Complex Training Input Data Shape:", y_.shape)
  90. return x_, y_
  91. # ------------------------------------------------------------
  92. # Example usage
  93. # ------------------------------------------------------------
  94. train_file_path = "TrainingData.mat"
  95. x_, y_ = process_training_data(train_file_path)
  96. # %% [markdown]
  97. # %%
  98. def process_validation_data(val_file_path):
  99. """
  100. Load validation data from an HDF5 (.mat) file and convert
  101. real/imaginary channel pairs into complex-valued arrays.
  102. Parameters
  103. ----------
  104. val_file_path : str
  105. Path to the validation HDF5 file.
  106. Returns
  107. -------
  108. x_test_ : np.ndarray
  109. Complex-valued localizer validation data.
  110. y_test_ : np.ndarray
  111. Complex-valued input (target) validation data.
  112. """
  113. # ------------------------------------------------------------
  114. # Load data
  115. # ------------------------------------------------------------
  116. with h5py.File(val_file_path, "r") as val_file:
  117. # "x_test" data (localizer)
  118. localizer_data_val = val_file["lvLovalizerSave"][:, :, :]
  119. # "y_test" data (input / target)
  120. input_data_val = val_file["lvSaveDataInput"][:, :, :, :]
  121. print("\nOriginal Shapes:")
  122. print("Validation Input Data Shape:", input_data_val.shape)
  123. print("Validation Localizer Data Shape:", localizer_data_val.shape)
  124. # ------------------------------------------------------------
  125. # Move axes
  126. # ------------------------------------------------------------
  127. localizer_data_val = np.moveaxis(localizer_data_val, 2, -1)
  128. input_data_val = np.moveaxis(input_data_val, 2, -1)
  129. input_data_val = np.moveaxis(input_data_val, 1, -1)
  130. print("\nAfter Moving Axis:")
  131. print("Validation Input Data Shape:", input_data_val.shape)
  132. print("Validation Localizer Data Shape:", localizer_data_val.shape)
  133. # ------------------------------------------------------------
  134. # Remove magnitude channel (localizer with all Tx channels on)
  135. # ------------------------------------------------------------
  136. localizer_data_val = np.delete(localizer_data_val, 0, axis=1)
  137. print("\nAfter Deleting Magnitude Value:")
  138. print("Validation Localizer Data Shape:", localizer_data_val.shape)
  139. # ------------------------------------------------------------
  140. # Split real / imaginary parts
  141. # ------------------------------------------------------------
  142. # Localizer
  143. localizer_real_val = localizer_data_val[:, ::2, :, :]
  144. localizer_imag_val = localizer_data_val[:, 1::2, :, :]
  145. # Input / target
  146. input_real_val = input_data_val[:, ::2, :, :]
  147. input_imag_val = input_data_val[:, 1::2, :, :]
  148. # ------------------------------------------------------------
  149. # Combine into complex-valued arrays
  150. # ------------------------------------------------------------
  151. x_test_ = localizer_real_val + 1j * localizer_imag_val
  152. y_test_ = input_real_val + 1j * input_imag_val
  153. print("\nComplex Validation Data Shapes:")
  154. print("Complex Validation Localizer Data Shape:", x_test_.shape)
  155. print("Complex Validation Input Data Shape:", y_test_.shape)
  156. return x_test_, y_test_
  157. # ------------------------------------------------------------
  158. # Example usage
  159. # ------------------------------------------------------------
  160. val_file_path = ("ValidationData.mat")
  161. x_test_, y_test_ = process_validation_data(val_file_path)
  162. # %%
  163. # Convert to PyTorch tensor and move to device
  164. x_test_tensor = torch.from_numpy(x_test_).to(device)
  165. # %%
  166. # %% [markdown]
  167. # # Custom Functions
  168. # %%
  169. def size_of(x):
  170. print(x.numel()*x.element_size()/1024/1024)
  171. def count(net):
  172. return sum(p.numel() for p in net.parameters())
  173. # %%
  174. ###---###---###---###
  175. ''' Initial weights '''
  176. ###---###---###---###
  177. def _init_weights(module):
  178. if isinstance(module, torchcomplex.nn.Conv2d):
  179. module.weight.data.normal_(mean=0.0, std=0.02)
  180. # %% [markdown]
  181. # # Loss Function
  182. # %%
  183. ###---###---###---###
  184. """ Loss Function """
  185. ###---###---###---###
  186. class ComplexMSELoss:
  187. def __call__(self, true, prediction):
  188. # Convert NumPy arrays to PyTorch tensors of complex64 type right at the beginning
  189. true_tensor = torch.tensor(true, dtype=torch.complex64)
  190. prediction_tensor = torch.tensor(prediction, dtype=torch.complex64)
  191. # Perform the MSE computation
  192. return (0.5 * (true_tensor - prediction_tensor) ** 2).mean()
  193. class PerpLoss(nn.Module):
  194. def __init__(self, eps=1e-8, l1factor=1.0, mask=False):
  195. super(PerpLoss, self).__init__()
  196. self.eps = eps
  197. self.l1factor = l1factor
  198. self.mask = mask
  199. def forward(self, target, prediction):
  200. # Calculate the cross term as the absolute value of the determinant of the complex numbers
  201. cross = torch.abs(target.real * prediction.imag - target.imag * prediction.real)
  202. # Calculate the perpendicular loss component
  203. ploss_raw = cross / (torch.abs(prediction) + self.eps)
  204. # Corrected: Ensure the mask is a boolean tensor
  205. # Here, it's assumed that you want to mask based on the condition that involves 'target'
  206. # Adjust the condition according to your specific requirements
  207. mask = target.abs() > 1e-3 # This now produces a boolean tensor
  208. angle_smaller_90 = ((target / prediction).real > 0).detach() # is the angle < pi/2 ?
  209. # Calculate the final loss with the conditional mask applied
  210. # torch.where now receives a boolean tensor as expected
  211. ploss = torch.where(angle_smaller_90, ploss_raw, 2 * torch.abs(target) - ploss_raw)
  212. l1loss = torch.nn.functional.l1_loss(prediction, target, reduction='none')
  213. loss = ploss + self.l1factor * l1loss
  214. if self.mask:
  215. loss = (loss * mask).sum() / (mask.sum() + self.eps) # Returning the maksed mean loss over all elements
  216. else:
  217. loss = loss.mean() # return the mean over all elements
  218. return loss
  219. # %% [markdown]
  220. # # 2D Convolutional Block
  221. # %%
  222. ###---###---###---###
  223. """ 2D Convolutional Block """
  224. ###---###---###---###
  225. class C2D_Block(nn.Module):
  226. def __init__(self, in_c, n_filters, batchnorm, skip):
  227. super().__init__()
  228. self.conv1 = torchcomplex.nn.Conv2d(in_c, n_filters, kernel_size=3, padding=1)
  229. if batchnorm:
  230. self.bn1 = torchcomplex.nn.BatchNorm2d(n_filters)
  231. self.bn2 = torchcomplex.nn.BatchNorm2d(n_filters)
  232. else:
  233. self.bn1 = None
  234. self.bn2 = None
  235. # self.relu1 = torchcomplex.nn.CReLU() - do not use CReLU here, look up in docs
  236. self.relu1 = torchcomplex.nn.AdaptiveCmodReLU(n_filters)
  237. self.conv2 = torchcomplex.nn.Conv2d(n_filters, n_filters, kernel_size=3, padding=1)
  238. # self.relu2 = torchcomplex.nn.CReLU() - do not use CReLU here, look up in docs
  239. self.relu2 = torchcomplex.nn.AdaptiveCmodReLU(n_filters)
  240. if skip:
  241. self.skip = torchcomplex.nn.Conv2d(in_c, n_filters, kernel_size=1)
  242. with torch.no_grad():
  243. self.skip.bias.zero_()
  244. else:
  245. self.skip = None
  246. def forward(self, xin):
  247. x = self.conv1(xin)
  248. if self.bn1:
  249. x = self.bn1(x)
  250. x = self.relu1(x)
  251. x = self.conv2(x)
  252. if self.bn2:
  253. x = self.bn2(x)
  254. if self.skip:
  255. x = x + self.skip(xin)
  256. x = self.relu2(x)
  257. return x
  258. # %% [markdown]
  259. # # Encoder
  260. # %%
  261. ###---###---###---###
  262. """ Encoder """
  263. ###---###---###---###
  264. class Encoder(nn.Module):
  265. def __init__(self, in_c, dropout, features, maxpool, batchnorm, skip):
  266. super().__init__()
  267. self.encBlocks = nn.ModuleList()
  268. self.downsamples = nn.ModuleList()
  269. for feature in features:
  270. self.encBlocks.append(C2D_Block(in_c, feature, batchnorm=batchnorm, skip=skip))
  271. if maxpool:
  272. self.downsamples.append(torchcomplex.nn.MaxPool2d(2))
  273. in_c = feature
  274. else:
  275. down = torch.nn.Sequential(
  276. torchcomplex.nn.Conv2d(feature, features[-1], kernel_size=3, stride=2, padding=1), torchcomplex.nn.AdaptiveCmodReLU(features[-1])
  277. )
  278. self.downsamples.append(down)
  279. in_c = features[-1]
  280. self.dropouts = torchcomplex.nn.Dropout2d(dropout) if dropout else torch.nn.Identity()
  281. self.dropout2 = torchcomplex.nn.Dropout2d(dropout * 2) if dropout else torch.nn.Identity()
  282. self.dropout3 = torchcomplex.nn.Dropout2d(dropout * 3) if dropout else torch.nn.Identity()
  283. # self.bottleneck = C2D_Block(features[-1], features[-1]*2)
  284. self.bottleneck = torch.nn.Sequential(
  285. torchcomplex.nn.Conv2d(features[-1], features[-1], kernel_size=3, padding=1), torchcomplex.nn.AdaptiveCmodReLU( features[-1])
  286. )
  287. def forward(self, x):
  288. skip_connections = []
  289. # downsampling
  290. for depth, (block, down) in enumerate(zip(self.encBlocks, self.downsamples)):
  291. x = block(x)
  292. skip_connections.append(x)
  293. x = down(x)
  294. if depth < 2:
  295. x = self.dropout1(x)
  296. else:
  297. x = self.dropout2(x)
  298. x = self.bottleneck(x)
  299. x = self.dropout3(x)
  300. return x, skip_connections
  301. # %% [markdown]
  302. # # Decoder
  303. # %%
  304. ###---###---###---###
  305. """ Decoder """
  306. ###---###---###---###
  307. class Decoder(nn.Module):
  308. def __init__(self, dropout, features, upsample, batchnorm, skip):
  309. super().__init__()
  310. features_out = list(reversed(features))
  311. features_in = [features[-1], *features[:0:-1]]
  312. self.upConvs = nn.ModuleList()
  313. self.decBlocks = nn.ModuleList()
  314. for fin, fout in zip(features_in, features_out):
  315. if upsample:
  316. self.upConvs.append(
  317. torch.nn.Sequential(
  318. torchcomplex.nn.Upsample(mode="bilinear", scale_factor=2, size=None),
  319. torchcomplex.nn.Conv2d(fin, fout, kernel_size=3, padding=1),
  320. torchcomplex.nn.AdaptiveCmodReLU(fout),
  321. )
  322. )
  323. else:
  324. self.upConvs.append(
  325. torch.nn.Sequential(
  326. torchcomplex.nn.ConvTranspose2d(fin, fout, 2, stride=2),
  327. torchcomplex.nn.AdaptiveCmodReLU(fout),
  328. )
  329. )
  330. self.decBlocks.append(C2D_Block(2 * fout, fout, batchnorm=batchnorm, skip=skip))
  331. # with torch.no_grad():
  332. # self.upConvs.apply(_init_weights)
  333. self.dropout1 = torchcomplex.nn.Dropout2d(dropout) if dropout else torch.nn.Identity()
  334. self.dropout2 = torchcomplex.nn.Dropout2d(dropout * 2) if dropout else torch.nn.Identity()
  335. def forward(self, x, skipped_feautures):
  336. for depth, (up, block, skipped) in enumerate(zip(self.upConvs, self.decBlocks, skipped_feautures, strict=True)):
  337. x = up(x)
  338. x = torch.cat([x, skipped], dim=1)
  339. x = block(x)
  340. if depth < 2:
  341. x = self.dropout2(x)
  342. else:
  343. x = self.dropout1(x)
  344. return x
  345. def crop(self, encFeaturs, x):
  346. (_, _, H, W) = x.shape
  347. encFeaturs = CenterCrop([H, W])(encFeaturs)
  348. return encFeaturs
  349. # %%
  350. class Head(nn.Module):
  351. def __init__(self, features_in, features_out=1, features_hidden=(64,32,16)):
  352. super().__init__()
  353. modules = []
  354. fin = features_in
  355. for fout in features_hidden:
  356. modules.append(torchcomplex.nn.Conv2d(fin,fout, 3, padding=1))
  357. modules.append(torchcomplex.nn.AdaptiveCmodReLU(fout))
  358. fin = fout
  359. modules.append(torchcomplex.nn.Conv2d(fin, features_out, 3, padding=1))
  360. self.net = torch.nn.Sequential(*modules)
  361. with torch.no_grad():
  362. self.net[-1].bias.zero_()
  363. def forward(self,x):
  364. return self.net(x)
  365. # %% [markdown]
  366. # # UNet
  367. # %%
  368. ###---###---###---###
  369. """ UNet """
  370. ###---###---###---###
  371. class UNet(nn.Module):
  372. def __init__(self, in_c, out_c, dropout, features, maxpool=True, upsample=False, batchnorm=False, skip=True):
  373. super().__init__()
  374. self.encoder = Encoder(in_c, dropout, features, maxpool=maxpool, batchnorm=batchnorm, skip=skip)
  375. self.decoder1 = Decoder(dropout, features, upsample=upsample, batchnorm=batchnorm, skip=skip)
  376. self.decoder2 = Decoder(dropout, features ,upsample=upsample, batchnorm=batchnorm, skip=skip)
  377. self.decoder3 = Decoder(dropout, features ,upsample=upsample, batchnorm=batchnorm, skip=skip)
  378. self.decoder4 = Decoder(dropout, features ,upsample=upsample, batchnorm=batchnorm, skip=skip)
  379. self.decoder5 = Decoder(dropout, features ,upsample=upsample, batchnorm=batchnorm, skip=skip)
  380. self.decoder6 = Decoder(dropout, features ,upsample=upsample, batchnorm=batchnorm, skip=skip)
  381. self.decoder7 = Decoder(dropout, features ,upsample=upsample, batchnorm=batchnorm, skip=skip)
  382. self.decoder8 = Decoder(dropout, features ,upsample=upsample, batchnorm=batchnorm, skip=skip)
  383. self.head1 = Head(features[0], out_c)
  384. self.head2 = Head(features[0], out_c)
  385. self.head3 = Head(features[0], out_c)
  386. self.head4 = Head(features[0], out_c)
  387. self.head5 = Head(features[0], out_c)
  388. self.head6 = Head(features[0], out_c)
  389. self.head7 = Head(features[0], out_c)
  390. self.head8 = Head(features[0], out_c)
  391. def forward(self, x):
  392. x, encFeatures = self.encoder(x)
  393. decFeatures1 = self.decoder1(x, encFeatures[::-1])
  394. output1 = self.head1(decFeatures1)
  395. decFeatures2 = self.decoder2(x, encFeatures[::-1])
  396. output2 = self.head2(decFeatures2)
  397. decFeatures3 = self.decoder3(x, encFeatures[::-1])
  398. output3 = self.head3(decFeatures3)
  399. decFeatures4 = self.decoder4(x, encFeatures[::-1])
  400. output4 = self.head4(decFeatures4)
  401. decFeatures5 = self.decoder5(x, encFeatures[::-1])
  402. output5 = self.head5(decFeatures5)
  403. decFeatures6 = self.decoder6(x, encFeatures[::-1])
  404. output6 = self.head6(decFeatures6)
  405. decFeatures7 = self.decoder7(x, encFeatures[::-1])
  406. output7 = self.head7(decFeatures7)
  407. decFeatures8 = self.decoder8(x, encFeatures[::-1])
  408. output8 = self.head8(decFeatures8)
  409. return output1, output2, output3, output4, output5, output6, output7, output8
  410. # %%
  411. # %% [markdown]
  412. # # Data preparation
  413. # %%
  414. # ============================================================
  415. # Data preparation
  416. # ============================================================
  417. # Convert input data to PyTorch tensor
  418. x_tensor = torch.from_numpy(x_)
  419. # Select first 8 channels from target data
  420. y_tensor = torch.tensor(y_[:, 0:8, :, :])
  421. # Create TensorDataset:
  422. # x_tensor : input
  423. # y_tensor split : one tensor per Tx channel
  424. data = TensorDataset(
  425. x_tensor,
  426. *y_tensor.unsqueeze(2).unbind(1)
  427. )
  428. # Split into training and validation sets (80 / 20)
  429. train_dataset, val_dataset = random_split(
  430. data,
  431. [0.8, 0.2]
  432. )
  433. # Concatenate back if a unified dataset is required
  434. dataset = ConcatDataset([train_dataset, val_dataset])
  435. # %% [markdown]
  436. # # Hyperparameters
  437. # %%
  438. # ============================================================
  439. # Hyperparameters
  440. # ============================================================
  441. # Add light Gaussian noise to input images in a fraction of cases
  442. params = dict(
  443. lr=1e-4, # lower LR for long, stable training
  444. gamma=0.9985, # very slow exponential decay over 4000 epochs
  445. batch_size=1,
  446. dropout=0.005, # slightly higher to counter long training
  447. num_epochs=4000,
  448. weight_decay=0.05, # regularization to prevent overfitting
  449. features=(32, 32, 64, 128, 256),
  450. maxpool=True,
  451. batchnorm=False,
  452. skip=True,
  453. upsample=True,
  454. clip_grad_norm=1.0, # safety for long runs
  455. )
  456. # ------------------------------------------------------------
  457. # Loss function
  458. # ------------------------------------------------------------
  459. criterion = lambda gt, pred: torch.nn.functional.mse_loss(
  460. torch.view_as_real(gt),
  461. torch.view_as_real(pred),
  462. )
  463. # %% [markdown]
  464. # # Train Model
  465. # %%
  466. # ============================================================
  467. # Reproducibility
  468. # ============================================================
  469. torch.manual_seed(42)
  470. # ============================================================
  471. # Model
  472. # ============================================================
  473. model = UNet(
  474. in_c=32,
  475. out_c=1,
  476. dropout=params["dropout"],
  477. features=params["features"],
  478. maxpool=params["maxpool"],
  479. skip=params["skip"],
  480. batchnorm=params["batchnorm"],
  481. upsample=params["upsample"],
  482. ).to(device)
  483. n_params = sum(p.numel() for p in model.parameters())
  484. print(f"{n_params / 1e6:.2f} Mio.")
  485. print("number_trainable_parameters =", n_params)
  486. print(model)
  487. # If criterion is a callable/loss instance, this is just informational
  488. try:
  489. print("criterion =", criterion.__class__.__name__)
  490. except Exception:
  491. pass
  492. # ============================================================
  493. # Train/val split (via samplers)
  494. # ============================================================
  495. train_loss = []
  496. valid_loss = []
  497. start_time = time.time()
  498. train_idx, val_idx = torch.utils.data.random_split(
  499. torch.arange(len(dataset)),
  500. (0.9, 0.1),
  501. )
  502. train_loader = DataLoader(
  503. dataset,
  504. batch_size=params["batch_size"],
  505. sampler=SubsetRandomSampler(train_idx),
  506. num_workers=10,
  507. )
  508. val_loader = DataLoader(
  509. dataset,
  510. batch_size=params["batch_size"],
  511. sampler=SubsetRandomSampler(val_idx),
  512. num_workers=10,
  513. )
  514. # ============================================================
  515. # Optimizer + scheduler
  516. # ============================================================
  517. optimizer = optim.AdamW(
  518. model.parameters(),
  519. lr=params["lr"],
  520. weight_decay=params["weight_decay"],
  521. )
  522. scheduler = lr_scheduler.ExponentialLR(
  523. optimizer,
  524. gamma=params["gamma"],
  525. )
  526. # ============================================================
  527. # Training loop
  528. # ============================================================
  529. for epoch in range(params["num_epochs"]):
  530. epoch_start = time.time()
  531. # ------------------------
  532. # Train
  533. # ------------------------
  534. model.train()
  535. train_epoch_loss = 0.0
  536. for step, (x, *y) in enumerate(train_loader):
  537. x = x.to(device)
  538. y = [yi.to(device) for yi in y]
  539. optimizer.zero_grad()
  540. outputs = model(x) # expected: iterable/list of heads
  541. head_losses = [criterion(out_i, y_i) for out_i, y_i in zip(outputs, y)]
  542. loss = sum(head_losses) / len(head_losses)
  543. loss.backward()
  544. torch.nn.utils.clip_grad_norm_(model.parameters(), params["clip_grad_norm"])
  545. optimizer.step()
  546. train_epoch_loss += loss.item()
  547. avg_train_loss = train_epoch_loss / len(train_loader)
  548. train_loss.append(avg_train_loss)
  549. # LR step (printed explicitly)
  550. lr_before = optimizer.param_groups[0]["lr"]
  551. scheduler.step()
  552. lr_after = optimizer.param_groups[0]["lr"]
  553. print("\n" + "-" * 60)
  554. print(f"Epoch {epoch + 1:4d}/{params['num_epochs']} | train_loss: {avg_train_loss:.6f}")
  555. print(f"lr: {lr_before:.6e} -> {lr_after:.6e}")
  556. # ------------------------
  557. # Validation
  558. # ------------------------
  559. model.eval()
  560. val_epoch_loss = 0.0
  561. with torch.no_grad():
  562. for x, *y in val_loader:
  563. x = x.to(device)
  564. y = [yi.to(device) for yi in y]
  565. outputs = model(x)
  566. head_losses = [criterion(out_i, y_i) for out_i, y_i in zip(outputs, y)]
  567. val_loss = sum(head_losses) / len(head_losses)
  568. val_epoch_loss += val_loss.item()
  569. avg_val_loss = val_epoch_loss / len(val_loader)
  570. valid_loss.append(avg_val_loss)
  571. epoch_time = time.time() - epoch_start
  572. print(f"val_loss: {avg_val_loss:.6f} | epoch_time: {epoch_time:.2f}s")
  573. # ============================================================
  574. # Done
  575. # ============================================================
  576. total_time = time.time() - start_time
  577. print(f"\n[INFO] total time taken to train the model: {total_time:.2f}s")
  578. # %% [markdown]
  579. # # Save Model
  580. # %%
  581. torch.save(
  582. {
  583. "epochs": epoch,
  584. "parameters": params,
  585. "model_state_dict": model.state_dict(),
  586. "optimizer_state_dict": optimizer.state_dict(),
  587. "train_loss": train_loss[-1],
  588. "validation_loss": valid_loss[-1],
  589. },
  590. 'SaveModel.pth',
  591. )

Train_Complex_Model_Save_Model.ipynb at commit 7d80d96, no license · at the source

Overview

  1. Physikalisch‐Technische Bundesanstalt Berlin Germany
  2. Medical Physics in Radiology German Cancer Research Center (DKFZ) Heidelberg Germany
  3. Faculty of Physics and Astronomy Heidelberg University Heidelberg Germany
  4. Center for Magnetic Resonance Research University of Minnesota Minneapolis Minnesota USA
  5. Institute for Applied Medical Informatics University Medical Center Hamburg‐Eppendorf (UKE) Hamburg Germany
  6. Max Planck Research Group MR Physics, Max Planck Institute for Human Development Berlin Germany
Journal: NMR in biomedicine, volume 39, issue 5, article e70263
Dates: received 18 September 2025; accepted 13 February 2026; published online 6 April 2026; in print May 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1002/nbm.70263 · PMID 41937594 · PMCID PMC13051333 · OpenAlex W7150966690
Open access: hybrid, a free copy (OpenAlex)
Status: code verified
Categories: structural MRI / diffusion (modality), human (organism), methods / tools (subfield)
Methods: Machine learning, Statistics
Keywords: 7T, B1+ mapping, brain, deep learning, model generalization, model transferability, parallel transmission
MeSH: Brain Mapping*, Convolutional Neural Networks*, Image Processing, Computer-Assisted*, Magnetic Resonance Imaging*, Humans (* major topic)
Topic: Functional Brain Connectivity Studies (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Funding: Deutsche Forschungsgemeinschaft (DFG) (SCHM 2677/4‐1, SCHM 2677/5‐1, GRK2260, BIOQIC)
Citations: not cited yet (Europe PMC); 48 references in the paper

Abstract

Convolutional neural networks (CNNs) can rapidly predict channel‐wise B1+ maps from 7T localizer images, reducing acquisition time to seconds. This paper investigates if a CNN trained on one site's data can generalize to predict B1+ maps for brain imaging at unseen sites supporting the feasibility of a universal network for subject‐specific B1+‐ mapping. We evaluated a U‐Net CNN cross‐site generalization by training on datasets from two different 7T sites and testing its performance across three 7T sites (1 additional testing site) to assess robustness, adaptability, and generalization. The study design included both commercially same systems and the identical physical hardware unit transported between two sites, enabling a more insightful attribution of performance differences to either hardware issues or dataset‐specific variations.

To assess prediction quality, we examined magnitude/phase images, error maps, correlation plots, Pearson coefficients, and residual spread plots. Quantitative evaluation included RMSE and SSIM scores. Finally, we calculated 4 kT‐points pulses with both on‐site and cross‐site CNNs to evaluate the effectiveness of the obtained B1+ maps for parallel‐transmission (pTx).

While on‐site B1+ transversal magnitude RMSE scores were as low as 3.0% and 3.1% for the two CNNs, their respective transfer yielded 3.6% and 4.1%. The dynamic pTx‐application showed a CV of 6.5% when using B1+ maps predicted by a network trained on its own site. The transfer case, using a map predicted from a network trained on a different site, yielded an increased CV of 13.7%.

Although cross‐site applications introduced larger deviations, the predicted maps remained qualitatively plausible and enabled practical use cases, such as calculating dynamic‐pTx. These findings support the potential of cross‐site training, suggesting CNNs trained at one site may generalize sufficiently to unseen sites without additional adjustments. This strengthens the feasibility of a transferable training approach where a single network could be deployed across different institutions without extensive retraining.

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.

hkimon/B1P_Mapping_CCN

License: none: the authors keep all their rights
State: the link answers, verified on 28 September 2026
Evidence: files inventoried
Commit: 7d80d9675182f215bbe3e8c16080c05cbc002a27, 23 January 2026
Languages: Jupyter (5)
Size: 7 files, 5 scripts
Software Heritage: not archived
Found in: “Data Availability Statement”
Holds: 5 notebooks
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: h5py (5 files), Matplotlib (5 files), NumPy (5 files), Keras (3 files), scikit-image (3 files), scikit-learn (3 files), TensorFlow (3 files), PyTorch (2 files), pandas (1 file), SciPy (1 file)
Availability: 1 check, the latest on 28 September 2026: the link answers
  • 28 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;
  • 5 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

Data Availability Statement

The data supporting the findings of this study are openly available in Zenodo at https://doi.org/10.5281/zenodo.18338273. The code used for data processing, model training, and evaluation is available at GitHub at https://github.com/hkimon/B1P_Mapping_CCN.git.

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 2, 28 September 2026

  • Publisher: n/a → Wiley

Version 1, 28 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 14 authors, 7 keywords, 5 MeSH terms, 1 funder, 43 references.

Cite

This paper

Hadjikiriakos, K., Krüger, F., Zimmermann, F. F., Grimm, J. A., Schorling, C., Lutz, M., Schmidt, S., Riemann, L. T., Degenhardt, K., Schäffter, T., Ladd, M. E., Metzger, G. J., Aigner, C. S., & Schmitter, S. (2026). Cross-Site Generalization of CNN-Based $$ {B}_1^{+} $$ Mapping in UHF MRI. NMR in biomedicine, 39(5), e70263. https://doi.org/10.1002/nbm.70263

BibTeX

@article{hadjikiriakos2026cross,
author = {Hadjikiriakos, Kimon and Krüger, Felix and Zimmermann, Felix Frederik and Grimm, Johannes A. and Schorling, Constantin and Lutz, Max and Schmidt, Simon and Riemann, Layla Tabea and Degenhardt, Katja and Schäffter, Tobias and Ladd, Mark E. and Metzger, Gregory J. and Aigner, Christoph Stefan and Schmitter, Sebastian},
title = {{Cross-Site Generalization of CNN-Based \$\$ \{B\}\_1\textasciicircum{}\{+\} \$\$ Mapping in UHF MRI}},
journal = {NMR in biomedicine},
year = {2026},
month = may,
volume = {39},
number = {5},
pages = {e70263},
publisher = {Wiley},
issn = {0952-3480},
doi = {10.1002/nbm.70263},
url = {https://doi.org/10.1002/nbm.70263},
pmid = {41937594},
pmcid = {PMC13051333}
}

RIS

TY - JOUR
AU - Hadjikiriakos, Kimon
AU - Krüger, Felix
AU - Zimmermann, Felix Frederik
AU - Grimm, Johannes A.
AU - Schorling, Constantin
AU - Lutz, Max
AU - Schmidt, Simon
AU - Riemann, Layla Tabea
AU - Degenhardt, Katja
AU - Schäffter, Tobias
AU - Ladd, Mark E.
AU - Metzger, Gregory J.
AU - Aigner, Christoph Stefan
AU - Schmitter, Sebastian
TI - Cross-Site Generalization of CNN-Based $$ {B}_1^{+} $$ Mapping in UHF MRI
T2 - NMR in biomedicine
J2 - NMR Biomed
PY - 2026
DA - 2026/05/01
VL - 39
IS - 5
SP - e70263
SN - 0952-3480
PB - Wiley
DO - 10.1002/nbm.70263
UR - https://doi.org/10.1002/nbm.70263
LA - en
ER -

CSL-JSON

{
"id": "10.1002/nbm.70263",
"type": "article-journal",
"title": "Cross-Site Generalization of CNN-Based $$ {B}_1^{+} $$ Mapping in UHF MRI",
"container-title": "NMR in biomedicine",
"author": [
{
"family": "Hadjikiriakos",
"given": "Kimon"
},
{
"family": "Krüger",
"given": "Felix"
},
{
"family": "Zimmermann",
"given": "Felix Frederik"
},
{
"family": "Grimm",
"given": "Johannes A."
},
{
"family": "Schorling",
"given": "Constantin"
},
{
"family": "Lutz",
"given": "Max"
},
{
"family": "Schmidt",
"given": "Simon"
},
{
"family": "Riemann",
"given": "Layla Tabea"
},
{
"family": "Degenhardt",
"given": "Katja"
},
{
"family": "Schäffter",
"given": "Tobias"
},
{
"family": "Ladd",
"given": "Mark E."
},
{
"family": "Metzger",
"given": "Gregory J."
},
{
"family": "Aigner",
"given": "Christoph Stefan"
},
{
"family": "Schmitter",
"given": "Sebastian"
}
],
"container-title-short": "NMR Biomed",
"volume": "39",
"issue": "5",
"page": "e70263",
"DOI": "10.1002/nbm.70263",
"PMID": "41937594",
"PMCID": "PMC13051333",
"ISSN": "0952-3480",
"publisher": "Wiley",
"URL": "https://doi.org/10.1002/nbm.70263",
"language": "en",
"issued": {
"date-parts": [
[
2026,
5,
1
]
]
}
}

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.1002/mrm.70431 [code]
SelExNet: A Self-Supervised Physics-Informed Framework for Multi-Channel Joint RF and Gradient Waveform Optimization in 2D Spatially Selective Excitation.
Journal: Magnetic resonance in medicine
In common: PyTorch, SciPy, Matplotlib, 1 other tool, structural MRI / diffusion, 5 references
[2] doi:10.1002/nbm.70228 [code]
Transceiver 16-Channel Coaxial-End Dipole Array for Combined Head and C-Spine MRI at 9.4 T.
Journal: NMR in biomedicine
In common: structural MRI / diffusion, 7 references
[3] doi:10.1162/imag.a.1362 [code]
Human fMRI at 11.7T: Assessing feasibility, stability, and reliability on the Iseult scanner.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: h5py, pandas, SciPy, 2 other tools, methods / tools, 4 references
[4] doi:10.1093/nar/gkag706 [code]
scDifformer: diffusion-based post-training for virtual cell modeling across large-scale single-cell data.
Journal: Nucleic acids research
In common: Keras, TensorFlow, scikit-image, 7 other tools
[5] doi:10.1162/imag.a.1183 [code]
Learning-based segmentation of diffusion-weighted MR images with arbitrary &lt;i&gt;q&lt;/i&gt;-space samplings.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: Keras, TensorFlow, scikit-image, 6 other tools, methods / tools, structural MRI / diffusion
[6] doi:10.1364/boe.605322 [code]
Generalized plaque digitization framework for multi-dimensional mesoscopic images.
Journal: Biomedical optics express
In common: Keras, TensorFlow, scikit-image, 7 other tools
[7] doi:10.3389/fnsys.2026.1822122 [code]
Convergence-divergence circuits for multimodal integration of innate and learned opponent valences.
Journal: Frontiers in systems neuroscience
In common: Keras, TensorFlow, scikit-image, 7 other tools
[8] doi:10.1038/s41467-026-72057-9 [code]
Sex-specific behavioral feedback modulates sensorimotor processing and drives flexible social behavior.
Journal: Nature communications
In common: Keras, TensorFlow, scikit-image, 7 other tools
[9] doi:10.1080/07853890.2026.2685416 [code]
Pulmonary and cerebral damage in COVID-19 survivors: is there any association?
Journal: Annals of medicine
In common: Keras, TensorFlow, scikit-image, 6 other tools, structural MRI / diffusion
[10] doi:10.1038/s41592-026-03057-2 [code]
CREsted: modeling genomic and synthetic cell-type-specific enhancers across tissues and species.
Journal: Nature methods
In common: Keras, TensorFlow, h5py, 6 other tools, methods / tools

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.