Singular value decomposition (SVD), low-rank approximation (LRA) in Python

If you want to speed up, I don't think you will use it from Lapack or Python, so I hope you can use such scientific and technological calculations as much as the answers of people who do it in cuda, C, or C ++.

I thought it was a memo

Source code

low_rank_approximation.py


import numpy as np
from scipy import linalg

def low_rank_approximation(a,rank):
    u, s, v = linalg.svd(a)
    ur = u[:, :rank]
    sr = np.matrix(linalg.diagsvd(s[:rank], rank,rank))
    vr = v[:rank, :]
    return np.asarray(ur*sr*vr)

A = np.array([[1,2,3],[4,5,6],[7,8,9]])
print A
B = low_rank_approximation(A,1)
print B

# python low_rank_approximation.py
# [[1 2 3]
#  [4 5 6]
#  [7 8 9]]
# [[ 1.73621779  2.07174246  2.40726714]
#  [ 4.2071528   5.02018649  5.83322018]
#  [ 6.6780878   7.96863051  9.25917322]]

reference

Recommended Posts

Singular value decomposition (SVD), low-rank approximation (LRA) in Python
Low-rank approximation of images by singular value decomposition
LU decomposition in Python
Shapley value calculation in Python
Low-rank approximation of images by Tucker decomposition
[Python] Invert bool value in one line
String → Bool value conversion in Python Consideration
File DL, byte value and delete in Python3
Try singular value decomposition of the daimyo matrix
Find the divisor of the value entered in python