【问题标题】:How to predict and extract R Squared with .lm.fit?如何使用 .lm.fit 预测和提取 R Squared?
【发布时间】:2023-01-03 15:21:57
【问题描述】:

正如标题所暗示的,我看到一些用户提到.lm.fit() 函数比常规的lm() 具有更快的速度优势,但是当我深入查看帮助中的.lm.fit() 时,它应该是一个更合适的函数,它返回一个列表集代替模型,这让我想到是否仍然可以提取 R 平方、Adj R 平方等组件,最后从中提取 predict()

以下是示例数据和执行:

test_dat <- data.frame(y = rnorm(780, 20, 10))
for(b in 1:300){
  name_var <- paste0("x",b)
  test_dat[[name_var]] <- rnorm(780, 0.01 * b, 5)
}

tic()
obj_lm <- lm(y ~ ., data = test_dat)
print(class(obj_lm))
print(summary(obj_lm)$r.squared)
print(summary(obj_lm)$adj.r.squared)
predict(obj_lm)
toc() #approximately 0.4 seconds

tic()
datm <- as.matrix(test_dat)
obj_lm_fit <- .lm.fit(cbind(1,datm[,-1]), datm[,1])
print(class(obj_lm_fit))
toc() #approximately 0.2 seconds

【问题讨论】:

  • 不是答案,但真实时间对.lm.fit更有利,你也在计时as.matrixcbind

标签: r lm


【解决方案1】:

函数predictresid 是通用的,因为.lm.fit 返回类"list" 的对象,您所要做的就是编写实现您想要的定义的方法。以下是计算拟合值、残差和 R^2 的方法。

set.seed(2023)    # make the results reproducible
test_dat <- data.frame(y = rnorm(780, 20, 10))
for(b in 1:300){
  name_var <- paste0("x",b)
  test_dat[[name_var]] <- rnorm(780, 0.01 * b, 5)
}

obj_lm <- lm(y ~ ., data = test_dat)

datm <- as.matrix(test_dat)
obj_lm_fit <- .lm.fit(cbind(1,datm[,-1]), datm[,1])

#------------------------------------------------------------------------
# the methods for objects of class "list"
#
fitted.list <- function(object, X) {
  X %*% object$coefficients
}
resid.list <- residuals.list <- function(object, X, y) {
  y_fitted <- fitted(object, X)
  y - y_fitted
}
rsquared <- function(x, ...) UseMethod("rsquared")
rsquared.default <- function(x, ...) {
  summary(x)$r.squared
}
rsquared.list <- function(object, X, y) {
  e <- resid.list(object, X, y)
  1 - sum(e^2)/sum( (y - mean(y))^2 )
}

rsquared(obj_lm_fit, cbind(1,datm[,-1]), datm[,1])
#> [1] 0.3948863
rsquared(obj_lm)
#> [1] 0.3948863

创建于 2023-01-03 reprex v2.0.2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-11
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    相关资源
    最近更新 更多