keras-team/keras · error · TypeError

n must be an integer. Received: n=

Error message

n must be an integer. Received: n={n} of type {type(n)}

What it means

MatrixPower.__init__ in keras/src/ops/linalg.py type-checks its exponent: n must be a Python int. It raises TypeError when a float, numpy scalar, tensor, or other non-int is passed as the power to which each matrix in x will be raised.

Solutions

  1. Pass a plain Python int, e.g. keras.ops.matrix_power(a, 3) not 3.0
  2. Convert explicitly with int(n) if the exponent comes from a float or numpy scalar
  3. For fractional powers use another formulation (e.g. eigendecomposition or pinv) instead of matrix_power
Defensive patterns

Strategy: type-guard

When it happens

Trigger: Thrown at keras/src/ops/linalg.py:739 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25). Data as JSON: /api/errors/50dc79e494eef379. Report an issue: GitHub.

Appendix: source

Thrown at keras/src/ops/linalg.py:739

        An integer tensor of shape `(...,)` with the rank of each matrix
        in the batch.

    Example:

    >>> a = keras.ops.convert_to_tensor([[1., 2.], [2., 4.]])
    >>> keras.ops.matrix_rank(a)
    1
    """
    if any_symbolic_tensors((x,)):
        return MatrixRank(tol=tol).symbolic_call(x)
    return backend.linalg.matrix_rank(x, tol=tol)


class MatrixPower(Operation):
    def __init__(self, n, *, name=None):
        super().__init__(name=name)
        if not isinstance(n, int):
            raise TypeError(
                f"n must be an integer. Received: n={n} of type {type(n)}"
            )
        self.n = n

    def call(self, x):
        return _matrix_power(x, self.n)

    def compute_output_spec(self, x):
        _assert_2d(x)
        _assert_square(x)
        return KerasTensor(x.shape, x.dtype)


@keras_export(["keras.ops.matrix_power", "keras.ops.linalg.matrix_power"])
def matrix_power(x, n):
    """Raise a square matrix to the (integer) power `n`.

    For positive integers `n`, the power is computed by repeated matrix

View on GitHub (pinned to 7a34a03db6)