A MONAI transform pipeline for a 3D volume
Normalising the intensity of an MRI volume, cropping it and adding random augmentation.
Goal: Training a small segmentation network for a few steps on synthetic data and monitoring the Dice metric.
import torch
from monai.losses import DiceLoss
from monai.metrics import DiceMetric
from monai.networks.nets import UNet
torch.manual_seed(0)
def sample(n=2, s=32):
g = torch.stack(torch.meshgrid(*[torch.arange(s)] * 3, indexing="ij")).float()
m = (((g - s / 2) ** 2).sum(0) < (s / 4) ** 2).float()
x = m + 0.5 * torch.randn(n, 1, s, s, s)
return x, m.expand(n, 1, s, s, s)
net = UNet(spatial_dims=3, in_channels=1, out_channels=1, channels=(8, 16, 32), strides=(2, 2), num_res_units=1)
loss_fn = DiceLoss(sigmoid=True)
metric = DiceMetric(include_background=True, reduction="mean")
opt = torch.optim.Adam(net.parameters(), 1e-2)
for step in range(1, 31):
x, y = sample()
loss = loss_fn(net(x), y)
opt.zero_grad(); loss.backward(); opt.step()
if step % 10 == 0:
with torch.no_grad():
pred = (torch.sigmoid(net(x)) > 0.5).float()
metric(pred, y); d = metric.aggregate().item(); metric.reset()
print(f"step {step}: dice_loss={loss.item():.4f} dice={d:.3f}")
We build a 3D UNet from MONAI, use DiceLoss, which suits the pixel imbalance between tumour and background, and DiceMetric for evaluation. The data is a synthetic sphere inside noise; the goal is to illustrate the API, not a clinical result.
step 10: dice_loss=0.7871 dice=0.434 step 20: dice_loss=0.7600 dice=0.592 step 30: dice_loss=0.7150 dice=0.657
This example was actually run and tested on 21 November 2026 on a CPU — monai 1.6.2, torch 2.15.0, python 3.13.18
Normalising the intensity of an MRI volume, cropping it and adding random augmentation.
Running a network on a volume larger than the training size without running out of memory.
Sections
No section has this name. Press “Search” to search all site content.
Favourites
My results & certificates
My academy progressMy quiz resultsKids’ progressAcademy certificatesQuiz certificatesStart any lesson or quiz and it will show up here so you can get back to it quickly.
Settings
I am the AI Frameworks & Libraries Assistant. Describe your project or ask me about a library, a comparison or a code example, and I will answer from the encyclopedia's database with links and sources.
Answers from the encyclopedia's database only, without a language model and without sending your question to any third party.
The assistant can make mistakes, so check the attached sources.