Skip to content

Instantly share code, notes, and snippets.

@toyeiei
Created November 15, 2019 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toyeiei/d835bc115c269520880a0fb998f334ce to your computer and use it in GitHub Desktop.
Save toyeiei/d835bc115c269520880a0fb998f334ce to your computer and use it in GitHub Desktop.
train linear regression in R using kfold method
## R version 3.6.1
## Created by DataRockie 15 November 2019
## load library
library(caret)
library(mlbench)
library(dplyr)
## load dataset
data("BostonHousing")
## tibble dataframe
BostonHousing <- as.tbl(BostonHousing)
## create folds
(folds <- createFolds(BostonHousing$medv, k=5, list=T))
## train linear regression
kfoldLM <- function(data, k) {
folds <- createFolds(BostonHousing$medv, k=k, list=T)
result <- vector()
for(fold in folds) {
trainData <- data[-fold, ]
testData <- data[fold, ]
r2 <- summary(lm(trainData))$r.squared
result <- append(result, r2)
}
cat("Average R2:", round(mean(result),4) )
cat("\nStandard Deviation R2:", round(sd(result),4) )
}
## test function with k=5
kfoldLM(data = BostonHousing, k = 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment