我遇到的情况是我的秩X矩阵不足,但仍需要回归系数。具体来说,我想要由base::qr
require(Matrix)
y <- c(230, 192, 195, 180, 200, 185, 0)
X <- new("dgCMatrix", i = c(0L, 1L, 2L, 3L, 4L, 5L, 6L, 0L, 1L, 2L,
3L, 4L, 5L, 1L, 3L, 5L, 2L, 3L, 4L, 5L, 1L, 0L), p = c(0L, 7L,
13L, 16L, 20L, 20L, 21L, 22L), Dim = c(7L, 7L), Dimnames = list(
c("419", "420", "421", "422", "423", "424", ""), c("", "(Intercept)",
"A", "B1", "B2", "B3", "B4")), x = c(0.451764131343143,
0.434020584428936, 0.451764131343143, 0.434020584428936, 0.451764131343143,
0.451764131343143, 0.788669766125214, 0.788669766125214, 0.757693869580585,
0.788669766125214, 0.757693869580585, 0.788669766125214, 0.788669766125214,
0.757693869580585, 0.757693869580585, 0.788669766125214, 0.788669766125214,
0.757693869580585, 0.788669766125214, 0.788669766125214, 0.757693869580585,
0.788669766125214), factors = list())
qrB <- base::qr(X)
qrM <- Matrix::qr(X)
qr.coef(qrB, y)
# (Intercept) A B1 B2 B3 B4
# -8.438370e-14 2.916303e+02 -1.441398e+01 -4.120863e+01 NA -2.381583e+01 NA
qr.coef(qrM, y)
# [1] -9.730332e-01 -1.314143e+16 -1.597833e+01 1.314143e+16 0.000000e+00 1.314143e+16 1.314143e+16
# Warning message:
# In lengths(res@Dimnames) :
# sparseQR_coef(): structurally rank deficient case: possibly WRONG zeros
因此,两个人都认识到他们无法估计B2并估计NA NA(base
)或零(Matrix
),我对这两个结果都很好。但是,base::qr
还认识到它需要删除第二列并选择最后一列(尚不清楚原因,但它确实可行),而Matrix::qr
大胆地伪造并估计与.Machine$double.eps
。
在这种情况下,Matrix的稳定性也较差(请原谅,我忘记了哪种类型),因为平方和比底数要小
coef <- qr.coef(qrB, y)
coef[is.na(coef)] <- 0
sum((X %*% coef - y)^2)
# [1] 15.17039
sum((X %*% qr.coef(qrM, y) - y)^2)
# [1] 18.58891
是否有一种方法可以使Matrix::qr
这样的超快速方法像base::qr
那样工作,并给出快速但稳定的结果?我意识到这并不是一个“大矩阵”,部分原因是它是MWE。
Ben Bolker的答案here和两个答案here讨论了Lapack和Linpack之间的区别,但是这些方法在base::qr
中。我正在寻找一种方法,以从Matrix::qr
获得修改后的结果,从而给出可以使用的系数。