Created
December 26, 2018 01:54
-
-
Save alexhallam/f3f7c63e48cf341c546bfcf6a16163c9 to your computer and use it in GitHub Desktop.
A way to clean a glmnet object
This file contains hidden or 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
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