keras-team/keras · error · ValueError

DenseNet does not support the `channels_first` image data fo

Error message

DenseNet does not support the `channels_first` image data format. Switch to `channels_last` by editing your local config file at ~/.keras/keras.json

What it means

With padding=valid, reconstruct_patches assumes no padding existed at extraction, so each output spatial dim must equal patch_size * grid_count exactly. If output_size disagrees with grid*p for any axis, reconstructing would need to invent or drop pixels, so compute_output_spec rejects it.

Source

Thrown at keras/src/applications/densenet.py:186

                the output of the model will be a 2D tensor.
            - `max` means that global max pooling will
                be applied.
        classes: optional number of classes to classify images
            into, only to be specified if `include_top` is `True`, and
            if no `weights` argument is specified. Defaults to `1000`.
        classifier_activation: A `str` or callable.
            The activation function to use
            on the "top" layer. Ignored unless `include_top=True`. Set
            `classifier_activation=None` to return the logits of the "top"
            layer. When loading pretrained weights, `classifier_activation`
            can only be `None` or `"softmax"`.
        name: The name of the model (string).

    Returns:
        A model instance.
    """
    if backend.image_data_format() == "channels_first":
        raise ValueError(
            "DenseNet does not support the `channels_first` image data "
            "format. Switch to `channels_last` by editing your local "
            "config file at ~/.keras/keras.json"
        )
    if not (weights in {"imagenet", None} or file_utils.exists(weights)):
        raise ValueError(
            "The `weights` argument should be either "
            "`None` (random initialization), `imagenet` "
            "(pre-training on ImageNet), "
            "or the path to the weights file to be loaded."
        )

    if weights == "imagenet" and include_top and classes != 1000:
        raise ValueError(
            'If using `weights` as `"imagenet"` with `include_top`'
            " as true, `classes` should be 1000"
        )

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Set output_size per axis to exactly grid * patch_size (e.g. omit output_size and let it be inferred, or compute it from the grid dims of patches)
  2. If patches overlapped or the input was padded, use padding=same with an output_size in the valid overlap range
  3. Re-extract with strides=size (non-overlapping) if you want lossless valid reconstruction

Example fix

before: reconstruct_patches(p, size=(8,8), padding="valid", output_size=(33,33)) -> ValueError; after: reconstruct_patches(p, size=(8,8), padding="valid") # output_size inferred as (32,32)
Defensive patterns

Strategy: validation

Validate before calling

for g, p, o in zip(grid_dims, patch_dims, output_size):
    assert g * p == o, f"valid padding needs o == g*p, got {o} != {g*p}"

Type guard

def valid_padding_ok(grid, patch, out) -> bool:
    return all(g * p == o for g, p, o in zip(grid, patch, out))

Prevention

When it happens

Trigger: reconstruct_patches(patches, size, output_size=(33, 33)) where grid=4 and p=8 (grid*p=32); extracting with strides < size (overlapping patches) but claiming padding=valid; output_size copied from the padded input shape instead of the valid-extraction shape.

Common situations: Using stride 1 overlapping patches and assuming full-size reconstruction; feeding the original image dims as output_size after a valid-mode extraction trimmed the border; porting from frameworks whose padding semantics differ.

Related errors


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