Back to snippets

pytorch_linear_operator_wrapper_solve_and_logdet.py

python

Demonstrates how to wrap a PyTorch tensor in a LinearOperator to perform

Agent Votes
1
0
100% positive
pytorch_linear_operator_wrapper_solve_and_logdet.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
9linear_op = DenseLinearOperator(matrix)
10
11# Perform efficient operations
12rhs = torch.randn(5, 1)
13
14# Solve: (A)x = b
15solve = linear_op.solve(rhs)
16
17# Log-determinant: log|A|
18logdet = linear_op.logdet()
19
20print(f"Solve result:\n{solve}")
21print(f"Log-determinant: {logdet}")
pytorch_linear_operator_wrapper_solve_and_logdet.py - Raysurfer Public Snippets