0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pythonで特異値分解を左右特異ベクトルと特異値行列を計算して再現を確認

Posted at

行列Xを特異値分解して元の行列を再現する

$X = USV$
と特異値分解して各行列$U,S,V$を計算する

特異値分解する行列$X$を設定

import numpy as np

X = np.array([
    [1,2],
    [3,4],
    [5,6],
    [7,8]
])
print(X)
[[1 2]
 [3 4]
 [5 6]
 [7 8]]

$X$(M行×N列)のM,Nを求めて
M=Nの時
M>Nの時
M<Nの時
で場合分けして$U,S,V$を計算する

M,N = X.shape

U,D,V = np.linalg.svd(X)
if M == N:
    S = np.diag(D)
elif M > N:
    S = np.vstack([np.diag(D),np.zeros((M-N,N))])
else:
    S = np.hstack([np.diag(D),np.zeros((M,N-M))])
print('(M,N)=',(M,N))
print('S.shape:',S.shape,'\n')
print('U:\n',U,'\n')
print('S:\n',S,'\n')
print('V:\n',V,'\n')
(M,N)= (4, 2)
S.shape: (4, 2) 

U:
 [[-0.15248323 -0.82264747 -0.39450102 -0.37995913]
 [-0.34991837 -0.42137529  0.24279655  0.80065588]
 [-0.54735351 -0.0201031   0.69790998 -0.46143436]
 [-0.74478865  0.38116908 -0.5462055   0.04073761]] 

S:
 [[14.2690955   0.        ]
 [ 0.          0.62682823]
 [ 0.          0.        ]
 [ 0.          0.        ]] 

V:
 [[-0.64142303 -0.7671874 ]
 [ 0.7671874  -0.64142303]] 

$USV$で元の行列$X$が再現されているかを確認

print(np.dot(np.dot(U,S),V))
[[1. 2.]
 [3. 4.]
 [5. 6.]
 [7. 8.]]
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?