keras-team/keras · error · ValueError

`variance` must be length 4, got {variance}

Error message

`variance` must be length 4, got {variance}

What it means

encode_box_to_deltas converts anchor boxes plus offsets into encoded deltas, optionally normalizing by a per-coordinate variance. The variance vector must have exactly 4 elements (x, y, w, h components); after conversion to a float32 tensor, a last-dimension size other than 4 raises this ValueError.

Source

Thrown at keras/src/layers/preprocessing/image_preprocessing/bounding_boxes/converters.py:305

            are divided by the variance. Defaults to None.
        image_shape: `Tuple[int]`. The shape of the image (height, width, 3).
            When using relative bounding box format for `box_format` the
            `image_shape` is used for normalization.
    Returns:
        Encoded box deltas. The return type matches the `encode_format`.

    Raises:
        ValueError: If `variance` is not None and its length is not 4.
        ValueError: If `encoding_format` is not `"center_xywh"` or
            `"center_yxhw"`.

    """
    if variance is not None:
        variance = ops.convert_to_tensor(variance, "float32")
        var_len = variance.shape[-1]

        if var_len != 4:
            raise ValueError(f"`variance` must be length 4, got {variance}")

    if encoding_format not in ["center_xywh", "center_yxhw"]:
        raise ValueError(
            "`encoding_format` should be one of 'center_xywh' or "
            f"'center_yxhw', got {encoding_format}"
        )

    if image_shape is None:
        height, width = None, None
    else:
        height, width, _ = image_shape

    encoded_anchors = convert_format(
        anchors,
        source=anchor_format,
        target=encoding_format,
        height=height,
        width=width,

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Supply exactly four variance values, e.g. variance=[0.1, 0.1, 0.2, 0.2].
  2. Or omit variance (pass None) if you do not need variance normalization.

Example fix

# before
deltas = encode_box_to_deltas(boxes, anchors, variance=[0.1, 0.1, 0.2])
# after
deltas = encode_box_to_deltas(boxes, anchors, variance=[0.1, 0.1, 0.2, 0.2])
Defensive patterns

Strategy: validation

Validate before calling

if variance is not None:
    assert len(variance) == 4, f"variance must have 4 elements, got {len(variance)}"

Type guard

def is_valid_variance(v):
    return v is None or (hasattr(v, "__len__") and len(v) == 4)

Prevention

When it happens

Trigger: Passing variance=[0.1, 0.1, 0.2] (3 elements), a scalar variance, or an (N, 5) variance array to encode_box_to_deltas.

Common situations: Copying variance values from an SSD/RetinaNet config that lists variances for a different box parameterization; building variance from a loop with an off-by-one length.

Related errors


AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25). Data as JSON: /api/errors/7453005bfb88f04d. Report an issue: GitHub.