jax-ml/jax · error · TypeError

{}-dimensional array given. Array must be at least two-dimen

Error message

{}-dimensional array given. Array must be at least two-dimensional

What it means

jnp.linalg.matrix_power raises a matrix to an integer power n and therefore requires at least a 2D square input. If the input array has fewer than 2 dimensions, TypeError('{ndim}-dimensional array given. Array must be at least two-dimensional') is raised, matching NumPy.

Source

Thrown at jax/_src/numpy/linalg.py:381

    and also supports negative powers:

    >>> with jnp.printoptions(precision=3):
    ...   jnp.linalg.matrix_power(a, -2)
    Array([[ 5.5 , -2.5 ],
           [-3.75,  1.75]], dtype=float32)

    Negative powers are equivalent to matmul of the inverse:

    >>> inv_a = jnp.linalg.inv(a)
    >>> with jnp.printoptions(precision=3):
    ...   inv_a @ inv_a
    Array([[ 5.5 , -2.5 ],
           [-3.75,  1.75]], dtype=float32)
  """
  arr = ensure_arraylike("jnp.linalg.matrix_power", a)

  if arr.ndim < 2:
    raise TypeError("{}-dimensional array given. Array must be at least "
                    "two-dimensional".format(arr.ndim))
  if arr.shape[-2] != arr.shape[-1]:
    raise TypeError("Last 2 dimensions of the array must be square")
  try:
    n = operator.index(n)
  except TypeError as err:
    raise TypeError(f"exponent must be an integer, got {n}") from err

  if n == 0:
    return jnp.broadcast_to(jnp.eye(arr.shape[-2], dtype=arr.dtype), arr.shape)
  elif n < 0:
    arr = inv(arr)
    n = abs(n)

  if n == 1:
    return arr
  elif n == 2:
    return arr @ arr

View on GitHub (pinned to 1e1c6a8fc0)

Solutions

  1. Reshape to 2D: a.reshape(1, -1) or the intended square shape
  2. Use jnp.pow / ** for elementwise powers of vectors or scalars
  3. Verify a.ndim >= 2 and a.shape[-2] == a.shape[-1] before calling

Example fix

// before
jnp.linalg.matrix_power(vec, 3)  # vec is 1D
// after
jnp.linalg.matrix_power(vec.reshape(1, -1) @ vec.reshape(-1, 1) ... )
// or if elementwise power was meant:
vec ** 3
Defensive patterns

Strategy: validation

Validate before calling

a = jnp.asarray(a)
assert a.ndim >= 2, 'matrix_power needs at least 2D input'
jnp.linalg.matrix_power(a, n)

Type guard

def is_matrix(x) -> bool:
    return jnp.asarray(x).ndim >= 2

Prevention

When it happens

Trigger: jnp.linalg.matrix_power(1D_vector, n), or a scalar/0-dim input; e.g. matrix_power(jnp.arange(4), 3). Called in tests like testMatrixPowerBool with non-matrix input.

Common situations: Passing a vector when a (1, n) or square matrix was intended; iterating over rows of a batch and forgetting to index yields scalars; boolean arrays also flow through this same check.

Related errors


AI-assisted analysis of jax-ml/jax@1e1c6a8fc0 (2026-08-27). Data as JSON: /api/errors/25a1613a0b92f00b. Report an issue: GitHub.