tracel-ai/burn · error

Dice metric requires at least 2 classes when including backg

Error message

Dice metric requires at least 2 classes when including background.

What it means

Configuration guard in `DiceMetric::update`: `include_background` is enabled but the tensors contain fewer than 2 classes, so there would be no foreground classes left after the background handling and the Dice computation is meaningless.

Source

Thrown at crates/burn-train/src/metric/vision/dice.rs:267

                item.outputs.dims(),
                item.targets.dims()
            );
        }

        let dims = item.outputs.dims();
        let batch_size = dims[0];
        let n_classes = dims[1];

        let mut outputs = item.outputs.clone();
        let mut targets = item.targets.clone();

        if !self.config.include_background && n_classes > 1 {
            // If not including background, we can ignore the first class
            outputs = outputs.slice(s![.., 1..]);
            targets = targets.slice(s![.., 1..]);
        } else if self.config.include_background && n_classes < 2 {
            // If including background, we need at least 2 classes
            panic!("Dice metric requires at least 2 classes when including background.");
        }

        let intersection = (outputs.clone() * targets.clone()).sum();
        let outputs_sum = outputs.sum();
        let targets_sum = targets.sum();

        // Convert to f64
        let intersection_val = intersection.into_scalar::<f64>();
        let outputs_sum_val = outputs_sum.into_scalar::<f64>();
        let targets_sum_val = targets_sum.into_scalar::<f64>();

        self.state.update(
            intersection_val,
            outputs_sum_val,
            targets_sum_val,
            batch_size,
            self.config.epsilon,
        );

View on GitHub (pinned to d16f7ba2ed)

Solutions

  1. Ensure the model outputs at least 2 channels (classes)
  2. Set `include_background: false` in the metric config if you only have a single foreground channel
  3. Check that targets/outputs use a class dimension of the expected size
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at crates/burn-train/src/metric/vision/dice.rs:267 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of tracel-ai/burn@d16f7ba2ed (2026-09-05). Data as JSON: /api/errors/61388172dd1feb9a. Report an issue: GitHub.