{"record":{"id":"6a57d33089ac2b85","repo":"keras-team/keras","slug":"lu-decomposition-failed-e-lu-decomposition-is","errorCode":null,"errorMessage":"LU decomposition failed: {e}. LU decomposition is only supported for square matrices in Tensorflow.","messagePattern":"LU decomposition failed: (.+?)\\. LU decomposition is only supported for square matrices in Tensorflow\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"keras/src/ops/linalg.py","lineNumber":276,"sourceCode":"    Returns:\n        A tuple of two tensors: a tensor of shape `(..., M, M)` containing the\n        lower and upper triangular matrices and a tensor of shape `(..., M)`\n        containing the pivots.\n\n    \"\"\"\n    if any_symbolic_tensors((x,)):\n        return LuFactor().symbolic_call(x)\n    return _lu_factor(x)\n\n\ndef _lu_factor(x):\n    x = backend.convert_to_tensor(x)\n    _assert_2d(x)\n    if backend.backend() == \"tensorflow\":\n        try:\n            _assert_square(x)\n        except ValueError as e:\n            raise ValueError(\n                f\"LU decomposition failed: {e}. LU decomposition is only \"\n                \"supported for square matrices in Tensorflow.\"\n            )\n    return backend.linalg.lu_factor(x)\n\n\nclass Norm(Operation):\n    def __init__(self, ord=None, axis=None, keepdims=False, *, name=None):\n        super().__init__(name=name)\n        if isinstance(ord, str):\n            if ord not in (\"fro\", \"nuc\"):\n                raise ValueError(\n                    \"Invalid `ord` argument. \"\n                    \"Expected one of {'fro', 'nuc'} when using string. \"\n                    f\"Received: ord={ord}\"\n                )\n        if isinstance(axis, int):\n            axis = [axis]","sourceCodeStart":258,"sourceCodeEnd":294,"githubUrl":"https://github.com/keras-team/keras/blob/7a34a03db60bf60042242d6a556fc3be119046a5/keras/src/ops/linalg.py#L258-L294","documentation":"lu_factor on the TensorFlow backend checks squareness explicitly because TF's LU implementation only supports square matrices; the underlying _assert_square ValueError is rewrapped with this backend-specific note. Non-square input works on JAX/NumPy backends but raises here on TensorFlow.","triggerScenarios":"keras.ops.linalg.lu_factor(rectangular_matrix) while backend() == 'tensorflow'; code that ran on JAX/NumPy with tall matrices then switched the keras backend to 'tensorflow'.","commonSituations":"Portable code written against JAX scipy.linalg.lu_factor semantics; solving least-squares-style systems on TF where a QR-based path is actually required.","solutions":["Pad or crop the matrix to square before lu_factor on the TF backend.","Switch to a QR or SVD-based solve for non-square systems.","Or run that computation on the numpy/jax backend if rectangular LU is required."],"exampleFix":"# before\nlu, p = keras.ops.linalg.lu_factor(A)  # A: (m, n), m != n, TF backend\n\n# after\nn = min(A.shape)\nlu, p = keras.ops.linalg.lu_factor(A[:n, :n])","handlingStrategy":"validation","validationCode":"import numpy as np, keras\nA = np.asarray(x)\nif keras.backend.backend() == 'tensorflow':\n    assert A.ndim == 2 and A.shape[0] == A.shape[1], 'TF lu_factor needs square input'","typeGuard":"def lu_factorizable(x, backend='tensorflow'):\n    A = np.asarray(x)\n    return A.ndim == 2 and (backend != 'tensorflow' or A.shape[0] == A.shape[1])","tryCatchPattern":"try:\n    lu, p = keras.ops.linalg.lu_factor(A)\nexcept ValueError as e:\n    if 'only supported for square matrices' in str(e):\n        n = min(A.shape)\n        lu, p = keras.ops.linalg.lu_factor(A[:n, :n])\n    else:\n        raise","preventionTips":["Gate backend-specific linear algebra behind a backend check.","Prefer QR for rectangular least-squares problems."],"tags":["keras","linalg","lu","tensorflow","backend-specific"],"backgroundTag":"backend-unsupported-operation","analyzedSha":"7a34a03db60bf60042242d6a556fc3be119046a5","analyzedAt":"2026-08-25T21:25:25.994Z","schemaVersion":2},"datasetVersion":"2026-08-26T02:17:13.382Z"}