Skip to content

Instantly share code, notes, and snippets.

@ianjohns
Created August 28, 2019 04:27
Show Gist options
  • Save ianjohns/960dd5200520cc61a412f3a6951a3f33 to your computer and use it in GitHub Desktop.
Save ianjohns/960dd5200520cc61a412f3a6951a3f33 to your computer and use it in GitHub Desktop.
R TensorFlow Multiple Linear Regression
library(tfestimators)
library(caret)
#input_fn for a given subset of data
cars_19_input_fn <- function(data, num_epochs = 1) {
input_fn(
data,
features = colnames(cars_19[c(2:12)]),
response = "fuel_economy_combined",
batch_size = 64,
num_epochs = num_epochs
)
}
cols <- feature_columns(
column_numeric(colnames(cars_19[c(2, 3, 5, 8)])),
column_categorical_with_identity("transmission", num_buckets = 7),
column_categorical_with_identity("air_aspired_method", num_buckets = 5),
column_categorical_with_identity("regen_brake", num_buckets = 3),
column_categorical_with_identity("drive", num_buckets = 5),
column_categorical_with_identity("fuel_type", num_buckets = 5),
column_categorical_with_identity("cyl_deactivate", num_buckets = 2),
column_categorical_with_identity("variable_valve", num_buckets = 2)
)
model <- linear_regressor(feature_columns = cols)
set.seed(123)
indices <- sample(1:nrow(cars_19), size = 0.75 * nrow(cars_19))
train <- cars_19[indices, ]
test <- cars_19[-indices, ]
#train model
model %>% train(cars_19_input_fn(train, num_epochs = 1000))
#evaluate model
model %>% evaluate(cars_19_input_fn(test))
#predict
yhat <- model %>% predict(cars_19_input_fn(test))
yhat <- unlist(yhat)
y <- test$fuel_economy_combined
postResample(yhat, y)
r <- y - yhat
plot(y, yhat, xlab = "actual", ylab = "predicted", main = "Multiple Linear Regression")
abline(lm(yhat ~ y))
plot(r)
#RMSE Rsquared MAE
#2.5583185 0.7891934 1.9381757
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment