R lsfit()和Numpy lstsq()

时间:2014-10-10 00:39:51

标签: python r numpy least-squares

我在numpy做一些数学,在R中,我认为它应该得到相同的结果,但它没有,你能解释一下原因吗?我怎样才能模仿我从Numpy得到的结果?在R?

NUMPY / PYTHON

>>> X
matrix([[ 1,  0,  0, -1,  0,  0],
        [ 0, -1,  1,  0,  0,  0],
        [ 1,  0,  0,  0,  0, -1],
        [ 0, -1,  0,  0,  1,  0],
        [ 0,  0,  1,  0,  0, -1],
        [ 0,  0,  0, -1,  1,  0]])
>>> y
matrix([[500],
        [300],
        [600],
        [250],
        [400],
        [350]])
>>> linalg.lstsq(X,y)[0]
matrix([[ 316.66666667],
        [-133.33333333],
        [ 150.        ],
        [-200.        ],
        [ 133.33333333],
        [-266.66666667]])

[R

> X
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    0    0   -1    0    0
[2,]    0   -1    1    0    0    0
[3,]    1    0    0    0    0   -1
[4,]    0   -1    0    0    1    0
[5,]    0    0    1    0    0   -1
[6,]    0    0    0   -1    1    0

> y
     [,1]
[1,]  500
[2,]  300
[3,]  600
[4,]  250
[5,]  400
[6,]  350

> lsfit(X,y, intercept=FALSE)$coef
       X1        X2        X3        X4        X5        X6 
583.33333 133.33333 416.66667  66.66667 400.00000   0.00000 
Warning message:
In lsfit(X, y, intercept = FALSE) : 'X' matrix was collinear

0 个答案:

没有答案