add monotonic constraints to workflow using tidymodels

I am working with tidymodels , so far so good. But sometimes is interesting to add monotonic constraints in the model (forcing to be always increasing, decreasing (1 , -1). This constraint is passed as a vector referring to every column in the dataframe.

Example code (non tidymodel):

# Train the model.
  xgb_model <- xgboost::xgb.train(params =  params,
                                  data=data,
                                  nrounds = num_trees,
                                  print_every_n = 5,
                                  metrics = "auc",
                                  monotone_constraints = c(1,-1,1,-1,1,-1,0,0,0,-1,1)
                                  maximize = F,
                                  tree_method = tree_method,
                                  verbose=verbose
  )

How could I insert this monotonic constraint in tidymodels?

Thanks in advance

As long as you are not doing any filtering of predictors, you should be able to pass the vector as an engine argument:

library(parsnip)
boost_tree() %>% 
  set_mode("regression") %>% 
  set_engine("xgboost", monotone_constraints = c(1,-1,1,-1,1,-1,0,0,0,-1,1)) %>% 
  translate()
#> Boosted Tree Model Specification (regression)
#> 
#> Engine-Specific Arguments:
#>   monotone_constraints = c(1, -1, 1, -1, 1, -1, 0, 0, 0, -1, 1)
#> 
#> Computational engine: xgboost 
#> 
#> Model fit template:
#> parsnip::xgb_train(x = missing_arg(), y = missing_arg(), monotone_constraints = c(1, 
#>     -1, 1, -1, 1, -1, 0, 0, 0, -1, 1), nthread = 1, verbose = 0)

Created on 2022-01-03 by the reprex package (v2.0.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.