keras-team/keras · error · ValueError

`padding` should have two elements. Received: padding={paddi

Error message

`padding` should have two elements. Received: padding={padding}.

What it means

ZeroPadding2D.__init__ accepts padding as an int, or a 2-element sequence (height, width), each element further standardized to a (before, after) pair. Passing a sequence with a length other than 2 — e.g. a flat 4-tuple like (1,1,2,2) — raises immediately at construction.

Source

Thrown at keras/src/layers/reshaping/zero_padding2d.py:78

        - If `data_format` is `"channels_first"`:
          `(batch_size, channels, height, width)`

    Output shape:
        4D tensor with shape:
        - If `data_format` is `"channels_last"`:
          `(batch_size, padded_height, padded_width, channels)`
        - If `data_format` is `"channels_first"`:
          `(batch_size, channels, padded_height, padded_width)`
    """

    def __init__(self, padding=(1, 1), data_format=None, **kwargs):
        super().__init__(**kwargs)
        self.data_format = backend.standardize_data_format(data_format)
        if isinstance(padding, int):
            self.padding = ((padding, padding), (padding, padding))
        elif hasattr(padding, "__len__"):
            if len(padding) != 2:
                raise ValueError(
                    "`padding` should have two elements. "
                    f"Received: padding={padding}."
                )
            height_padding = argument_validation.standardize_tuple(
                padding[0], 2, "1st entry of padding", allow_zero=True
            )
            width_padding = argument_validation.standardize_tuple(
                padding[1], 2, "2nd entry of padding", allow_zero=True
            )
            self.padding = (height_padding, width_padding)
        else:
            raise ValueError(
                "`padding` should be either an int, a tuple of 2 ints "
                "(symmetric_height_crop, symmetric_width_crop), "
                "or a tuple of 2 tuples of 2 ints "
                "((top_crop, bottom_crop), (left_crop, right_crop)). "
                f"Received: padding={padding}."
            )

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Use the Keras shape: int, (h, w), or ((h_top, h_bottom), (w_left, w_right))
  2. If porting from PyTorch, convert torch's (left,right,top,bottom) to Keras ((top,bottom),(left,right))
  3. Validate the padding structure in config-loading code before layer construction

Example fix

# before (PyTorch style, invalid in Keras)
layer = ZeroPadding2D(padding=(1, 1, 2, 2))

# after
layer = ZeroPadding2D(padding=((1, 1), (2, 2)))
Defensive patterns

Strategy: validation

Validate before calling

def normalize_padding2d(p):
    if isinstance(p, int):
        return ((p, p), (p, p))
    if len(p) != 2:
        raise ValueError('padding must be int, (h, w), or ((h1,h2),(w1,w2))')
    def pair(v):
        return (v, v) if isinstance(v, int) else tuple(v)
    return (pair(p[0]), pair(p[1]))

layer = ZeroPadding2D(padding=normalize_padding2d(cfg['padding']))

Type guard

def is_valid_padding2d(p) -> bool:
    if isinstance(p, int):
        return True
    return hasattr(p, '__len__') and len(p) == 2

Prevention

When it happens

Trigger: ZeroPadding2D(padding=(1,1,2,2)) (flat 4-tuple, length 4); ZeroPadding2D(padding=[1]) (length 1); ZeroPadding2D(padding=((1,1),(2,2),(3,3))) (length 3). Correct forms: 2, (2,2), or ((1,1),(2,2)).

Common situations: Assuming the Keras API mirrors PyTorch's nn.ZeroPad2d, which does take a flat 4-tuple (left,right,top,bottom); building padding programmatically and flattening the nested structure; config files storing padding as a flat list.

Related errors


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