jax-ml/jax · error · TypeError
expected 1D vector for x
Error message
expected 1D vector for x
What it means
polyfit fits a polynomial along a 1-D independent variable: it builds vander(x, order), which is only defined for a 1-D x. Passing multi-dimensional x (2-D grid, batched samples) is a TypeError because the Vandermonde construction and the least-squares system would be ambiguous.
Source
Thrown at jax/_src/numpy/polynomial.py:239
If ``cov=True`` and ``full=False``, returns a tuple of arrays having
polynomial coefficients and covariance matrix.
>>> 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:View on GitHub (pinned to 1e1c6a8fc0)
Solutions
- Flatten x (and correspondingly y) so both are 1-D and length-matched: jnp.polyfit(X.ravel(), Y.ravel(), deg).
- For multivariate fitting, use jax.scipy or a custom linear solve on stacked basis features, not polyfit.
- Check x.ndim == 1 before the call.
Example fix
// before c = jnp.polyfit(X, Z, 2) # X from meshgrid, shape (m, n) // after c = jnp.polyfit(X.ravel(), Z.ravel(), 2)
Defensive patterns
Strategy: validation
Validate before calling
x = jnp.asarray(x)
if x.ndim != 1:
x = x.ravel()
y = y.reshape(-1) if x.size == y.size else y
c = jnp.polyfit(x, y, deg) Type guard
def is_1d(x) -> bool:
return getattr(x, 'ndim', 0) == 1 Prevention
- Flatten meshgrid outputs before fitting
- polyfit is 1-D only; use custom least squares for surfaces
When it happens
Trigger: jnp.polyfit(X, y, deg) where X has shape (m, n) (e.g. a meshgrid output); passing paired (x, y) points as a 2-D array to the first argument.
Common situations: Confusing polyfit's signature with sklearn-style fit(features, target); using the X output of np.meshgrid directly instead of a flattened coordinate array.
Related errors
- expected 1D or 2D array for y
- 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/d7fba7338f04fa87.
Report an issue: GitHub.