python - R 和 Numpy 的 QR 分解之间的差异

标签 python r numpy

我正在研究一个大型 R (v3.6.0) 代码库,并试图了解它在做什么。为此,我使用 Numpy (v1.14.3) 将一些 R 代码转换为 Python (v3.6.5)。我有一段 R 代码,看起来工作得很好:

> v<-c(1,1,1,1)
> qrout<-qr(v)
> qr.Q(qrout)
     [,1]
[1,] -0.5
[2,] -0.5
[3,] -0.5
[4,] -0.5
> qr.R(qrout)
     [,1]
[1,]   -2

Python 的等价物不太很好:

>>> import numpy as np
>>> v=np.ones(4)
>>> v
array([1., 1., 1., 1.])
>>> np.linalg.qr(v)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/python/3.6.5/lib/python3.6/site-packages/numpy/linalg/linalg.py", line 753, in qr
    _assertRank2(a)
  File "/opt/python/3.6.5/lib/python3.6/site-packages/numpy/linalg/linalg.py", line 195, in _assertRank2
    'two-dimensional' % a.ndim)
numpy.linalg.linalg.LinAlgError: 1-dimensional array given. Array must be two-dimensional

查看文档,R 中似乎使用 LAPACK 的 DQRDC(2)/DGEQP3/ZGEQP3,而 Numpy 使用 LAPACK 的 >dgeqrfzgeqrfdorgqrzungqr。显然,R 对一维矩阵感到满意,而 Numpy 则不满意。

问题

如何使用 Numpy 复制 R 的 QR 分解?

最佳答案

如错误消息中所述

Array must be two-dimensional

<罢工>
In [7]: qr(v[:,None])                                                                     
Out[7]: 
(array([[-0.5],
        [-0.5],
        [-0.5],
        [-0.5]]), array([[-2.]]))

<罢工>

编辑
接下来的内容与上面的删除代码没有什么不同,但谁知道呢......

In [28]: from numpy.linalg import qr 
    ...: from numpy import ones

In [29]: v = ones(4) ; print(v.shape) ; print(v[:,None].shape) # adding a dimension
(4,)
(4, 1)

In [30]: q, r = qr(v[:, None])

In [31]: print(q) ; print() ; print(r)                 
[[-0.5]
 [-0.5]
 [-0.5]
 [-0.5]]

[[-2.]]

In [32]:

在 Python/Numpy 数组中只能有一维,但是 qr需要一个二维数组。

例如,在 Python 中,转置不会修改本质上一维向量的维度。

In [9]: print(v); print(v.T)                                                              
[1 1 1 1]
[1 1 1 1]

[10]: print(v.shape); print((v.T).shape)                                                
(4,)
(4,)

在 R 中,qr()尝试将其输入强制为二维数组(矩阵),因此 qr()为您执行此步骤,而在 Python 中您必须显式执行此步骤。

向 Numpy 数组添加维度的最惯用方法是使用 None在切片对象中表示向其添加虚拟维度。

关于python - R 和 Numpy 的 QR 分解之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58713843/

相关文章:

python - 如何从一组数据点插入单个 ("non-piecewise") 三次样条?

Python按以下顺序创建物化路径

python - 如何更改列表的顺序,同时保留对原始 Python 的引用

python - 如何检索两个 3D 向量之间的角度?

python - numpy.unique 对 numpy.array 的对象表现得很奇怪

r - ggplot2 本地和 Shiny 托管输出之间的差异

python - Python 2D 热图中的行数增加

python - 如何从 python 列表中只删除零位?

r - 如何最好地比较公式?

r - 将变量从逗号拆分为有序数据框