Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201945

Differences between R's and Numpy's QR decomposition

$
0
0

I'm working through a large R (v3.6.0) codebase and trying to understand what it is doing. To do this, I'm translating some of the R code into Python (v3.6.5) using Numpy (v1.14.3). I have a piece of R code that appears to work just fine:

> 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

The Python equivalent is not fine :

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

Looking at the docs it appears that in R uses LAPACK's DQRDC(2)/DGEQP3/ZGEQP3, while Numpy uses LAPACK's dgeqrf, zgeqrf, dorgqr, and zungqr. Clearly R is happy with a 1 dimensional matrix, while Numpy is not.

QUESTION

How do I replicate R's QR factorization using Numpy?


Viewing all articles
Browse latest Browse all 201945

Trending Articles