在python中重现Matlab的SVD [英] Reproduce Matlab's SVD in python

查看:208
本文介绍了在python中重现Matlab的SVD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重现一些使用python用Matlab编写的大型项目. 我设法重现了大多数结果,但是我特别对SVD分解存在问题. (我只看最后的V部分).

I'm trying to reproduce some large project that was written in Matlab, using python. I managed to reproduce most of the results, but I have a problem specifically with SVD decomposition. (I'm looking only on the last, V, part.)

在Matlab中:

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

这使我得到以下V:

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

以numpy格式显示:

in 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]

得到我:

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

哪个换位了(我认为应该在numpy和matlab之间换位),但是在某些减号上也有所不同.

Which is transposed (as I think is expected between numpy and matlab) but also different on some minus signs.

即使使用opencv(cv2)或scipy(甚至使用lapack_driver ="gesvd"),仍然会得到相同的结果

even using opencv (cv2) or scipy (even with lapack_driver="gesvd") still gets the same result

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

使用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]])

这篇关于在python中重现Matlab的SVD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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