---
title: "Model selection in practice"
output:
  rmarkdown::html_vignette:
    df_print: kable
vignette: >
  %\VignetteIndexEntry{Model selection in practice}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown}
editor_options:
  markdown:
    wrap: 80
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 7,
  fig.align = "center"
)
```

```{r setup}
library(mixvlmc)
library(ggplot2)
```

The complexity of a Variable Length Markov Chain (VLMC) or of a VLMC with
covariates (COVLMC) is controlled mainly by a cut off parameter: a large
model is first built and then pruned, removing the contexts that do not
change significantly the conditional distribution of the next state. The
introductory vignettes, `vignette("variable-length-markov-chains")` and
`vignette("covlmc")`, present the estimation algorithms and the basic use of
the automatic model selection functions `tune_vlmc()` and `tune_covlmc()`,
while `vignette("likelihood")` discusses the likelihood functions on which
information criteria are based. This vignette is a practical guide that
goes further: it explains how the automatic selection works, how to read
its results, how to obtain other models than the selected one and how to
implement other selection strategies, such as hold-out validation.

## Running example

We use the household electricity consumption data set included in the
package (`powerconsumption`, one observation every 10 minutes). We keep three
weeks of data and turn the active power into a binary time series: the
consumption is `low` below 0.4 kW (typically at night or when nobody is at
home) and `high` above.

```{r}
pc <- powerconsumption[powerconsumption$week %in% 15:17, ]
elec <- cut(pc$active_power,
  breaks = c(0, 0.4, 8),
  labels = c("low", "high")
)
table(elec)
```

The first two weeks are used to estimate the models and the third one is
kept for hold-out validation (see below).

```{r}
n_train <- sum(pc$week %in% 15:16)
elec_train <- elec[1:n_train]
```

## Automatic selection with `tune_vlmc()`

### Principle

`tune_vlmc()` implements the following procedure:

1. it fits a large VLMC with `vlmc()`, using a conservative (small) cut off,
   so that the context tree is limited essentially by the `min_size`
   parameter;
2. it computes with `cutoff()` all the cut off values that lead to a
   different (simpler) model;
3. it prunes the model successively with `prune()` using those values, until
   the memoryless model (a single context) is reached;
4. it evaluates an information criterion (BIC or AIC) for each model and
   returns the model that minimises it. In case of a tie, the simplest
   model is preferred.

As pruning a VLMC with a given cut off gives the model that `vlmc()` would
build directly with this cut off (up to numerical instabilities), this
procedure explores *all* the models that can be obtained from the time series
with cut off values larger than the initial one, and does so far more
efficiently than repeated calls to `vlmc()`.

```{r}
elec_tune <- tune_vlmc(elec_train)
elec_tune
```

The selected model can be extracted with `as_vlmc()` (or as the
`best_model` component of the result).

```{r}
elec_vlmc <- as_vlmc(elec_tune)
draw(elec_vlmc)
```

### Main parameters

The behaviour of `tune_vlmc()` is controlled by the following parameters:

-   `criterion`: the information criterion to minimise, `"BIC"` (default) or
    `"AIC"`. The BIC is consistent and generally leads to simpler models,
    while the AIC can be preferred for prediction or simulation oriented
    uses of the model;
-   `initial`: the likelihood function used to compute the criterion,
    `"truncated"` (default), `"specific"` or `"extended"` (see the section
    on likelihood functions below);
-   `alpha_init` and `cutoff_init`: the cut off used to build the initial
    model, in quantile and native scale respectively (`cutoff_init` takes
    precedence). The default value, in native scale, is $\frac{1}{4}\log n$
    for the BIC (with $n$ the length of the time series) and 1 for the AIC.
    The models considered are all simpler than this initial model. If the
    selected model is the initial one (the first row of the results
    described below), a more permissive (smaller) cut off should be used;
-   `min_size`: the minimal number of occurrences of a context in the time
    series to be included in the initial context tree (default: 2);
-   `max_depth`: the initial maximal length of the contexts (default: 100).
    This parameter is *not* a complexity control parameter: when the initial
    context tree reaches `max_depth`, the value is doubled and the model is
    fitted again, until the depth of the tree is limited only by `min_size`. A
    small value gives therefore the same results as the default one;
-   `backend`: the implementation of the context tree, `"R"` or `"C++"`
    (default: the value of the `mixvlmc.backend` option, that is `"C++"`
    unless it has been changed). Both backends give the same results, but the
    C++ one is faster on long time series. As it builds the complete suffix
    tree of the time series, the maximal depth is directly set to its largest
    possible value;
-   `verbose`: when larger than 0, the progress of the selection (increases
    of `max_depth`, pruning steps and improvements of the criterion) is
    reported with `message()`;
-   `save`: which models are kept in the result, see the section on getting
    other models below.

For instance, the R backend with a very small initial `max_depth` gives the
same results as the C++ backend used above:

```{r}
elec_tune_r <- tune_vlmc(elec_train, max_depth = 4, backend = "R")
all.equal(elec_tune$results, elec_tune_r$results)
```

### Reading the results

Printing the result of `tune_vlmc()` shows the selected model, the value of
the criterion and of the log likelihood, as above. `summary()` adds the
characteristics of all the models considered during the selection:

```{r}
summary(elec_tune)
```

Those characteristics are stored in the `results` data frame, which has
one row per model, from the initial (most complex) model to the memoryless
model. Its columns are:

-   `cutoff` and `alpha`: the cut off used to build the model (by `vlmc()`
    for the first row and by `prune()` for the other ones) in native and
    quantile scale respectively;
-   `depth` and `nb_contexts`: the length of the longest context and the
    number of contexts of the model;
-   `loglikelihood`, `AIC` and `BIC`: the log likelihood of the model and
    the associated information criteria.

```{r}
head(elec_tune$results)
```

The selected model corresponds to the row with the smallest value of the
criterion:

```{r}
best_row <- which.min(elec_tune$results$BIC)
elec_tune$results[best_row, ]
```

The selection process can be represented graphically with `plot()`, which
shows the criterion (or the log likelihood with `value = "likelihood"`) as
a function of the cut off, in quantile scale by default. Additional
parameters are passed to `base::plot()`, for instance here to use a
logarithmic scale for the cut off in native scale:

```{r fig.height=4, fig.alt="Line plot of the BIC against the cut off in native scale, on a logarithmic axis, for the models considered by tune_vlmc() on the binary electricity consumption series. The BIC decreases quickly when the cut off increases from its initial value, remains close to its minimum over a range of intermediate cut offs and then increases sharply for the largest cut offs, which give the simplest models."}
plot(elec_tune, cutoff = "native", log = "x")
```

`autoplot()` (which requires ggplot2) gives a more complete representation
with one panel per characteristic of the models:

```{r fig.height=5, fig.alt="Five panels showing the AIC, the BIC, the number of contexts, the depth and the log likelihood of the models considered by tune_vlmc() against the cut off in quantile scale. The number of contexts, the depth and the log likelihood increase with the cut off in quantile scale, that is with the complexity of the models. Both criteria are very high for the smallest cut offs, drop sharply and are minimal for small values of the cut off, the BIC increasing more than the AIC for larger cut offs."}
print(autoplot(elec_tune))
```

## Getting another model than the selected one

### Saved models

By default, `tune_vlmc()` keeps only the selected model. The `save`
parameter can be used to keep more models: with `save = "initial"` the
result contains in addition the initial model, while with `save = "all"` it
contains all the models considered during the selection. They are stored in
the `saved_models` component, a list with:

-   `initial`: the initial model, which corresponds to the first row of
    `results`;
-   `all` (only when `save = "all"`): the list of the *other* models, in the
    order of the pruning process. The `k`-th model of this list corresponds
    therefore to the row `k + 1` of `results`.

For instance, we can obtain from a BIC based selection the model that
minimises the AIC as follows:

```{r}
elec_tune_all <- tune_vlmc(elec_train, save = "all")
length(elec_tune_all$saved_models$all)
nrow(elec_tune_all$results)
aic_row <- which.min(elec_tune_all$results$AIC)
if (aic_row == 1) {
  elec_aic <- elec_tune_all$saved_models$initial
} else {
  elec_aic <- elec_tune_all$saved_models$all[[aic_row - 1]]
}
elec_aic
```

In this example, this model has the same contexts as the one obtained by a
direct AIC based selection, as shown below (the contexts are compared as sets
of character strings, as their order in the result of `contexts()` depends on
the way the context tree was built). However, this is not always the case:
because of the default values of the initial cut off, the initial model of a
BIC based selection is simpler than the one of an AIC based selection, and the
model that minimises the AIC may be more complex than all the models
considered in a BIC based selection.

```{r}
context_set <- function(model) {
  ctxs <- contexts(model, sequence = TRUE)$context
  sort(vapply(ctxs, paste, character(1), collapse = ", "))
}
elec_tune_aic <- tune_vlmc(elec_train, criterion = "AIC")
identical(context_set(elec_aic), context_set(as_vlmc(elec_tune_aic)))
```

Notice also that the criteria reported by the two selections for the same
model are not identical: as explained below, the truncated likelihood used
by default depends on the depth of the initial model, which differs between
the two selections.

```{r}
elec_tune_all$results$depth[1]
min(elec_tune_all$results$AIC)
elec_tune_aic$results$depth[1]
min(elec_tune_aic$results$AIC)
```

### Pruning the initial model

Saving all the models can use a lot of memory for long time series. An
alternative consists in saving only the initial model and in pruning it with
the cut off of the row of interest of `results`. As pruning gives the same
model as a direct estimation, this reproduces exactly the model of the
selection:

```{r}
elec_tune_init <- tune_vlmc(elec_train, save = "initial")
elec_aic_2 <- prune(elec_tune_init$saved_models$initial,
  cutoff = elec_tune_init$results$cutoff[aic_row]
)
all.equal(elec_aic, elec_aic_2)
```

The native scale (`cutoff` column) should be preferred to the quantile one
(`alpha` column) for this operation, as the latter can be very close to zero
for simple models and suffer from rounding errors.

## Manual selection with `cutoff()` and `prune()`

### Cut off scales

In a VLMC, the cut off is compared to the log likelihood ratio between the
conditional distribution of the next state given a context and the one given
its parent context (the context shortened by one state): starting from the
leaves of the context tree, a context is removed when this ratio is smaller
than the cut off. This is the *native* scale of the cut off, used by the
`cutoff` parameters of `vlmc()`, `prune()` and `tune_vlmc()`. A larger value
in native scale leads to a simpler model.

The *quantile* scale, used by the `alpha` parameters, interprets the pruning
decision as a likelihood ratio test: twice the log likelihood ratio follows
asymptotically a $\chi^2$ distribution with $|S|-1$ degrees of freedom
(where $|S|$ is the number of states) and `alpha` is the level of the test,
that is the probability that the $\chi^2$ variable exceeds twice the cut
off. A *smaller* value in quantile scale leads to a simpler model. The two
columns of `results` are related as follows:

```{r}
nb_states <- length(states(elec_vlmc))
all.equal(
  elec_tune$results$alpha,
  pchisq(2 * elec_tune$results$cutoff, df = nb_states - 1, lower.tail = FALSE)
)
```

The native scale is more directly related to the information criteria:
removing a context with $|S|-1$ parameters from a model decreases the BIC
when its log likelihood ratio is smaller than $\frac{|S|-1}{2}\log n$ (and
the AIC when it is smaller than $|S|-1$). The default initial cut offs of
`tune_vlmc()` ($\frac{1}{4}\log n$ and 1) are smaller than or equal to those
thresholds, so that the initial model keeps the contexts that may be
useful according to the criterion.

### Candidate cut off values

`cutoff()` returns the cut off values that lead to all the models simpler
than a given one. By default, the values are in quantile scale, in
decreasing order (from the least to the most pruned model). With
`scale = "native"` they are in increasing order.

```{r}
cutoff(elec_vlmc, scale = "native")
```

The default values are guaranteed to induce pruning: they are placed between
the actual log likelihood ratios of the model, which are obtained with
`raw = TRUE` (see also the `cutoff` parameter of `contexts()`, described in
`vignette("dts-and-contexts")`, which reports the ratio of each context):

```{r}
cutoff(elec_vlmc, scale = "native", raw = TRUE)
```

Pruning with the first value gives the least pruned model simpler than the
reference one:

```{r}
elec_simpler <- prune(elec_vlmc,
  cutoff = cutoff(elec_vlmc, scale = "native")[1]
)
elec_simpler
```

### A custom selection rule

The `results` data frame and `prune()` make it easy to implement other
selection rules. For instance, we may look for an easily interpretable model
with a memory of at most 30 minutes, that is with contexts of length at most
three. The best model according to the BIC under this constraint is obtained
as follows:

```{r}
init_results <- elec_tune_init$results
short_rows <- which(init_results$depth <= 3)
short_row <- short_rows[which.min(init_results$BIC[short_rows])]
elec_short <- prune(elec_tune_init$saved_models$initial,
  cutoff = init_results$cutoff[short_row]
)
draw(elec_short)
```

This model has `r context_number(elec_short)` contexts and a BIC of
`r round(init_results$BIC[short_row], 2)`, while the BIC of the selected
model (with `r context_number(elec_vlmc)` contexts) is
`r round(min(init_results$BIC), 2)`.

## Likelihood functions and number of parameters

### Likelihood functions

In a VLMC of depth $d$, the contexts of the first $d$ observations of a time
series are not completely known. The `initial` parameter of
`loglikelihood()`, `logLik()` and of the selection functions specifies how
those observations are handled:

-   `"truncated"`: they are excluded from the likelihood;
-   `"specific"`: each of them is predicted by a specific context, with a
    perfect prediction and one additional parameter;
-   `"extended"`: they are predicted using shorter contexts, which may turn
    internal nodes of the context tree into additional contexts.

`vignette("likelihood")` describes these functions in detail. For model
selection, the main point is that the truncated likelihood of models of
different depths is computed on different observations. To allow a fair
comparison, `tune_vlmc()` and `tune_covlmc()` exclude from the likelihood of
all the models the first observations, as many as the depth of the
initial model. As a consequence, the criteria reported in `results` differ
from the ones computed directly on the selected model:

```{r}
BIC(elec_vlmc)
min(elec_tune$results$BIC)
```

They can be reproduced with the `ignore` parameter of `loglikelihood()`,
which specifies the number of initial observations excluded from the
likelihood (this requires passing the time series as `newdata`):

```{r}
elec_ll <- loglikelihood(elec_vlmc,
  newdata = elec_train,
  ignore = elec_tune$results$depth[1]
)
elec_ll
BIC(elec_ll)
```

This also means that the criteria reported by two calls to `tune_vlmc()`
with different initial models (for instance with different values of
`min_size` or of the criterion, as seen above) are not directly comparable.
When models selected separately must be compared, their likelihood must be
computed on the same observations, using an `ignore` value at least equal to
the largest depth of the models.

The likelihood function also has an impact on the selected model, as the
specific and extended likelihood functions tend to penalise complex models
more than the truncated one (see `vignette("likelihood")`):

```{r}
elec_tunes <- lapply(
  c("truncated", "specific", "extended"),
  function(ini) as_vlmc(tune_vlmc(elec_train, initial = ini))
)
data.frame(
  initial = c("truncated", "specific", "extended"),
  depth = sapply(elec_tunes, depth),
  nb_contexts = sapply(elec_tunes, context_number)
)
```

### Number of parameters

The number of parameters used by the information criteria is given by the
`df` attribute of the log likelihood. In a VLMC, each context is associated
with a probability distribution on the state space, that is with $|S|-1$
parameters. The specific likelihood adds one parameter per specific
context (that is the depth of the model), while the extended likelihood adds
$|S|-1$ parameters for each internal node turned into a context.

```{r}
context_number(elec_vlmc) * (nb_states - 1)
sapply(
  c("truncated", "specific", "extended"),
  function(ini) attr(logLik(elec_vlmc, initial = ini), "df")
)
```

Notice that all the $|S|-1$ parameters of a context are counted, even if
some states never follow this context in the time series (and have therefore
a zero estimated probability). The same rule applies to the intercepts of the
logistic models of a COVLMC, as explained below.

## Hold-out validation

Information criteria are not the only way to choose a model. When enough
data are available, the models can be compared on their capacity to predict
new observations, by computing their log likelihood on a hold-out part of
the time series that was not used to estimate them. This is done with the
`newdata` parameter of `loglikelihood()`.

A convenient way to evaluate the models on the hold-out observations is to
pass the *complete* time series as `newdata` and to exclude the training
observations from the likelihood with `ignore`. This way, the contexts of the
first hold-out observations are computed using the last training
observations, and all the models are evaluated on exactly the same
observations:

```{r}
elec_models <- c(
  list(elec_tune_all$saved_models$initial),
  elec_tune_all$saved_models$all
)
holdout_ll <- sapply(
  elec_models,
  function(model) loglikelihood(model, newdata = elec, ignore = n_train)
)
elec_holdout <- cbind(
  elec_tune_all$results[c("cutoff", "depth", "nb_contexts", "AIC", "BIC")],
  holdout = holdout_ll
)
elec_holdout
```

Complex models have a log likelihood of `-Inf` on the hold-out data: they
give a zero probability to some transitions observed in the hold-out data, a
clear sign of overfitting. This happens in particular for the model selected
by the AIC. On the contrary, the model with the highest hold-out
log likelihood is simpler than the model selected by the BIC:

```{r}
holdout_row <- which.max(holdout_ll)
elec_holdout[c(aic_row, best_row, holdout_row), ]
```

```{r fig.height=4, fig.alt="Line plot with points of the hold-out log likelihood against the cut off in native scale, for the models with a finite hold-out log likelihood. The log likelihood increases with the cut off up to a maximum reached for a fairly simple model, and then decreases sharply for the simplest models."}
ggplot(
  elec_holdout[is.finite(elec_holdout$holdout), ],
  aes(x = cutoff, y = holdout)
) +
  geom_line() +
  geom_point() +
  scale_x_log10() +
  xlab("Cut off (native scale)") +
  ylab("Hold-out log likelihood")
```

Notice that zero probabilities make the log likelihood a very demanding
criterion, especially when the number of states is larger than two, as rare
transitions are often missing from the training data. Other ways of assessing
the predictive performances of a model, based on `predict()` and `metrics()`,
are described in `vignette("prediction")`.

## Model selection for VLMC with covariates

We consider now a COVLMC with a categorical covariate, the period of the
day, which is a factor with four levels.

```{r}
period <- cut(pc$hour,
  breaks = c(-1, 6, 12, 18, 23),
  labels = c("night", "morning", "afternoon", "evening")
)
elec_cov <- data.frame(period = period)
elec_cov_train <- elec_cov[1:n_train, , drop = FALSE]
```

### Automatic selection with `tune_covlmc()`

`tune_covlmc()` follows the same principle as `tune_vlmc()` and shares most
of its parameters (`criterion`, `initial`, `alpha_init`, `min_size`,
`max_depth`, `verbose` and `save`). The main differences are the following:

-   there is a single implementation of COVLMC, hence no `backend`
    parameter, and the default value of `min_size` is 5 (see below);
-   the cut off is expressed only in quantile scale: the pruning decisions
    of the COVLMC algorithm are based on likelihood ratio tests between
    logistic models whose numbers of parameters vary, and there is no
    meaningful native scale. `cutoff()` returns therefore $p$-values and
    `prune()` accepts only `alpha`. The initial model is built with
    `alpha_init`, which defaults to 0.5;
-   pruning a COVLMC requires fitting new logistic models, and `cutoff()`
    returns only a subset of the useful cut off values. `tune_covlmc()`
    prunes therefore the models one step at a time, using the largest cut
    off value of the current model that is smaller than its own cut off;
-   the `control` parameter gives additional parameters for the estimation of
    the models (see `covlmc_control()`), currently the number of pseudo
    observations used to regularise the probability estimates of the
    contexts always followed by the same state;
-   the `results` data frame has no `cutoff` column but a `cov_depth` column
    which gives the longest memory used for the covariates by the model (see
    `covariate_depth()`).

```{r}
elec_cov_tune <- tune_covlmc(elec_train, elec_cov_train)
elec_cov_tune
elec_cov_tune$results
```

The selected model uses the covariate in one of its contexts (see the article
[Drawing context trees and
models](https://fabrice-rossi.github.io/mixvlmc/articles/drawing.html) for
the representation of the logistic models):

```{r}
elec_covlmc <- as_covlmc(elec_cov_tune)
draw(elec_covlmc, model = "full")
```

`summary()`, `plot()` and `autoplot()` work as for `tune_vlmc()` (except
that `plot()` does not support the native scale).

```{r fig.height=5, fig.alt="Six panels showing the AIC, the BIC, the number of contexts, the covariate depth, the depth and the log likelihood of the models considered by tune_covlmc() against the cut off in quantile scale. The number of contexts, the depths and the log likelihood increase overall with the cut off. Both criteria are very high for the smallest cut offs and drop sharply; the BIC then increases slowly with the cut off while the AIC remains almost flat."}
print(autoplot(elec_cov_tune))
```

Notice that the models of a COVLMC selection are not strictly nested:
removing a context can give to its parent context a logistic model with a
longer memory of the covariates. As a consequence, the number of
parameters and the log likelihood do not always decrease along the pruning
process.

### Saved models and memory occupation

The `save` parameter has the same meaning as for `tune_vlmc()`, with the same
organisation of the `saved_models` component. As COVLMC objects can be large,
the intermediate models of `saved_models$all` are saved in a trimmed form (see
`trim.covlmc()`), as specified by the `trimming` parameter:

-   `"full"` (default): the logistic models are removed, which saves a lot of
    memory but prevents the use of the models on new data
    (`loglikelihood()` with `newdata`, `predict()`, `simulate()`);
-   `"partial"`: the logistic models are kept in a simplified form, which
    enables the use of the models on new data;
-   `"none"`: no trimming, which is recommended only for small data sets.

The initial model and the selected one are not trimmed by default, but they
can be trimmed with the `best_trimming` parameter (which takes the same
values), for instance to reduce the size of the results in parallel
processing. As trimmed models cannot be pruned, the initial model must not be
trimmed to obtain new models with `prune()`. The memory occupied by COVLMC
objects and the operations supported by trimmed models are detailed in the
article [Computing engines and control of VLMC with
covariates](https://fabrice-rossi.github.io/mixvlmc/articles/covlmc-engines.html).

Unlike for VLMC, pruning the initial model with the `alpha` value of a row of
`results` does not always give the model obtained by the successive pruning
steps of `tune_covlmc()`, as each step fits new logistic models. Saving all
the models is therefore the only reliable way to recover the models
considered during a COVLMC selection.

### Number of parameters

The number of parameters of a COVLMC, used by the information criteria, is
the sum of the numbers of parameters of the logistic models of its contexts.
As for a VLMC, the model of a context has $|S|-1$ intercepts, even if some
states never follow this context. The coefficients of the covariates are
counted only when they are actually estimated: the ones associated with the
states that never follow a context or with the levels of factors absent from
the data of a context are not counted, and a context always followed by the
same state has therefore only $|S|-1$ parameters. Counting all the intercepts
ensures that each context has a cost in the information criteria (see the
"Number of parameters" section of `?loglikelihood.covlmc` and the article on
computing engines cited above for details).

```{r}
attr(logLik(elec_covlmc), "df")
```

This number can be read on the representation of the model given above: each
context has an intercept ($|S|-1=1$ for this binary time series) and the
context that uses the covariate has in addition one coefficient per level of
the period of the day (except the reference level) for each time step of its
covariate memory. The likelihood ratio tests used to build the model rely
instead on the nominal number of parameters, which counts the coefficients of
the covariates for all the states and all the levels of the factors, as in
the original algorithm.

### Choosing `min_size`

While `min_size` has generally little influence on the models selected for
VLMC, this is not the case for COVLMC: it specifies the number of
observations per parameter of the logistic models needed for a context to be
considered. There is no automatic support for this choice in `mixvlmc`, but
it is easy to compare the models selected for a few values of `min_size`.
As explained above, the criteria must be computed on the same observations,
here with an `ignore` value equal to the largest depth of the models. We
compute in addition the hold-out log likelihood of the models, using the
`newcov` parameter to give the covariates of the complete time series.

```{r}
min_sizes <- c(2, 5, 10, 20)
cov_models <- lapply(
  min_sizes,
  function(ms) as_covlmc(tune_covlmc(elec_train, elec_cov_train, min_size = ms))
)
common_ignore <- max(sapply(cov_models, depth))
data.frame(
  min_size = min_sizes,
  depth = sapply(cov_models, depth),
  nb_contexts = sapply(cov_models, context_number),
  cov_depth = sapply(cov_models, covariate_depth),
  BIC = sapply(cov_models, function(model) {
    BIC(loglikelihood(model,
      newdata = elec_train, newcov = elec_cov_train,
      ignore = common_ignore
    ))
  }),
  holdout = sapply(cov_models, function(model) {
    loglikelihood(model,
      newdata = elec, newcov = elec_cov,
      ignore = n_train
    )
  })
)
```

Small values of `min_size` give here the same model, while larger values
give simpler models with a higher BIC and a lower hold-out log likelihood.
Notice that the BIC values differ from the ones reported by `tune_covlmc()`,
which are computed with an `ignore` value that depends on the initial model,
and thus on `min_size`.

### Hold-out validation

Finally, all the models considered by `tune_covlmc()` can be compared on the
hold-out data, provided they are saved with a trimming that keeps the
logistic models:

```{r}
elec_cov_tune_all <- tune_covlmc(elec_train, elec_cov_train,
  save = "all", trimming = "partial"
)
cov_models_all <- c(
  list(elec_cov_tune_all$saved_models$initial),
  elec_cov_tune_all$saved_models$all
)
cov_columns <- c("alpha", "depth", "nb_contexts", "cov_depth", "BIC")
cov_holdout <- cbind(
  elec_cov_tune_all$results[cov_columns],
  holdout = sapply(cov_models_all, function(model) {
    loglikelihood(model, newdata = elec, newcov = elec_cov, ignore = n_train)
  })
)
cov_holdout
```

In this example, the model with the highest hold-out log likelihood
(row `r which.max(cov_holdout$holdout)`) is the one selected by the BIC
(row `r which.min(cov_holdout$BIC)`). Its hold-out log likelihood,
`r round(max(cov_holdout$holdout), 2)`, is higher than the one of the VLMC
selected by the BIC, `r round(holdout_ll[best_row], 2)`, but lower than the
best hold-out log likelihood obtained by a VLMC,
`r round(max(holdout_ll), 2)`: the effect of the period of the day found on
the first two weeks does not fully carry over to the third one. With a single
week of hold-out data, such small differences should not be over-interpreted.
