tracel-ai/burn · error

top_k must be non-zero

Error message

top_k must be non-zero

What it means

Config validation in `PrecisionRecallMetric`/`ClassificationMetricConfig`: `top_k` of zero was supplied to the multiclass precision constructor, where a zero top-k is meaningless for label selection, so construction panics.

Source

Thrown at crates/burn-train/src/metric/precision.rs:63

    pub fn binary(threshold: f64) -> Self {
        Self::new(ClassificationMetricConfig {
            decision_rule: DecisionRule::Threshold(threshold),
            // binary classification results are the same independently of class_reduction
            ..Default::default()
        })
    }

    /// Precision metric for multiclass classification.
    ///
    /// # Arguments
    ///
    /// * `top_k` - The number of highest predictions considered to find the correct label (typically `1`).
    /// * `class_reduction` - [Class reduction](ClassReduction) type.
    #[allow(dead_code)]
    pub fn multiclass(top_k: usize, class_reduction: ClassReduction) -> Self {
        Self::new(ClassificationMetricConfig {
            decision_rule: DecisionRule::TopK(
                NonZeroUsize::new(top_k).expect("top_k must be non-zero"),
            ),
            class_reduction,
        })
    }

    /// Precision metric for multi-label classification.
    ///
    /// # Arguments
    ///
    /// * `threshold` - The threshold to transform a probability into a binary value.
    /// * `class_reduction` - [Class reduction](ClassReduction) type.
    #[allow(dead_code)]
    pub fn multilabel(threshold: f64, class_reduction: ClassReduction) -> Self {
        Self {
            config: ClassificationMetricConfig {
                decision_rule: DecisionRule::Threshold(threshold),
                class_reduction,
            },

View on GitHub (pinned to d16f7ba2ed)

Solutions

  1. Use top_k >= 1 when creating the metric
  2. Clamp or validate top_k from user config before construction
  3. Choose the binary(threshold) constructor when top-k is irrelevant
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at crates/burn-train/src/metric/precision.rs:63 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/79c31a7ffe2af2ab. Report an issue: GitHub.