keras-team/keras · error · ValueError

`cdist` inputs must have rank >= 2

Error message

`cdist` inputs must have rank >= 2

What it means

Rank guard in the NumPy backend's `cdist` (pairwise distance): distances are computed between the rows of two matrices, so both inputs must have at least two dimensions — the last being the feature dimension. If either `x` or `y` is 0D/1D (a bare vector rather than a batch of points), the check `x.ndim < 2 or y.ndim < 2` fires and rejects the call.

Solutions

  1. Promote single vectors to matrices: x = x[None, :] so both operands are (N, D) and (M, D)
  2. Fix slicing that produced a 1D row instead of a (1, D) matrix
  3. Stack lists of points with np.stack/keras.ops.stack before calling cdist
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at keras/src/backend/numpy/ops/math.py:114 when the library encounters an invalid state.

Common situations: See trigger scenarios.


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

Appendix: source

Thrown at keras/src/backend/numpy/ops/math.py:114

    return np.any(mask, axis=-1)


def logsumexp(x, axis=None, keepdims=False):
    x = convert_to_tensor(x)
    dtype = dtypes.result_type(x.dtype, float)
    return scipy.special.logsumexp(x, axis=axis, keepdims=keepdims).astype(
        dtype
    )


def cdist(x, y):
    x = np.asarray(x)
    y = np.asarray(y)
    dtype = dtypes.result_type(x.dtype, y.dtype, float)
    x = x.astype(dtype)
    y = y.astype(dtype)
    if x.ndim < 2 or y.ndim < 2:
        raise ValueError("`cdist` inputs must have rank >= 2")
    if x.shape[-1] != y.shape[-1]:
        raise ValueError("Last dimension of inputs to `cdist` must match")
    diff = x[..., :, None, :] - y[..., None, :, :]
    return np.sqrt(np.sum(diff * diff, axis=-1))


def extract_sequences(x, sequence_length, sequence_stride):
    *batch_shape, _ = x.shape
    batch_shape = list(batch_shape)
    shape = x.shape[:-1] + (
        (x.shape[-1] - (sequence_length - sequence_stride)) // sequence_stride,
        sequence_length,
    )
    strides = x.strides[:-1] + (
        sequence_stride * x.strides[-1],
        x.strides[-1],
    )
    x = np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)

View on GitHub (pinned to 7a34a03db6)