keras-team/keras · error · ValueError
Expected b to have rank 1 or 2. Received: b.shape=
Error message
Expected b to have rank 1 or 2. Received: b.shape={b.shape} What it means
Raised by Lstsq.compute_output_spec in keras/src/ops/linalg.py before solving the least-squares problem: `b` (the right-hand-side targets) must be a rank-1 vector or rank-2 matrix. The guard fires because keras.ops.lstsq was given a scalar or a tensor with rank >= 3, which no backend's lstsq supports.
Solutions
- Reshape b to rank 1 (a single target vector) or rank 2 (a batch of target columns), e.g. keras.ops.reshape(b, (-1,)) or (n, k)
- If b has extra batch dimensions, fold them into the matrix dimension or solve each batch element separately
- Check b.ndim before calling keras.ops.lstsq and squeeze/expand as needed
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at keras/src/ops/linalg.py:632 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/8b2fb24bc4ca3132.
Report an issue: GitHub.
Appendix: source
Thrown at keras/src/ops/linalg.py:632
_assert_2d(x)
return backend.linalg.svd(x, full_matrices, compute_uv)
class Lstsq(Operation):
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"])View on GitHub (pinned to 7a34a03db6)