keras-team/keras · error · ValueError
Expected data_format to be one of `channels_first` or `chann
Error message
Expected data_format to be one of `channels_first` or `channels_last`. Received: data_format={data_format} What it means
Runtime validation in _crop_images: only rank-3 (single image) or rank-4 (batched) image tensors are accepted; anything else raises before cropping executes.
Source
Thrown at keras/src/applications/imagenet_utils.py:98
PREPROCESS_INPUT_RET_DOC_CAFFE = """
The images are converted from RGB to BGR, then each color channel is
zero-centered with respect to the ImageNet dataset, without scaling."""
@keras_export("keras.applications.imagenet_utils.preprocess_input")
def preprocess_input(x, data_format=None, mode="caffe"):
"""Preprocesses a tensor or Numpy array encoding a batch of images."""
if mode not in {"caffe", "tf", "torch"}:
raise ValueError(
"Expected mode to be one of `caffe`, `tf` or `torch`. "
f"Received: mode={mode}"
)
if data_format is None:
data_format = backend.image_data_format()
elif data_format not in {"channels_first", "channels_last"}:
raise ValueError(
"Expected data_format to be one of `channels_first` or "
f"`channels_last`. Received: data_format={data_format}"
)
if isinstance(x, np.ndarray):
return _preprocess_numpy_input(x, data_format=data_format, mode=mode)
else:
return _preprocess_tensor_input(x, data_format=data_format, mode=mode)
preprocess_input.__doc__ = PREPROCESS_INPUT_DOC.format(
mode=PREPROCESS_INPUT_MODE_DOC,
ret="",
error=PREPROCESS_INPUT_DEFAULT_ERROR_DOC,
)
@keras_export("keras.applications.imagenet_utils.decode_predictions")View on GitHub (pinned to 7a34a03db6)
Solutions
- Expand to rank 3/4 with [..., None] or [None, ...]
- Reshape video data to rank-4 per frame
- Check ops.shape(images) rank before calling
Example fix
# before out = ops.image.crop_images(mask, ...) # (H, W) # after out = ops.image.crop_images(mask[..., None], ...) # (H, W, 1)
Defensive patterns
Strategy: type-guard
Validate before calling
if len(ops.shape(images)) not in (3, 4):
images = backend.convert_to_tensor(images)
if len(images.shape) == 2:
images = images[..., None] Type guard
def is_crop_safe_rank(t) -> bool:
return len(t.shape) in (3, 4) Try / catch
try:
out = ops.image.crop_images(images, ...)
except ValueError as e:
if 'rank' in str(e):
images = normalize_rank(images)
else:
raise Prevention
- Keep images rank-4 (N,H,W,C) end to end
- Reshape video frames to rank-4 before cropping
When it happens
Trigger: Eager calls to ops.image.crop_images with rank-2 arrays, rank-5 video tensors, or lists converted to wrong-rank tensors.
Common situations: Feeding unlabeled masks; per-frame video processing without reshaping; converting from libraries that drop singleton axes.
Related errors
- weights_path undefined
- The `weights` argument should be either `None` (random initi
- If using `weights="imagenet"` as true, `classes` should be 1
- The number of repeats in `EfficientNet` must be > 0. Receive
- The `weights` argument should be either `None` (random initi
AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25).
Data as JSON: /api/errors/6e9e6840dbd87e8d.
Report an issue: GitHub.