简体   繁体   English

在python中重现Matlab的SVD

[英]Reproduce Matlab's SVD in python

I'm trying to reproduce some large project that was written in Matlab, using python. 我正在尝试使用python复制一些用Matlab编写的大型项目。 I managed to reproduce most of the results, but I have a problem specifically with SVD decomposition. 我设法重现了大多数结果,但是我特别对SVD分解有问题。 (I'm looking only on the last, V, part.) (我只看最后的第五部分。)

In Matlab: 在Matlab中:

[~, ~, V] = svd([4.719, -17.257, -11.5392; -17.2575, 63.9545, 40.5581; -11.5392, 40.5581, 31.3256]);

This gets me the following V: 这使我获得以下V:

-0.2216    0.0241   -0.9748
0.8081   -0.5549   -0.1974
0.5457    0.8316   -0.1035

in numpy: 在numpy中:

 np.linalg.svd(np.array([[4.71993, -17.2575, -11.539], [-17.257, 63.954, 40.558], [-11.539, 40.558, 31.325]]))[2]

Gets me: 得到我:

array([[-0.22159139,  0.80814521,  0.54570924],
       [ 0.02407525, -0.55491709,  0.83155722],
       [ 0.97484237,  0.19740401,  0.10350855]])

Which is transposed (as I think is expected between numpy and matlab) but also different on some minus signs. 这是换位的(正如我认为在numpy和matlab之间所期望的),但在某些减号上也有所不同。

even using opencv (cv2) or scipy (even with lapack_driver="gesvd") still gets the same result 即使使用opencv(cv2)或scipy(即使使用lapack_driver =“ gesvd”),仍然会得到相同的结果

scipy.linalg.svd(np.array([[4.71993, -17.2575, -11.539], [-17.257, 63.954, 40.558], [-11.539, 40.558, 31.325]]), lapack_driver="gesvd")[2]

I also tried to transpose the input matrix, which didn't change much. 我还尝试转置输入矩阵,该矩阵变化不大。

I understand that both answers are correct. 我知道两个答案都是正确的。 But I really need to get the exact same result to be able to reproduce the project. 但是我确实需要获得完全相同的结果才能重现该项目。

you're not representing the matrix the same in both environments (different numerical precision). 您在两种环境中都不能代表相同的矩阵(不同的数值精度)。 If you use the same matrix it should be equivalent (transpose). 如果使用相同的矩阵,则应等效(转置)。

>> a=[[4.71993, -17.2575, -11.539]; [-17.257, ...
a =

    4.7199  -17.2575  -11.5390
  -17.2570   63.9540   40.5580
  -11.5390   40.5580   31.3250

>> [~,~,v]=svd(a);
>> v'
ans =

  -0.221591   0.808145   0.545709
   0.024075  -0.554917   0.831557
   0.974842   0.197404   0.103509

with Python 用Python

import numpy as np

np.set_printoptions(precision=6)
a=[[4.71993, -17.2575, -11.539], [-17.257, ...
np.linalg.svd(np.array(a))[2]

array([[-0.221591,  0.808145,  0.545709],
       [ 0.024075, -0.554917,  0.831557],
       [ 0.974842,  0.197404,  0.103509]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM