LoginSignup
6
6

More than 5 years have passed since last update.

pythonでQL分解とQR分解

Posted at

numpyには(他のライブラリにも)QR分解あるけどQL分解がないので簡単に作る.

行列生成

import numpy as np

A = np.random.rand(4,4)
print(A)
output
[[ 0.79124883  0.99846239  0.68643175  0.62022478]
 [ 0.62550988  0.4907801   0.43422796  0.70191408]
 [ 0.55936063  0.31190068  0.77154881  0.08427772]
 [ 0.11253189  0.65420468  0.46686985  0.11447206]]

QR分解

QR分解
Q, R = np.linalg.qr(A)
print('Q\n', Q)
print('R\n', R)
print('Q @ R\n', Q @ R)
print('A == Q @ R ?', np.allclose(A, Q @ R))
print('Q @ Q^T == I ?', np.allclose(Q @ Q.transpose(), np.eye(4)))
print('Q^T @ Q == I ?', np.allclose(Q.transpose() @ Q, np.eye(4)))
output
Q
 [[-0.68280023  0.31934702  0.36684631 -0.54518356]
 [-0.53977747 -0.21055993  0.30305429  0.75661278]
 [-0.48269464 -0.38522751 -0.77364703 -0.14168954]
 [-0.09710826  0.83981055 -0.41839235  0.33201818]]
R
 [[-1.15882918 -1.16074386 -1.12084163 -0.85416362]
 [ 0.          0.64477264  0.22263932  0.1139407 ]
 [ 0.          0.         -0.40883161  0.32714981]
 [ 0.          0.          0.          0.21900634]]
Q @ R
 [[ 0.79124883  0.99846239  0.68643175  0.62022478]
 [ 0.62550988  0.4907801   0.43422796  0.70191408]
 [ 0.55936063  0.31190068  0.77154881  0.08427772]
 [ 0.11253189  0.65420468  0.46686985  0.11447206]]
A == Q @ R ? True
Q @ Q^T == I ? True
Q^T @ Q == I ? True

QL分解

QL分解
def QL(A):
    """
    QL factorization by using QR factorization
    """
    Q, L = np.linalg.qr(A[::-1,::-1])
    return Q[::-1,::-1], L[::-1,::-1]


Q, L = QL(A)
print('Q\n', Q)
print('L\n', L)
print('Q @ L\n', Q @ L)
print('A == Q @ L ?', np.allclose(A, Q @ L))
print('Q @ Q^T == I ?', np.allclose(Q @ Q.transpose(), np.eye(4)))
print('Q^T @ Q == I ?', np.allclose(Q.transpose() @ Q, np.eye(4)))
output
Q
 [[ 0.61195303  0.42670519 -0.1218915  -0.65465917]
 [-0.44726347 -0.4150739   0.28064256 -0.74088379]
 [ 0.09753892 -0.51781405 -0.84524639 -0.08895675]
 [-0.64494576  0.61441431 -0.43811043 -0.12082746]]
L
 [[ 0.18642187  0.          0.          0.        ]
 [-0.14250644  0.46278524  0.          0.        ]
 [-0.44300076 -0.53421711 -0.81849675  0.        ]
 [-1.04478428 -1.12405514 -0.89613647 -0.94740105]]
Q @ L
 [[ 0.79124883  0.99846239  0.68643175  0.62022478]
 [ 0.62550988  0.4907801   0.43422796  0.70191408]
 [ 0.55936063  0.31190068  0.77154881  0.08427772]
 [ 0.11253189  0.65420468  0.46686985  0.11447206]]
A == Q @ L ? True
Q @ Q^T == I ? True
Q^T @ Q == I ? True
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6