torch.Tensor.Tensor.inverse
Compute the matrix inverse of a square matrix or batch of matrices.
Returns the multiplicative inverse A^-1 such that A @ A^-1 = I (identity). Only defined for square matrices with full rank (determinant ≠ 0). Essential for solving linear systems and matrix equations.
Common use cases:
- Solving linear equations (Ax = b → x = A^-1 @ b)
- Matrix equation solving
- Covariance matrix inversion
- Quadratic form computation
- Numerical algorithms requiring matrix inversion
- Square matrices only: Shape must be (..., n, n).
- Full rank required: Matrix must be invertible (det ≠ 0).
- Batch support: Works on batches of matrices (first dimensions are batch).
- Numerical stability: May be ill-conditioned for near-singular matrices.
- GPU acceleration: Optimized on WebGPU with parallel batch processing.
- Singular matrices: Raises error if matrix is singular (det ≈ 0).
- Numerical instability: Ill-conditioned matrices may produce inaccurate results.
- Precision loss: Inverting twice doesn't guarantee recovery of original.
- Performance: O(n³) complexity; slow for large matrices.
Returns
Tensor<S, D, Dev>– Matrix inverse with same shape as input. If input is batch of matrices, computes inverse for each matrix in the batch.Examples
// Simple matrix inversion
const A = torch.tensor([[4, 7], [2, 6]]);
const A_inv = A.inverse();
// A @ A_inv ≈ [[1, 0], [0, 1]] (identity)
// Solve linear system: Ax = b
const b = torch.tensor([1, 2]);
const x = A.inverse().matmul(b); // Solution
// Batch matrix inversion
const batch_A = torch.randn(32, 5, 5); // 32 matrices of shape [5, 5]
const batch_A_inv = batch_A.inverse(); // [32, 5, 5]
// Covariance matrix inversion (statistics)
const data = torch.randn(100, 10); // 100 samples, 10 features
const cov = data.T().matmul(data).div(100); // [10, 10] covariance
const cov_inv = cov.inverse(); // Precision matrixSee Also
- PyTorch tensor.inverse()
- solve - Solve Ax = b directly (more numerically stable)
- matmul - Matrix multiplication
- det - Determinant (zero means singular)
- pinverse - Pseudo-inverse for non-square matrices