jax-ml/jax · error · ValueError
y has more than 2 dimensions
Error message
y has more than 2 dimensions
What it means
jnp.cov computes covariance and, when an optional second variable array y is supplied, promotes m and y to inexact dtypes and requires y to have at most 2 dimensions. A y with ndim > 2 raises ValueError('y has more than 2 dimensions'), matching NumPy's error.
Source
Thrown at jax/_src/numpy/lax_numpy.py:9180
Array([[ 1., -1.],
[-1., 1.]], dtype=float32)
In general, the entries of the covariance matrix may be any positive
or negative real value. For example, here is the covariance of 100
points drawn from a 3-dimensional standard normal distribution:
>>> key = jax.random.key(0)
>>> x = jax.random.normal(key, shape=(3, 100))
>>> with jnp.printoptions(precision=2):
... print(jnp.cov(x))
[[0.9 0.03 0.1 ]
[0.03 1. 0.01]
[0.1 0.01 0.85]]
"""
if y is not None:
m, y = util.promote_args_inexact("cov", m, y)
if y.ndim > 2:
raise ValueError("y has more than 2 dimensions")
else:
m, = util.promote_args_inexact("cov", m)
if m.ndim > 2:
raise ValueError("m has more than 2 dimensions") # same as numpy error
if dtype is not None and not dtypes.issubdtype(dtype, np.inexact):
raise ValueError(f"cov: dtype must be a subclass of float or complex; got {dtype=}")
X = atleast_2d(m)
if not rowvar and m.ndim != 1:
X = X.T
if X.shape[0] == 0:
return array([]).reshape(0, 0)
if y is not None:
y_arr = atleast_2d(y)
if not rowvar and y_arr.shape[0] != 1:View on GitHub (pinned to 1e1c6a8fc0)
Solutions
- Reshape y to at most 2D before calling: y.reshape(-1, y.shape[-1])
- If y is redundant, pass y=None
- Compute covariance per-slice with vmap over the extra dimensions
Example fix
// before jnp.cov(m, y_3d) # ValueError // after jnp.cov(m, y_3d.reshape(-1, y_3d.shape[-1]))
Defensive patterns
Strategy: validation
Validate before calling
if y is not None:
y = jnp.asarray(y)
assert y.ndim <= 2, 'y must be 1D or 2D'
jnp.cov(m, y) Type guard
def cov_ready_y(y) -> bool:
return y is None or jnp.asarray(y).ndim <= 2 Prevention
- Reshape extra tensor dims before cov
- Use vmap for batched covariance
- Keep observation data 2D
When it happens
Trigger: jnp.cov(m, y) where y is 3D or higher, e.g. an image batch of shape (N, H, W) passed as y.
Common situations: Feeding stacked/multidimensional tensors (e.g. batches of images or time-series windows) as the y argument without reshaping to 1D/2D.
Related errors
- m has more than 2 dimensions
- cannot handle multidimensional fweights
- cannot handle multidimensional aweights
- covariance does not have dimension {self.d}
- scan got `length` argument of {} which disagrees with leadin
AI-assisted analysis of jax-ml/jax@1e1c6a8fc0 (2026-08-27).
Data as JSON: /api/errors/ef8fa628f263c794.
Report an issue: GitHub.