jax-ml/jax · error · TypeError
expected 1D or 2D array for y
Error message
expected 1D or 2D array for y
What it means
polyfit accepts y either as a 1-D array of responses or a 2-D array where columns are separate responses to fit simultaneously. Any other rank (scalar after promotion, or 3-D+) breaks the shape contract with the Vandermonde design matrix and is rejected with a TypeError.
Source
Thrown at jax/_src/numpy/polynomial.py:243
>>> p, C = jnp.polyfit(x, y, 2, cov=True)
>>> p.shape, C.shape
((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]View on GitHub (pinned to 1e1c6a8fc0)
Solutions
- Reshape y to (len(x), n_targets): y.reshape(len(x), -1).
- Squeeze accidental extra axes (e.g. y[:, :, 0]).
- For higher-rank data, vmap polyfit over the extra axes.
Example fix
// before c = jnp.polyfit(x, Y, 3) # Y.shape == (T, C, B) // after c = jax.vmap(lambda y: jnp.polyfit(x, y, 3))(Y.reshape(len(x), C * B).reshape(len(x), -1)) // or simply: c = jnp.polyfit(x, Y.reshape(len(x), -1), 3)
Defensive patterns
Strategy: validation
Validate before calling
y = jnp.asarray(y)
if y.ndim not in (1, 2):
y = y.reshape(len(x), -1)
c = jnp.polyfit(x, y, deg) Type guard
def y_rank_ok(y) -> bool:
return y.ndim in (1, 2) Prevention
- Reshape multi-channel targets to (n_samples, n_targets)
- Squeeze accidental batch axes from y
When it happens
Trigger: jnp.polyfit(x, Y, deg) with Y.ndim == 3 (e.g. images or batched series); a 0-d y scalar.
Common situations: Fitting multiple channels that arrive as (T, C, B) instead of (T, C); passing a batched array of targets from a training pipeline without first squeezing the batch axis.
Related errors
- expected 1D vector for x
- expected a 1-d array for weights
- Input must be a rank-1 array.
- expected deg >= 0
- expected non-empty vector for x
AI-assisted analysis of jax-ml/jax@1e1c6a8fc0 (2026-08-27).
Data as JSON: /api/errors/d89b0888e21e10a8.
Report an issue: GitHub.