tensorflow/models · error · ValueError

Length of class_weights should be {}

Error message

Length of class_weights should be {}

What it means

Error "Length of class_weights should be {}" thrown in tensorflow/models.

Source

Thrown at official/vision/losses/segmentation_losses.py:96

    if not self._use_binary_cross_entropy:
      if num_layers > 1:
        raise ValueError(
            'Groundtruth mask must have only 1 layer if using categorical'
            'cross entropy, but got {} layers.'.format(num_layers))
    if self._gt_is_matting_map:
      if num_classes != 2:
        raise ValueError(
            'Groundtruth matting map only supports 2 classes, but got {} '
            'classes.'.format(num_classes))
      if num_layers > 1:
        raise ValueError(
            'Groundtruth matting map must have only 1 layer, but got {} '
            'layers.'.format(num_layers))

    class_weights = (
        self._class_weights if self._class_weights else [1] * num_classes)
    if num_classes != len(class_weights):
      raise ValueError(
          'Length of class_weights should be {}'.format(num_classes))
    class_weights = tf.constant(class_weights, dtype=output_dtype)

    if not self._gt_is_matting_map:
      labels = tf.cast(labels, tf.int32)
    if self._use_groundtruth_dimension:
      # TODO(arashwan): Test using align corners to match deeplab alignment.
      logits = tf.image.resize(
          logits, tf.shape(labels)[1:3], method=tf.image.ResizeMethod.BILINEAR)
    else:
      labels = tf.image.resize(
          labels, (height, width),
          method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)

    valid_mask = tf.not_equal(tf.cast(labels, tf.int32), self._ignore_label)

    # (batch_size, height, width, num_classes)
    labels_with_prob = self.get_labels_with_prob(logits, labels, valid_mask,

View on GitHub (pinned to e006f5f0d5)

Solutions

  1. Pass class_weights with the same length as the number of segmentation classes indicated in the error.
  2. Remove class_weights (use uniform weighting) if per-class weighting is not needed.

When it happens

Trigger: Thrown at official/vision/losses/segmentation_losses.py:96 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of tensorflow/models@e006f5f0d5 (2026-08-24). Data as JSON: /api/errors/14154dfd272ceba6. Report an issue: GitHub.