jax-ml/jax · error · RuntimeError
incompatible numbers of samples and aweights
Error message
incompatible numbers of samples and aweights
What it means
Observation weights (aweights) passed to jnp.cov must have length equal to the number of observations X.shape[1]. If np.shape(aweights)[0] != X.shape[1], RuntimeError('incompatible numbers of samples and aweights') is raised.
Source
Thrown at jax/_src/numpy/lax_numpy.py:9224
ddof = 1 if bias == 0 else 0
w: Array | None = None
if fweights is not None:
fweights = util.ensure_arraylike("cov", fweights)
if np.ndim(fweights) > 1:
raise RuntimeError("cannot handle multidimensional fweights")
if np.shape(fweights)[0] != X.shape[1]:
raise RuntimeError("incompatible numbers of samples and fweights")
if not issubdtype(fweights.dtype, np.integer):
raise TypeError("fweights must be integer.")
# Ensure positive fweights; note that numpy raises an error on negative fweights.
w = abs(fweights)
if aweights is not None:
aweights = util.ensure_arraylike("cov", aweights)
if np.ndim(aweights) > 1:
raise RuntimeError("cannot handle multidimensional aweights")
if np.shape(aweights)[0] != X.shape[1]:
raise RuntimeError("incompatible numbers of samples and aweights")
# Ensure positive aweights: note that numpy raises an error for negative aweights.
aweights = abs(aweights)
w = asarray(aweights if w is None else w * aweights)
if dtype is not None:
X = X.astype(dtype)
w = w.astype(dtype) if w is not None else w
avg, w_sum = reductions.average(X, axis=1, weights=w, returned=True)
w_sum = w_sum[0]
if w is None:
f = X.shape[1] - ddof
elif ddof == 0:
f = w_sum
elif aweights is None:
f = w_sum - ddof
else:View on GitHub (pinned to 1e1c6a8fc0)
Solutions
- Match weight length to observation count: len(aweights) == m.shape[1] (or m.shape[0] with rowvar=False)
- Slice or recompute weights after filtering data
- Add an assertion before the call
Example fix
// before jnp.cov(m, aweights=w) # len(w) != n_obs // after assert w.shape[0] == m.shape[-1] jnp.cov(m, aweights=w)
Defensive patterns
Strategy: validation
Validate before calling
n_obs = m.shape[-1] assert jnp.shape(aweights)[0] == n_obs, 'aweights length must equal number of samples' jnp.cov(m, aweights=aweights)
Prevention
- Match aweights length to X.shape[1]
- Adjust weights after subsampling
- Account for rowvar orientation
When it happens
Trigger: jnp.cov(m, y=None, aweights=np.ones(4)) with m of shape (2, 3) (3 observations); weights sized to variables rather than samples.
Common situations: rowvar confusion (weights computed for rows when columns are observations); subsampling data without adjusting weights.
Related errors
- incompatible numbers of samples and fweights
- cannot handle multidimensional fweights
- fweights must be integer.
- cannot handle multidimensional aweights
- expected w and y to have the same length
AI-assisted analysis of jax-ml/jax@1e1c6a8fc0 (2026-08-27).
Data as JSON: /api/errors/13cc92e7beecc25a.
Report an issue: GitHub.