How to Perform QR Decomposition of Matrices in NumPy (Using np.linalg.qr)

In matrix calculations, separating a matrix into an “orthogonal matrix (Q)” and an “upper triangular matrix (R)” is known as QR decomposition. This is a crucial method widely used when solving least squares problems or preprocessing for eigenvalue calculations. In NumPy, you can easily perform this calculation using the np.linalg.qr() function.

目次

1. Executable Sample Code

Here, we will define a 3×2 matrix and decompose it into Q and R. We will also confirm that multiplying the decomposed results reconstructs the original matrix.

import numpy as np

def qr_decomposition_demo():
    # 1. Define the matrix to decompose
    # Preparing a 3x2 matrix here
    matrix_a = np.array([
        [12, -51],
        [6, 167],
        [-4, 24]
    ])

    print("--- Original Matrix A ---")
    print(matrix_a)

    # 2. Execute QR Decomposition
    # q: Orthogonal matrix
    # r: Upper triangular matrix
    q, r = np.linalg.qr(matrix_a)

    print("\n--- Matrix Q (Orthogonal Matrix) ---")
    print(q)

    print("\n--- Matrix R (Upper Triangular Matrix) ---")
    print(r)

    # 3. Verification
    # Multiplying Q and R (dot product) should return the original A
    reconstructed_a = np.dot(q, r)
    
    print("\n--- Reconstructed A (Q @ R) ---")
    # Floating point errors may occur, so sometimes rounding is used for display
    print(reconstructed_a)

    # Bonus: Checking Orthogonality of Q
    # For an orthogonal matrix Q, the product with its transpose becomes the identity matrix (Q.T @ Q = I)
    print("\n--- Orthogonality Check (Q.T @ Q) ---")
    print(np.dot(q.T, q))

if __name__ == "__main__":
    qr_decomposition_demo()

2. Explanation: Meaning of Return Values

q (Orthogonal Matrix)

This is a matrix where the column vectors are orthogonal to each other (at right angles), and the size (norm) of each is 1. As shown in the verification part of the sample code, multiplying this matrix by its own transpose results in an identity matrix.

r (Upper Triangular Matrix)

This is a matrix where all elements below the diagonal line are 0. When solving systems of linear equations, having the matrix in this form allows for a method called “back substitution.” This makes it easier to find the solution and improves calculation efficiency.

3. About the mode Argument

You can specify the mode, such as np.linalg.qr(a, mode='reduced').

  • ‘reduced’ (Default): Returns Q and R in a compact size matching the shape of the input matrix. This is typically used.
  • ‘complete’: Calculates Q as a complete square matrix and the corresponding R.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次