Skip to content

Instantly share code, notes, and snippets.

@topepo
Created November 5, 2025 19:29
Show Gist options
  • Save topepo/0d6f7b24284117d4e09015ddbfa33049 to your computer and use it in GitHub Desktop.
Save topepo/0d6f7b24284117d4e09015ddbfa33049 to your computer and use it in GitHub Desktop.
Avoid estimation for a model in tidymodels
library(tidymodels)
actual_fit <- glm(mpg ~ ., data = mtcars)
not_fit <- glm(
mpg ~ .,
data = mtcars,
start = coef(actual_fit),
control = glm.control(maxit = 1, trace = TRUE)
)
# Can also trick tidymodels if we can initialize a model known to
no_parsnip_fit <-
linear_reg() |>
set_engine(
"glm",
start = coef(actual_fit),
control = glm.control(maxit = 1)
) |>
fit(mpg ~ ., data = mtcars)
waldo::compare(
coef(actual_fit),
no_parsnip_fit |> extract_fit_engine() |> coef()
)
@mattansb
Copy link

mattansb commented Nov 6, 2025

This doesn't seem to work if using other (non-estimated) coefficients:

library(tidymodels)

fixed_coef <- c("(Intercept)" = 30, cyl = -1.5, disp = -0.02)

not_fit <- glm(
  mpg ~ cyl + disp,
  data = mtcars,
  start = fixed_coef,
  control = glm.control(maxit = 1, trace = TRUE)
)
#> Deviance = 270.7403 Iterations - 1
#> Warning: glm.fit: algorithm did not converge

# Can also trick tidymodels if we can initialize a model known to
no_parsnip_fit <-
  linear_reg() |>
  set_engine(
    "glm",
    start = fixed_coef,
    control = glm.control(maxit = 1)
  ) |>
  fit(mpg ~ cyl + disp, data = mtcars)
#> Warning: glm.fit: algorithm did not converge

waldo::compare(
  fixed_coef,
  not_fit |> coef()
)
#> `old`: 30.00000 -1.50000 -0.02000
#> `new`: 34.66099 -1.58728 -0.02058

waldo::compare(
  fixed_coef,
  no_parsnip_fit |> extract_fit_engine() |> coef()
)
#> `old`: 30.00000 -1.50000 -0.02000
#> `new`: 34.66099 -1.58728 -0.02058

Created on 2025-11-06 with reprex v2.1.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment