获取np.linalg.svd的奇异值作为矩阵 [英] Getting the singular values of np.linalg.svd as a matrix

查看:186
本文介绍了获取np.linalg.svd的奇异值作为矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个5x4矩阵A =

Given a 5x4 matrix A =

一段用于构建矩阵的python代码

A piece of python code to construct the matrix

A = np.array([[1, 0, 0, 0],
              [0, 0, 0, 4],
              [0, 3, 0, 0],
              [0, 0, 0, 0],
              [2, 0, 0, 0]])

wolframalpha 给出svd结果

具有奇异值Σ的向量采用这种形式

the Vector(s) with the singular values Σ is in this form

np.linalg.svd的输出中的等效量(NumPy称为s)采用这种形式

the equivalent quantity (NumPy call it s) in the output of np.linalg.svd is in this form

[ 4.          3.          2.23606798 -0.        ]

是否有一种方法可以使numpy.linalg.svd输出中的数量显示为wolframalpha?

is there a way to have the quantity in output of numpy.linalg.svd shown as wolframalpha?

推荐答案

您可以使用diag大部分方法:

You can get most of the way there with diag:

>>> u, s, vh = np.linalg.svd(a)
>>> np.diag(s)
array([[ 4.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  3.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  2.23606798,  0.        ],
       [ 0.        ,  0.        ,  0.        , -0.        ]])

请注意,Wolfram Alpha额外增加了一行.要获得更多的参与是

Note that wolfram alpha is giving an extra row. Getting that is marginally more involved:

>>> sigma = np.zeros(A.shape, s.dtype)
>>> np.fill_diagonal(sigma, s)
>>> sigma
array([[ 4.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  3.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  2.23606798,  0.        ],
       [ 0.        ,  0.        ,  0.        , -0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ]])

根据您的目标,从U中删除列可能比在sigma中添加零行更好.看起来像:

Depending on what your goal is, removing a column from U might be a better approach than adding a row of zeros to sigma. That would look like:

>>> u, s, vh = np.linalg.svd(a, full_matrices=False)

这篇关于获取np.linalg.svd的奇异值作为矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆