大矩阵线性回归

时间:2018-09-11 09:20:42

标签: r r-bigmemory

我想对大矩阵进行线性回归。

这是我到目前为止尝试过的:

library(bigmemory)
library(biganalytics)
library(bigalgebra)

nrows <- 1000000
X <- as.big.matrix( replicate(100, rnorm(nrows)) )
y <- rnorm(nrows)

biglm.big.matrix(y ~ X)
# Error in CreateNextDataFrameGenerator(formula, data, chunksize, fc, getNextChunkFunc,  : 
  argument "data" is missing, with no default

biglm.big.matrix(y ~ X, data = cbind(y, X))
# Error in bigmemory:::mmap(vars, colnames(data)) : 
  Couldn't find a match to one of the arguments.

biglm.big.matrix(y ~ X, data = cbind(y = y, X = X))
# Error in bigmemory:::mmap(vars, colnames(data)) : 
  Couldn't find a match to one of the arguments.

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

在这里,X是一个100列的(大)矩阵。由于biglm.big.matrix()需要使用data=参数,因此您似乎无法像使用X一样要求该函数立即在lm()中的所有列上运行线性模型。还要注意,当您将cbind()big.matrix一起使用时,如cbind(y, X)那样,结果是list !!

似乎您需要同时yX才能成为big.matrix的一部分,然后您需要手动构建模型公式:

library(bigmemory)
library(biganalytics)
library(bigalgebra)

# Construct an empty big.matrix with the correct number of dimensions and
# with column names
nrows <- 1000000
dat <- big.matrix(nrow=nrows, ncol=101, 
                  dimnames=list(
                    NULL, # no rownames
                    c("y", paste0("X", 1:ncol(X))) # colnames: y, X1, X2, ..., X100
                  ))

# fill with y and X:
dat[,1] <- rnorm(nrows)
dat[,2:101] <- replicate(100, rnorm(nrows)) 

# construct the model formula as a character vector using paste:
# (Or you need to type y ~ X1 + X2 + ... + X100 manually in biglm.big.matrix()!)
f <- paste("y ~", paste(colnames(dat)[-1], collapse=" + "))

# run the model
res <- biglm.big.matrix(as.formula(f), data=dat)
summary(res)

答案 1 :(得分:0)

您可以轻松地使用package {bigstatsr}来实现这一点(免责声明:我是作者)。

真实值

nrows <- 1000000
X <- replicate(100, rnorm(nrows))
y <- rnorm(nrows)
system.time(
  true <- lm(y ~ X)
) # 11.3 sec

使用{bigstatsr}

library(bigstatsr)
system.time({
  X2 <- as_FBM(X)
  X2$add_columns(1)
  X2[, ncol(X2)] <- 1

  inv_XtX <- solve(big_crossprodSelf(X2)[])
  Xty <- big_cprodVec(X2, y)
  betas <- inv_XtX %*% Xty
  RSS <- drop(crossprod(y - big_prodVec(X2, betas)))
  df <- nrow(X2) - ncol(X2)
  std_err <- sqrt(RSS * diag(inv_XtX) / df)
}) # 1.6 sec

验证

head(summary(true)$coefficients)
# Intercept at the end
head(betas)  ## Estimate
head(std_err)
head(t_stat <- betas / std_err) ## t value
head(pval <- 2 * pt(abs(t_stat), df = df, lower.tail = FALSE))