获取第一个奇异值

时间:2019-10-03 19:37:12

标签: python matrix

我一直在尝试找到获取矩阵的前两个奇异值的方法。但是经过几次研究之后,我认为我可以在这里找到一些帮助,以寻求如何找到矩阵的第一个奇异值。

 import numpy.matlib
 import numpy as np
 from scipy.linalg import svd


 def get_singular_values(M, k):

     u, s, v = np.linalg.svd(M, full_matrices=False)

     singular_values = numpy.matrix(u[:, :k]) * numpy.diag(s[:k]) * 
     numpy.matrix(v[:k, :]) #my attempt

     return singular_values


 M = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

 only_first_singular_value = get_singular_values(M, 1) #first singular
 print(only_first_singular_value) # 1 is for first singular
 only_first_singular_value = get_singular_values(M, 2) #first two singular
 print(only_first_singular_value) # 2 is for 2 singular

1 个答案:

答案 0 :(得分:0)

np.linalg.svd()直接为您提供奇异值:

In [1]: m = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])

In [2]: _, s, _ = np.linalg.svd(m)

In [3]: s[0] # first singular value
Out[3]: 25.462407436036397

In [4]: s[1] # second singular value
Out[4]: 1.2906616757612328