keras-team/keras · error · ValueError

If using `weights` as `"imagenet"` with `include_top` as tru

Error message

If using `weights` as `"imagenet"` with `include_top` as true, `classes` should be 1000

What it means

Same eager guard as in extract_patches, on reconstruct_patches: size must be an int or a tuple/list, because reconstruction needs the patch extent to un-flatten each patch. Anything else (numpy array, string, None, dict) is a TypeError before any tensor work happens.

Source

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

    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"
        )

    # Determine proper input shape
    input_shape = imagenet_utils.obtain_input_shape(
        input_shape,
        default_size=224,
        min_size=32,
        data_format=backend.image_data_format(),
        require_flatten=include_top,
        weights=weights,
    )

    if input_tensor is None:
        img_input = layers.Input(shape=input_shape)
    else:
        if not backend.is_keras_tensor(input_tensor):

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Pass int or tuple/list of 2 or 3 ints: size=8 or size=(8, 8)
  2. Coerce near the boundary: size = int(size) if isinstance(size, (int, np.integer)) else tuple(int(s) for s in size)
  3. Share one validated size constant between the extract and reconstruct call sites

Example fix

before: reconstruct_patches(p, size=np.array([8, 8])) -> TypeError; after: reconstruct_patches(p, size=tuple(size.tolist()))
Defensive patterns

Strategy: type-guard

Validate before calling

import numpy as np
if isinstance(size, np.ndarray):
    size = size.tolist()
if isinstance(size, (np.integer,)):
    size = int(size)
assert isinstance(size, (int, tuple, list))

Type guard

def coerce_patch_size(size):
    if isinstance(size, np.integer):
        return int(size)
    if isinstance(size, np.ndarray):
        size = size.tolist()
    if isinstance(size, list):
        size = tuple(size)
    return size

Try / catch

try:
    recon = keras.ops.image.reconstruct_patches(patches, size=size)
except TypeError as e:
    raise ValueError(f"invalid size {size!r} of {type(size).__name__}") from e

Prevention

When it happens

Trigger: reconstruct_patches(patches, size=np.int64(8)) or size=np.array([8,8]); size=None reaching the call from an optional config; passing a dict or string parsed from a config file.

Common situations: Round-tripping configs through JSON where lists become arrays via numpy; size stored in a dataclass with the wrong type annotation; glue code between extract and reconstruct that transforms size.

Understand the failure class

Background: Invalid argument type errors: "must be of type string", "expected X, got Y", and ERR_INVALID_ARG_TYPE explained — this error's family across 15 libraries.

Related errors


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