PyTorch torch.linalg.qr Function


Pytorch torch 参考手册Pytorch torch Reference Manual

torch.linalg.qrIt is a function in the PyTorch linear algebra module used to compute the QR decomposition of a matrix. QR decomposition factorizes 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 the tuple (Q, R).

Usage Example

Example

import torch

# Create 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)

print("Matrix A:")
print(A)
print("nOrthogonal matrix Q:")
print(Q)
print("nUpper triangular matrix R:")
print(R)
print("nVerification: Q @ R =")
print(Q @ R)

The output result 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.]])

Pytorch torch 参考手册Pytorch torch Reference Manual

Other Extensions