A 3D UNet with Dice loss in MONAI

MediumImage segmentationMedical segmentation

Goal: Training a small segmentation network for a few steps on synthetic data and monitoring the Dice metric.

Python — example.py
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}")

Code explanation

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.

Requirements

Shell
pip install monai torch

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

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

Libraries used

Related examples