Created
May 7, 2019 02:20
-
-
Save toyeiei/0b897a4ba12411dce4fdaea945d823ae to your computer and use it in GitHub Desktop.
function to train linear regression
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
## this function takes four inputs | |
## formula such as "mpg ~ wt + hp" (character) | |
## dataset | |
## train_size ratio between 0-1 (numeric) | |
## target such as "mpg" (character) | |
LinearRegression <- function(formula, data, train_size, target){ | |
## split dataset into train and test | |
set.seed(99) | |
n <- nrow(data) | |
id <- sample(1:n, size = train_size*n, replace = FALSE) | |
train_df <- data[id, ] | |
test_df <- data[-id, ] | |
## train model | |
train_form <- as.formula(formula) | |
lm_model <- lm(train_form, data = train_df) | |
## predictions | |
train_p <- predict(lm_model) | |
test_p <- predict(lm_model, newdata = test_df) | |
## evaluate and print result | |
train_mae <- mean(abs(train_p - train_df[[target]])) | |
test_mae <- mean(abs(test_p - test_df[[target]])) | |
cat("Train MAE:", train_mae) | |
cat("\nTest MAE:", test_mae) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment