Search code examples
broomnnettidymodels

Multinomial (nnet) does not work using parsnip and broom


I'm trying to run a multinomial (nnet) using tidymodel, but it shows me the next result:

Error: object of type 'closure' is not subsettable

data(iris)
ml<-multinom_reg() %>% 
  set_engine("nnet") %>% 
  set_mode("classification") %>% 
  translate()
ml_fit <- ml %>% 
  fit(Species ~ Sepal.Width, data=iris) 
broom::tidy(ml_fit, exponentiate = F)

But when I run ... works perfectly

formula <- Species ~ Sepal.Width
model <- nnet::multinom(formula, data = iris)
broom::tidy(model, exponentiate = F)

Any idea of whether or not I'm writing properly the tidy model or is something else?


Solution

  • In tidymodels, we handle things in a way that the original data and formula are not contained in the resulting call (in the usual way). Some parts of multinom() want those (plus the actual data in the same place) to do the computations.

    We just changed how we handle the formula; that now comes through as it would have if you called multinom() directly. We can't really do the same with data but we did add a new function called repair_call() that you can use to make things they way that you want them.

    # devtools::install_dev("parsnip")
    library(parsnip)
    library(broom)
    multi_spec <- multinom_reg() %>% 
      set_engine("nnet") %>% 
      set_mode("classification")
    multi_fit <- multi_spec %>% 
      fit(Species ~ Sepal.Width, data = iris) 
    tidy(multi_fit)
    #> Error in as.data.frame.default(data, optional = TRUE): cannot coerce class '"function"' to a data.frame
    
    
    multi_fit_new <- repair_call(multi_fit, iris)
    tidy(multi_fit_new)
    #> # A tibble: 4 x 6
    #>   y.level    term        estimate std.error statistic  p.value
    #>   <chr>      <chr>          <dbl>     <dbl>     <dbl>    <dbl>
    #> 1 versicolor (Intercept)  1.55e+8     3.06       6.15 7.54e-10
    #> 2 versicolor Sepal.Width  2.20e-3     0.991     -6.17 6.70e-10
    #> 3 virginica  (Intercept)  4.41e+5     2.69       4.83 1.33e- 6
    #> 4 virginica  Sepal.Width  1.69e-2     0.844     -4.84 1.33e- 6
    

    Created on 2020-05-22 by the reprex package (v0.3.0)