jax-ml/jax · error · TypeError
expected x and y to have same length
Error message
expected x and y to have same length
What it means
polyfit builds vander(x, order) with len(x) rows, so y must have the same number of observations: y.shape[0] == x.shape[0]. A length mismatch means the design matrix and responses are inconsistent and the least-squares system cannot be formed.
Source
Thrown at jax/_src/numpy/polynomial.py:245
((3, 3), (3, 3, 3))
"""
if w is None:
x_arr, y_arr = ensure_arraylike("polyfit", x, y)
else:
x_arr, y_arr, w = ensure_arraylike("polyfit", x, y, w)
del x, y
deg = core.concrete_or_error(int, deg, "deg must be int")
order = deg + 1
if deg < 0:
raise ValueError("expected deg >= 0")
if x_arr.ndim != 1:
raise TypeError("expected 1D vector for x")
if x_arr.size == 0:
raise TypeError("expected non-empty vector for x")
if y_arr.ndim < 1 or y_arr.ndim > 2:
raise TypeError("expected 1D or 2D array for y")
if x_arr.shape[0] != y_arr.shape[0]:
raise TypeError("expected x and y to have same length")
if rcond is None:
rcond = len(x_arr) * float(finfo(x_arr.dtype).eps)
rcond = core.concrete_or_error(float, rcond, "rcond must be float")
# set up least squares equation for powers of x
lhs = vander(x_arr, order)
rhs = y_arr
# apply weighting
if w is not None:
w_arr, = promote_dtypes_inexact(w)
if w_arr.ndim != 1:
raise TypeError("expected a 1-d array for weights")
if w_arr.shape[0] != y_arr.shape[0]:
raise TypeError("expected w and y to have the same length")
lhs *= w_arr[:, np.newaxis]
if rhs.ndim == 2:
rhs *= w_arr[:, np.newaxis]View on GitHub (pinned to 1e1c6a8fc0)
Solutions
- Apply identical filtering/slicing to both: jnp.polyfit(x[mask], y[mask], deg).
- Verify shapes first: assert x.shape[0] == y.shape[0].
- When using meshgrid outputs, ravel both arrays.
Example fix
// before c = jnp.polyfit(x[keep], y, 3) // after c = jnp.polyfit(x[keep], y[keep], 3)
Defensive patterns
Strategy: validation
Validate before calling
x, y = jnp.asarray(x), jnp.asarray(y) assert x.shape[0] == y.shape[0], (x.shape, y.shape) c = jnp.polyfit(x, y, deg)
Type guard
def lengths_match(x, y) -> bool:
return x.shape[0] == y.shape[0] Prevention
- Apply identical masks to x and y
- Ravel both arrays from grid operations
When it happens
Trigger: jnp.polyfit(x, y, deg) with len(y) != len(x); x masked/filtered but y not (or vice versa); x from ravel of a grid paired with an unflattened y.
Common situations: Applying the same mask to x but forgetting y (or slicing y's columns only); mixing flattened and unflattened arrays after grid operations; off-by-one trimming of one series.
Related errors
- expected deg >= 0
- expected 1D vector for x
- expected non-empty vector for x
- expected 1D or 2D array for y
- expected a 1-d array for weights
AI-assisted analysis of jax-ml/jax@1e1c6a8fc0 (2026-08-27).
Data as JSON: /api/errors/a021dfd7dde5c12c.
Report an issue: GitHub.