keras-team/keras · error · ValueError

Leading dimensions of input arrays must match

Error message

Leading dimensions of input arrays must match

What it means

Raised in keras/src/backend/tensorflow/linalg.py lstsq: the leading (batch) dimension of a must equal the leading dimension of b, mirroring the constraint of a batched linear least-squares solve (each batch slice of a solves against the corresponding slice of b). Mismatched leading dims mean the equation system is inconsistent before the solver runs.

Solutions

  1. Ensure a.shape[0] == b.shape[0] (same number of rows / batch size)
  2. Transpose or reshape inputs so the batch dims align, e.g. pass b as (m, ...) when a is (m, n)
  3. Broadcast or tile b to match a's batch dimension where appropriate
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at keras/src/backend/tensorflow/linalg.py:213 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/0baff952dae40194. Report an issue: GitHub.

Appendix: source

Thrown at keras/src/backend/tensorflow/linalg.py:213

            tf.linalg.triangular_solve(a, b, lower=lower), axis=-1
        )
    return tf.linalg.triangular_solve(a, b, lower=lower)


def svd(x, full_matrices=True, compute_uv=True):
    if compute_uv is False:
        return tf.linalg.svd(x, full_matrices=full_matrices, compute_uv=False)
    s, u, v = tf.linalg.svd(
        x, full_matrices=full_matrices, compute_uv=compute_uv
    )
    return u, s, tf.linalg.adjoint(v)


def lstsq(a, b, rcond=None):
    a = convert_to_tensor(a)
    b = convert_to_tensor(b)
    if a.shape[0] != b.shape[0]:
        raise ValueError("Leading dimensions of input arrays must match")
    b_orig_ndim = b.ndim
    if b_orig_ndim == 1:
        b = b[:, None]
    if a.ndim != 2:
        raise TypeError(
            f"{a.ndim}-dimensional array given. Array must be two-dimensional"
        )
    if b.ndim != 2:
        raise TypeError(
            f"{b.ndim}-dimensional array given. "
            "Array must be one or two-dimensional"
        )
    m, n = a.shape
    dtype = a.dtype
    eps = tf.experimental.numpy.finfo(dtype).eps
    if a.shape == ():
        s = tf.zeros(0, dtype=a.dtype)
        x = tf.zeros((n, *b.shape[1:]), dtype=a.dtype)

View on GitHub (pinned to 7a34a03db6)