Created
November 15, 2019 09:52
-
-
Save toyeiei/d835bc115c269520880a0fb998f334ce to your computer and use it in GitHub Desktop.
train linear regression in R using kfold method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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