gpt4 book ai didi

r - 是否有一个简单的命令可以使用 lm() 函数进行留一法交叉验证?

转载 作者:行者123 更新时间:2023-12-04 12:36:06 24 4
gpt4 key购买 nike

是否有一个简单的命令可以使用 lm() 进行留一法交叉验证? R中的函数?

具体来说,下面的代码是否有一个简单的命令?

x <- rnorm(1000,3,2)
y <- 2*x + rnorm(1000)

pred_error_sq <- c(0)
for(i in 1:1000) {
x_i <- x[-i]
y_i <- y[-i]
mdl <- lm(y_i ~ x_i) # leave i'th observation out
y_pred <- predict(mdl, data.frame(x_i = x[i])) # predict i'th observation
pred_error_sq <- pred_error_sq + (y[i] - y_pred)^2 # cumulate squared prediction errors
}

y_squared <- sum((y-mean(y))^2)/100 # Variation of the data

R_squared <- 1 - (pred_error_sq/y_squared) # Measure for goodness of fit

最佳答案

另一种解决方案是使用 caret

library(caret)

data <- data.frame(x = rnorm(1000, 3, 2), y = 2*x + rnorm(1000))

train(y ~ x, method = "lm", data = data, trControl = trainControl(method = "LOOCV"))

Linear Regression

1000 samples 1 predictor

No pre-processing Resampling: Leave-One-Out Cross-Validation Summary of sample sizes: 999, 999, 999, 999, 999, 999, ... Resampling results:

RMSE Rsquared MAE
1.050268 0.940619 0.836808

Tuning parameter 'intercept' was held constant at a value of TRUE

关于r - 是否有一个简单的命令可以使用 lm() 函数进行留一法交叉验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47031556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com