keras-team/keras · error · ValueError

Unknown data_format: {data_format}

Error message

Unknown data_format: {data_format}

What it means

bias_add() from the deprecated Keras backend only accepts the data_format strings 'channels_first' or 'channels_last'. When data_format is None it falls back to the global backend.image_data_format(), so the error means either an explicitly passed bad string or a globally misconfigured image_data_format. Any other value ('NCHW', 'NHWC', 'first', typos) is rejected.

Source

Thrown at keras/src/legacy/backend.py:243

    if tf.executing_eagerly() or tf.inside_function():
        for x, value in tuples:
            value = np.asarray(value, dtype=x.dtype.name)
            x.assign(value)


@keras_export("keras._legacy.backend.batch_normalization")
def batch_normalization(x, mean, var, beta, gamma, axis=-1, epsilon=1e-3):
    """DEPRECATED."""
    return tf.nn.batch_normalization(x, mean, var, beta, gamma, epsilon)


@keras_export("keras._legacy.backend.bias_add")
def bias_add(x, bias, data_format=None):
    """DEPRECATED."""
    if data_format is None:
        data_format = backend.image_data_format()
    if data_format not in {"channels_first", "channels_last"}:
        raise ValueError(f"Unknown data_format: {data_format}")
    bias_shape = bias.shape
    if len(bias_shape) != 1 and len(bias_shape) != ndim(x) - 1:
        raise ValueError(
            f"Unexpected bias dimensions {len(bias_shape)}. "
            f"Expected it to be 1 or {ndim(x) - 1} dimensions"
        )

    if len(bias_shape) == 1:
        if data_format == "channels_first":
            return tf.nn.bias_add(x, bias, data_format="NCHW")
        return tf.nn.bias_add(x, bias, data_format="NHWC")
    if ndim(x) in (3, 4, 5):
        if data_format == "channels_first":
            bias_reshape_axis = (1, bias_shape[-1]) + bias_shape[:-1]
            return x + reshape(bias, bias_reshape_axis)
        return x + reshape(bias, (1,) + bias_shape)
    return tf.nn.bias_add(x, bias)

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Pass 'channels_last' or 'channels_first' explicitly (Keras names, not 'NHWC'/'NCHW')
  2. If you omitted data_format, check what keras.config.image_data_format() returns and reset it with keras.config.set_image_data_format('channels_last')
  3. Map TF-style names before calling: data_format = {'NHWC':'channels_last','NCHW':'channels_first'}[tf_fmt]

Example fix

// before
out = K.bias_add(x, b, data_format='NHWC')

// after
out = K.bias_add(x, b, data_format='channels_last')
Defensive patterns

Strategy: type-guard

Validate before calling

fmt = data_format if data_format is not None else keras.config.image_data_format()
assert fmt in ('channels_first', 'channels_last'), f'bad data_format: {fmt!r}'

Type guard

def is_valid_data_format(v) -> bool:
    return v is None or v in {'channels_first', 'channels_last'}

Try / catch

except ValueError as e:
    if 'data_format' in str(e):
        out = K.bias_add(x, bias, data_format='channels_last')
    else:
        raise

Prevention

When it happens

Trigger: Calling keras._legacy.backend.bias_add(x, bias, data_format='NCHW') or any string outside {'channels_first','channels_last'}; or keras.config.set_image_data_format() having been set to an invalid value earlier in the process.

Common situations: Code migrated from TF-speak ('NHWC'/'NCHW') instead of Keras-speak; a config file or notebook cell that set image_data_format to a TensorFlow-style string; copy-pasted layers that pass data_format through unvalidated from user input.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


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