PyTorch torch.linalg.qr function
PyTorch torch reference manual
torch.linalg.qr is a function in PyTorch's linear algebra module used to compute the QR decomposition of a matrix. QR decomposition factors matrix A as A = Q * R, where Q is an orthogonal matrix and R is an upper triangular matrix.
Function definition
torch.linalg.qr(A, mode='reduced', out=None)
Parameters:
A(Tensor): Input matrix.mode(str, optional): 'reduced' returns the reduced decomposition, 'complete' returns the complete decomposition. Defaults to 'reduced'.out(tuple, optional): Output tuple.
Return Value:
tuple: Returns a tuple (Q, R).
Usage examples
Example
import
torch
Create a matrix
A
=
torch.
tensor
(
[
[
12.0
,
51.0
,
4.0
]
,
[
6.0
,
167.0
,
68.0
]
,
[
4.0
,
24.0
,
41.0
]
]
)
QR decomposition
Q
,
R
=
torch.
linalg
.
qr
(
A
)
(
"Matrix A:"
)
(
A
)
(
"nOrthogonal matrix Q:"
)
(
Q
)
(
"nUpper triangular matrix R:"
)
(
R
)
(
"nVerify: Q @ R ="
)
(
Q
@
R
)
The output is:
矩阵 A:
tensor([[ 12., -51., 4.],
[ 6., 167., -68.],
[ -4., 24., -41.]])
正交矩阵 Q:
tensor([[-0.8571, 0.3943, 0.3314],
[-0.4286, -0.9029, -0.0343],
[ 0.2857, -0.1714, 0.9428]])
上三角矩阵 R:
tensor([[ -14., -21., 14.],
[ 0., -175., 70.],
[ 0., 0., -35.]])
验证: Q @ R =
tensor([[ 12., -51., 4.],
[ 6., 167., -68.],
[ -4., 24., -41.]])