# Troubleshooting models that fail

In this vignette, we illustrate how to troubleshoot tuning errors. This is not a comprehensive list (yet), but rather an attempt to illustrate how an error can be approached.

# NAs in the data

Most algorithms do not allow NAs. We can generate a problematic dataset by loading the Lacerta dataset, and manually add an NA:

    library(tidysdm)
    lacerta_thin <- readRDS(system.file("extdata/lacerta_thin_all_vars.rds",
      package = "tidysdm"
    ))
    lacerta_thin$bio05[37] <- NA

Let us set up a recipe and fit workflow_set

    lacerta_rec <- recipe(lacerta_thin, formula = class ~ .) %>%
      step_rm(all_of(c(
        "bio01", "bio02", "bio03", "bio04", "bio07", "bio08",
        "bio09", "bio10", "bio11", "bio12", "bio14", "bio16",
        "bio17", "bio18", "bio19", "altitude"
      )))

    lacerta_models <-
      # create the workflow_set
      workflow_set(
        preproc = list(default = lacerta_rec),
        models = list(
          # the standard glm specs
          glm = sdm_spec_glm(),
          # rf specs with tuning
          rf = sdm_spec_rf()
        ),
        # make all combinations of preproc and models,
        cross = TRUE
      ) %>%
      # tweak controls to store information needed later to create the ensemble
      option_add(control = control_ensemble_grid())

    set.seed(100)
    lacerta_cv <- spatial_block_cv(lacerta_thin, v = 5)
    lacerta_models <-
      lacerta_models %>%
      workflow_map("tune_grid",
        resamples = lacerta_cv, grid = 3,
        metrics = sdm_metric_set(), verbose = TRUE
      )
    #> i    No tuning parameters. `fit_resamples()` will be attempted
    #> i 1 of 2 resampling: default_glm
    #> ✔ 1 of 2 resampling: default_glm (136ms)
    #> i 2 of 2 tuning:     default_rf
    #> i Creating pre-processing data to finalize unknown parameter: mtry
    #> ✔ 2 of 2 tuning:     default_rf (1s)

We can see that the error is self-explanatory. Also, note that the error impacts all data splits (technically, `rset` objects): error A is repeated 15 times (5 splits for 3 hyperparameter values).

Prepping the recipe (which trains it on the dataset) can help diagnosing problems:

    lacerta_prep <- lacerta_rec %>% prep(lacerta_thin)
    lacerta_prep
    #>
    #> ── Recipe ──────────────────────────────────────────────────────────────────────
    #>
    #> ── Inputs
    #> Number of variables by role
    #> outcome:    1
    #> predictor: 20
    #> coords:     2
    #>
    #> ── Training information
    #> Training data contained 448 data points and 1 incomplete row.
    #>
    #> ── Operations
    #> • Variables removed: bio01, bio02, bio03, bio04, bio07, bio08, ... | Trained

Note that, in the training information, we were warned that 1 row was incomplete. You could use `step_naomit` to deal with this programmatically, or ascertain why you are generating missing data (we prefer the latter, as a good SDM pipeline should not generate observations, presences or pseudoabsences, with missing data).

# Recipes and the response variable

The response variable is treated in a special way in `recipes`, and this can lead to problems. It is best not to manipulate (e.g. transform character into factor) the response variable in a recipe, since that response variable will only be available when we train and test models, but not when we make projections. If we hard-coded a step in a recipe that includes the response variable, the model will fit, but then it will fail when we start making predictions.

Another potential mistake is to remove the response variable when selecting variables of interest. This can happen if we use `step_select` to choose variables of interest, and the error is less than clear:

Let’s load the data and create a recipe with `step_select`:

    lacerta_thin <- readRDS(system.file("extdata/lacerta_thin_all_vars.rds",
      package = "tidysdm"
    ))
    suggested_vars <- c("bio05", "bio06", "bio13", "bio14", "bio15")
    lacerta_rec_sel <- recipe(lacerta_thin, formula = class ~ .) %>%
      step_select(all_of(suggested_vars))

Now we create the workflow set and fit it:

    lacerta_models <-
      # create the workflow_set
      workflow_set(
        preproc = list(default = lacerta_rec_sel),
        models = list(
          # the standard glm specs
          glm = sdm_spec_glm(),
          # rf specs with tuning
          rf = sdm_spec_rf()
        ),
        # make all combinations of preproc and models,
        cross = TRUE
      ) %>%
      # tweak controls to store information needed later to create the ensemble
      option_add(control = control_ensemble_grid())

    set.seed(100)
    lacerta_cv <- spatial_block_cv(lacerta_thin, v = 5)
    lacerta_models <-
      lacerta_models %>%
      workflow_map("tune_grid",
        resamples = lacerta_cv, grid = 3,
        metrics = sdm_metric_set(), verbose = TRUE
      )
    #> i    No tuning parameters. `fit_resamples()` will be attempted
    #> i 1 of 2 resampling: default_glm
    #> → A | error:   ! `logistic_reg()` was unable to find an outcome.
    #>                ℹ Ensure that you have specified an outcome column and that it hasn't been
    #>                  removed in pre-processing.
    #> There were issues with some computations   A: x1
    #> There were issues with some computations   A: x5
    #>
    #> Warning: All models failed. Run `show_notes(.Last.tune.result)` for more
    #> information.
    #> Warning: Unknown or uninitialised column: `.notes`.
    #> ✖ 1 of 2 resampling: default_glm failed with
    #> i 2 of 2 tuning:     default_rf
    #> i Creating pre-processing data to finalize unknown parameter: mtry
    #> → A | error:   ! `rand_forest()` was unable to find an outcome.
    #>                ℹ Ensure that you have specified an outcome column and that it hasn't been
    #>                  removed in pre-processing.
    #> Warning: All models failed. Run `show_notes(.Last.tune.result)` for more information.
    #> Unknown or uninitialised column: `.notes`.
    #> ✖ 2 of 2 tuning:     default_rf failed with

The errors are not very intuitive. However, all models have failed for all algorithms, which suggests that the problem lies with the data preparation side (either the data themselves, or what we did with the recipe).

Ideally, you should have already had a look at your data (with `summary` or `glimpse`). So, in this case, we know that the data are fine. Whilst prepping (and sometimes baking) the recipe is generally informative for predictor variables, it is hard to diagnose problems with the outcome variable in a recipe. Prepping will not show anything obvious:

    lacerta_prep_sel <- lacerta_rec_sel %>% prep(lacerta_thin)
    lacerta_prep_sel
    #>
    #> ── Recipe ──────────────────────────────────────────────────────────────────────
    #>
    #> ── Inputs
    #> Number of variables by role
    #> outcome:    1
    #> predictor: 20
    #> coords:     2
    #>
    #> ── Training information
    #> Training data contained 448 data points and no incomplete rows.
    #>
    #> ── Operations
    #> • Variables selected: bio05, bio06, bio13, bio14, bio15 | Trained

In this case, it is a process of exclusion. Everything seems fine, but the models don’t work. Then ask yourself if the outcome variable might be problematic. As a general rule, we have found it easier to rely on `step_rm` to remove variables (e.g. correlated variables).

# Using the desired formula with GAM

General Additive Models have an unusual syntax, as the user has to define which variables are fitted with splines. `tidysdm` has some functions to simplify this process, assuming that the user just wants to fit a standard smooth to every continuous predictor.

    lacerta_thin <- readRDS(system.file("extdata/lacerta_thin_all_vars.rds",
      package = "tidysdm"
    ))

    lacerta_rec <- recipe(lacerta_thin, formula = class ~ .) %>%
      step_rm(all_of(c(
        "bio01", "bio02", "bio03", "bio04", "bio07", "bio08",
        "bio09", "bio10", "bio11", "bio12", "bio14", "bio16",
        "bio17", "bio18", "bio19", "altitude"
      )))

    lacerta_models <-
      # create the workflow_set
      workflow_set(
        preproc = list(default = lacerta_rec),
        models = list(
          # the standard glm specs
          glm = sdm_spec_glm(),
          # the standard gam specs
          gam = sdm_spec_gam()
        ),
        # make all combinations of preproc and models,
        cross = TRUE
      ) %>%
      # set formula for gams
      update_workflow_model("default_gam",
        spec = sdm_spec_gam(),
        formula = gam_formula(lacerta_rec)
      ) %>%
      # tweak controls to store information needed later to create the ensemble
      option_add(control = control_ensemble_grid())

    set.seed(100)
    lacerta_cv <- spatial_block_cv(lacerta_thin, v = 5)
    lacerta_models <-
      lacerta_models %>%
      workflow_map("tune_grid",
        resamples = lacerta_cv, grid = 3,
        metrics = sdm_metric_set(), verbose = TRUE
      )
    #> i    No tuning parameters. `fit_resamples()` will be attempted
    #> i 1 of 2 resampling: default_glm
    #> ✔ 1 of 2 resampling: default_glm (132ms)
    #> i    No tuning parameters. `fit_resamples()` will be attempted
    #> i 2 of 2 resampling: default_gam
    #> ✔ 2 of 2 resampling: default_gam (349ms)

Note that the step of defining a formula is incompatible with using `step_cor` in a recipe. `step_cor` removes correlated variables in recipes, using a similar algorithm to `filter_collinear` using method `cor_caret`. However, the algorithm is fitted to each data split when cross-validating. This means that different variables will eventually be presented to the model when it is fitted for each split, leading to an error as there will be a mismatch between the formula and the available variables. This is a known issue of how GAMs are implemented in `tidymodels`.

# When only some splits fail

In the examples above, all the splits used for cross-validation of a given algorithms failed. However, it is also possible that failures occur only on some splits for certain algorithms (technically, a specific `rsplit` within certain `workflows`). When this type of problem occurs, it is best to extract the problematic workflow, and potentially investigate fitting it to the specific `rsplit`.

We generate a problematic dataset by subsampling the lacerta dataset:

    lacerta_thin <- readRDS(system.file("extdata/lacerta_thin_all_vars.rds",
      package = "tidysdm"
    ))
    set.seed(123)
    lacerta_thin <- lacerta_thin[sample(
      seq_len(nrow(lacerta_thin)),
      nrow(lacerta_thin) / 5
    ), ]

    lacerta_rec <- recipe(lacerta_thin, formula = class ~ .) %>%
      step_rm(all_of(c(
        "bio01", "bio02", "bio03", "bio04", "bio07", "bio08",
        "bio09", "bio10", "bio11", "bio12", "bio14", "bio16",
        "bio17", "bio18", "bio19", "altitude"
      )))

    lacerta_models <-
      # create the workflow_set
      workflow_set(
        preproc = list(default = lacerta_rec),
        models = list(
          # the standard glm specs
          glm = sdm_spec_glm(),
          # the standard gam specs
          gam = sdm_spec_gam(),
          # rf specs with tuning
          rf = sdm_spec_rf()
        ),
        # make all combinations of preproc and models,
        cross = TRUE
      ) %>%
      # set formula for gams
      update_workflow_model("default_gam",
        spec = sdm_spec_gam(),
        formula = gam_formula(lacerta_rec)
      ) %>%
      # tweak controls to store information needed later to create the ensemble
      option_add(control = control_ensemble_grid())

We then create 3 folds and attempt to fit the models:

    set.seed(100)
    lacerta_cv <- spatial_block_cv(lacerta_thin, v = 3)
    lacerta_models <-
      lacerta_models %>%
      workflow_map("tune_grid",
        resamples = lacerta_cv, grid = 3,
        metrics = sdm_metric_set(), verbose = TRUE
      )
    #> i    No tuning parameters. `fit_resamples()` will be attempted
    #> i 1 of 3 resampling: default_glm
    #> ✔ 1 of 3 resampling: default_glm (90ms)
    #> i    No tuning parameters. `fit_resamples()` will be attempted
    #> i 2 of 3 resampling: default_gam
    #> ✔ 2 of 3 resampling: default_gam (323ms)
    #> i 3 of 3 tuning:     default_rf
    #> i Creating pre-processing data to finalize unknown parameter: mtry
    #> ✔ 3 of 3 tuning:     default_rf (272ms)

We see that one of the folds gives us an error when using GAMs. The error (“Fitting terminated with step failure - check results carefully”) comes from the gam function in the package `mgcv`. A quick google on StackOverflow[https://stats.stackexchange.com/questions/576273/gam-model-warning-message-step-failure-in-theta-estimation] gives us an idea of where this error comes from.

We start by extracting the results of the gam fits:

    gam_results <- extract_workflow_set_result(lacerta_models, id = "default_gam")
    gam_results
    #> # Resampling results
    #> # 3-fold spatial block cross-validation
    #> # A tibble: 3 × 5
    #>   splits          id    .metrics         .notes           .predictions
    #>   <list>          <chr> <list>           <list>           <list>
    #> 1 <split [57/32]> Fold1 <tibble [3 × 4]> <tibble [0 × 3]> <tibble [32 × 5]>
    #> 2 <split [53/36]> Fold2 <tibble [3 × 4]> <tibble [0 × 3]> <tibble [36 × 5]>
    #> 3 <split [68/21]> Fold3 <tibble [3 × 4]> <tibble [0 × 3]> <tibble [21 × 5]>

We see that, in the `.notes` column, the second item is not empty (it does not have zero rows). We can check that it indeed contains the error that we wanted:

    gam_results$.notes[2]
    #> [[1]]
    #> # A tibble: 0 × 3
    #> # ℹ 3 variables: location <chr>, type <chr>, note <chr>

We can now get the problematic data split, and extract the training data:

    problem_split <- gam_results$splits[2][[1]]
    summary(training(problem_split))
    #>         class             geometry      bio01            bio02
    #>  presence  :15   POINT        :53   Min.   : 3.852   Min.   : 7.111
    #>  background:38   epsg:NA      : 0   1st Qu.:12.058   1st Qu.: 8.990
    #>                  +proj=aea ...: 0   Median :13.846   Median :10.037
    #>                                     Mean   :13.340   Mean   :10.027
    #>                                     3rd Qu.:15.911   3rd Qu.:10.693
    #>                                     Max.   :18.194   Max.   :13.309
    #>      bio03           bio04           bio05           bio06
    #>  Min.   :32.96   Min.   :328.5   Min.   :20.40   Min.   :-7.35194
    #>  1st Qu.:37.73   1st Qu.:463.6   1st Qu.:24.17   1st Qu.: 0.02899
    #>  Median :39.73   Median :565.6   Median :27.24   Median : 3.24637
    #>  Mean   :40.31   Mean   :541.0   Mean   :27.58   Mean   : 2.53016
    #>  3rd Qu.:43.04   3rd Qu.:621.7   3rd Qu.:30.74   3rd Qu.: 5.02963
    #>  Max.   :46.16   Max.   :721.1   Max.   :34.80   Max.   : 7.35438
    #>      bio07           bio08            bio09            bio10
    #>  Min.   :16.33   Min.   :-2.000   Min.   : 5.432   Min.   :12.29
    #>  1st Qu.:21.80   1st Qu.: 8.173   1st Qu.:17.646   1st Qu.:18.35
    #>  Median :25.99   Median :10.099   Median :19.799   Median :20.57
    #>  Mean   :25.05   Mean   :10.232   Mean   :19.396   Mean   :20.38
    #>  3rd Qu.:27.75   3rd Qu.:12.354   3rd Qu.:22.679   3rd Qu.:22.89
    #>  Max.   :32.79   Max.   :17.571   Max.   :25.189   Max.   :25.44
    #>      bio11            bio12            bio13            bio14
    #>  Min.   :-3.213   Min.   : 284.9   Min.   : 43.00   Min.   : 1.00
    #>  1st Qu.: 5.283   1st Qu.: 563.6   1st Qu.: 76.04   1st Qu.: 5.90
    #>  Median : 8.226   Median : 711.5   Median :101.60   Median :20.31
    #>  Mean   : 7.223   Mean   : 816.5   Mean   :109.89   Mean   :22.86
    #>  3rd Qu.: 9.734   3rd Qu.:1060.2   3rd Qu.:137.29   3rd Qu.:36.00
    #>  Max.   :11.853   Max.   :1635.6   Max.   :227.81   Max.   :66.92
    #>      bio15           bio16           bio17            bio18
    #>  Min.   :16.81   Min.   :106.0   Min.   : 15.77   Min.   : 22.52
    #>  1st Qu.:30.08   1st Qu.:203.6   1st Qu.: 38.17   1st Qu.: 42.01
    #>  Median :42.82   Median :278.6   Median : 84.75   Median : 90.28
    #>  Mean   :42.93   Mean   :302.4   Mean   : 94.49   Mean   :104.30
    #>  3rd Qu.:54.96   3rd Qu.:388.6   3rd Qu.:144.16   3rd Qu.:156.29
    #>  Max.   :76.74   Max.   :635.7   Max.   :231.83   Max.   :231.83
    #>      bio19           altitude
    #>  Min.   : 77.48   Min.   :  67.29
    #>  1st Qu.:174.77   1st Qu.: 167.05
    #>  Median :253.72   Median : 402.55
    #>  Mean   :274.80   Mean   : 554.89
    #>  3rd Qu.:361.03   3rd Qu.: 754.81
    #>  Max.   :634.26   Max.   :2056.80

In this case, there is nothing too obvious that leads to the error (an important check is to make sure that you have enough presences in a split; too few presences will generally lead to errors).

We can now extract the workflow and refit it to the split to confirm that we have isolated the problem:

    gam_workflow <- extract_workflow(lacerta_models, id = "default_gam")
    faulty_gam <- fit(gam_workflow, training(problem_split))

The next step would be to dig deeper into the data, trying to understand whether there are some outliers that are problematic. The specific steps will depend on the algorithm that is giving problems.