Skip to content

Instantly share code, notes, and snippets.

@alexhallam
Created December 26, 2018 01:54
Show Gist options
  • Save alexhallam/f3f7c63e48cf341c546bfcf6a16163c9 to your computer and use it in GitHub Desktop.
Save alexhallam/f3f7c63e48cf341c546bfcf6a16163c9 to your computer and use it in GitHub Desktop.
A way to clean a glmnet object
library(tidyverse)
library(tidymodels)
Sacramento %>% str()
y <- Sacramento %>% select(price) %>% as.matrix()
x <- Sacramento %>% as.matrix() %>% scale()
fit <- glmnet::glmnet(x, y, lambda = 4192.847)
str(fit)
tidy_glmnet <- function(fit){
lasso_coeffs <- tibble(index = seq(1:fit$dim[1]) - 1, terms = row.names(fit$beta)) %>%
full_join(tibble(index = fit$beta@i, estimates = fit$beta@x), by = "index") %>%
mutate(estimates = ifelse(is.na(estimates), 0, estimates)) %>%
mutate(index = index + 1) %>%
rbind(c(0,"(Intercept)",fit$a0)) %>%
arrange(index) %>%
mutate(lambda = fit$lambda, log_lambda = log(fit$lambda), df = fit$df) %>%
mutate(estimates = as.numeric(estimates))
lasso_coeffs
}
tidy_glmnet(fit)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment