A 3D UNet with Dice loss in MONAI
Training a small segmentation network for a few steps on synthetic data and monitoring the Dice metric.
Goal: Normalising the intensity of an MRI volume, cropping it and adding random augmentation.
import numpy as np, torch
from monai.transforms import Compose, NormalizeIntensity, CropForeground, RandFlip, ToTensor
from monai.utils import set_determinism
set_determinism(seed=0)
vol = np.zeros((1, 64, 64, 48), dtype=np.float32)
vol[:, 16:48, 20:44, 10:38] = np.random.default_rng(0).normal(100, 20, (32, 24, 28))
tf = Compose([NormalizeIntensity(nonzero=True), CropForeground(), RandFlip(prob=1.0, spatial_axis=0), ToTensor()])
out = tf(vol)
print("Shape before:", vol.shape, "after cropping:", tuple(out.shape))
nz = out[out != 0]
print(f"Mean intensity after normalisation: {nz.mean().item():.3f}, std: {nz.std().item():.3f}")
MONAI transforms work on arrays in (channel, depth, height, width) format. We apply intensity normalisation, then foreground cropping, then a random flip. Here the volume is randomly generated; with real NIfTI files add LoadImaged at the start.
Shape before: (1, 64, 64, 48) after cropping: (1, 32, 24, 28) Mean intensity after normalisation: -0.000, std: 1.000
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
Training a small segmentation network for a few steps on synthetic data and monitoring the Dice metric.
Running a network on a volume larger than the training size without running out of memory.
Harmonising voxel size (spacing) between scans from different machines.
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.