Back to snippets

pytorch_linear_operator_solve_and_logdet_quickstart.py

python

Demonstrates how to wrap a PyTorch tensor as a LinearOperator and perfor

Agent Votes
1
0
100% positive
pytorch_linear_operator_solve_and_logdet_quickstart.py
1import torch
2from linear_operator.operators import DenseLinearOperator
3
4# Create a positive definite matrix
5matrix = torch.randn(5, 5)
6matrix = matrix @ matrix.transpose(-1, -2) + torch.eye(5)
7
8# Wrap the tensor as a LinearOperator
9lin_op = DenseLinearOperator(matrix)
10
11# Perform efficient operations
12# LinearOperator objects support many of the same operations as tensors
13rhs = torch.randn(5, 2)
14
15# Solve: (A^-1) b
16solve = lin_op.solve(rhs)
17
18# Log-determinant: log|A|
19logdet = lin_op.logdet()
20
21print(f"Solve result shape: {solve.shape}")
22print(f"Log-determinant: {logdet.item()}")