keras-team/keras · error · ValueError

Expected b.shape[0] to be equal to a.shape[0]. Received…

Error message

Expected b.shape[0] to be equal to a.shape[0]. Received: a.shape={a.shape}, b.shape={b.shape}

What it means

Raised by Lstsq.compute_output_spec in keras/src/ops/linalg.py: the first dimension of `b` must match the row count m of the coefficient matrix `a` (a is (m, n)). It fires when the number of equations implied by a and the number of target rows in b disagree, e.g. a of shape (m, n) with b of shape (k, ...) where k != m.

Solutions

  1. Ensure b has exactly a.shape[0] rows: b.shape == (m,) or (m, k)
  2. Transpose or re-slice your data so the sample counts of a and b agree
  3. Verify you did not swap the argument order of keras.ops.lstsq(a, b)
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at keras/src/ops/linalg.py:637 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/7241a05f2adb4f9b. Report an issue: GitHub.

Appendix: source

Thrown at keras/src/ops/linalg.py:637

    def __init__(self, rcond=None, *, name=None):
        super().__init__(name=name)
        self.rcond = rcond

    def call(self, a, b):
        return backend.linalg.lstsq(a, b, rcond=self.rcond)

    def compute_output_spec(self, a, b):
        if len(a.shape) != 2:
            raise ValueError(
                f"Expected a to have rank 2. Received: a.shape={a.shape}"
            )
        if len(b.shape) not in (1, 2):
            raise ValueError(
                f"Expected b to have rank 1 or 2. Received: b.shape={b.shape}"
            )
        m, n = a.shape
        if b.shape[0] != m:
            raise ValueError(
                "Expected b.shape[0] to be equal to "
                "a.shape[0]. Received: "
                f"a.shape={a.shape}, b.shape={b.shape}"
            )
        if len(b.shape) == 2:
            k = b.shape[1]
            x = KerasTensor((n, k), dtype=a.dtype)
        else:
            x = KerasTensor((n,), dtype=a.dtype)
        return x


@keras_export(["keras.ops.lstsq", "keras.ops.linalg.lstsq"])
def lstsq(a, b, rcond=None):
    """Return the least-squares solution to a linear matrix equation.

    Computes the vector x that approximately solves the equation
    `a @ x = b`. The equation may be under-, well-, or over-determined

View on GitHub (pinned to 7a34a03db6)