% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/resample.R
\name{fit_resamples}
\alias{fit_resamples}
\alias{fit_resamples.model_spec}
\alias{fit_resamples.workflow}
\title{Fit multiple models via resampling}
\usage{
fit_resamples(object, ...)

\method{fit_resamples}{model_spec}(
  object,
  preprocessor,
  resamples,
  ...,
  metrics = NULL,
  eval_time = NULL,
  control = control_resamples()
)

\method{fit_resamples}{workflow}(
  object,
  resamples,
  ...,
  metrics = NULL,
  eval_time = NULL,
  control = control_resamples()
)
}
\arguments{
\item{object}{A \code{parsnip} model specification or an unfitted
\link[workflows:workflow]{workflow()}. No tuning parameters are allowed; if arguments
have been marked with \link[hardhat:tune]{tune()}, their values must be
\link[=finalize_model]{finalized}.}

\item{...}{Currently unused.}

\item{preprocessor}{A traditional model formula or a recipe created using
\code{\link[recipes:recipe]{recipes::recipe()}}.}

\item{resamples}{An \code{rset} resampling object created from an \code{rsample}
function, such as \code{\link[rsample:vfold_cv]{rsample::vfold_cv()}}.}

\item{metrics}{A \code{\link[yardstick:metric_set]{yardstick::metric_set()}}, or \code{NULL} to compute a standard
set of metrics.}

\item{eval_time}{A numeric vector of time points where dynamic event time
metrics should be computed (e.g. the time-dependent ROC curve, etc). The
values must be non-negative and should probably be no greater than the
largest event time in the training set (See Details below).}

\item{control}{A \code{\link[=control_resamples]{control_resamples()}} object used to fine tune the resampling
process.}
}
\description{
\code{\link[=fit_resamples]{fit_resamples()}} computes a set of performance metrics across one or more
resamples. It does not perform any tuning (see \code{\link[=tune_grid]{tune_grid()}} and
\code{\link[=tune_bayes]{tune_bayes()}} for that), and is instead used for fitting a single
model+recipe or model+formula combination across many resamples.
}
\section{Case Weights}{

Some models can utilize case weights during training. tidymodels currently
supports two types of case weights: importance weights (doubles) and
frequency weights (integers). Frequency weights are used during model
fitting and evaluation, whereas importance weights are only used during
fitting.

To know if your model is capable of using case weights, create a model spec
and test it using \code{\link[parsnip:case_weights_allowed]{parsnip::case_weights_allowed()}}.

To use them, you will need a numeric column in your data set that has been
passed through either \code{\link[hardhat:importance_weights]{hardhat:: importance_weights()}} or
\code{\link[hardhat:frequency_weights]{hardhat::frequency_weights()}}.

For functions such as \code{\link[=fit_resamples]{fit_resamples()}} and the \verb{tune_*()} functions, the
model must be contained inside of a \code{\link[workflows:workflow]{workflows::workflow()}}. To declare that
case weights are used, invoke \code{\link[workflows:add_case_weights]{workflows::add_case_weights()}} with the
corresponding (unquoted) column name.

From there, the packages will appropriately handle the weights during model
fitting and (if appropriate) performance estimation.
}

\section{Censored Regression Models}{


Three types of metrics can be used to assess the quality of censored
regression models:
\itemize{
\item static: the prediction is independent of time.
\item dynamic: the prediction is a time-specific probability (e.g., survival
probability) and is measured at one or more particular times.
\item integrated: same as the dynamic metric but returns the integral of the
different metrics from each time point.
}

Which metrics are chosen by the user affects how many evaluation times
should be specified. For example:

\if{html}{\out{<div class="sourceCode">}}\preformatted{# Needs no `eval_time` value
metric_set(concordance_survival)

# Needs at least one `eval_time`
metric_set(brier_survival)
metric_set(brier_survival, concordance_survival)

# Needs at least two eval_time` values
metric_set(brier_survival_integrated, concordance_survival)
metric_set(brier_survival_integrated, concordance_survival)
metric_set(brier_survival_integrated, concordance_survival, brier_survival)
}\if{html}{\out{</div>}}

Values of \code{eval_time} should be less than the largest observed event
time in the training data. For many non-parametric models, the results beyond
the largest time corresponding to an event are constant (or \code{NA}).
}

\section{Performance Metrics}{


To use your own performance metrics, the \code{\link[yardstick:metric_set]{yardstick::metric_set()}} function
can be used to pick what should be measured for each model. If multiple
metrics are desired, they can be bundled. For example, to estimate the area
under the ROC curve as well as the sensitivity and specificity (under the
typical probability cutoff of 0.50), the \code{metrics} argument could be given:

\preformatted{
  metrics = metric_set(roc_auc, sens, spec)
}

Each metric is calculated for each candidate model.

If no metric set is provided, one is created:
\itemize{
\item For regression models, the root mean squared error and coefficient
of determination are computed.
\item For classification, the area under the ROC curve and overall accuracy
are computed.
\item For censored regression, the dynamic Brier score
(\code{\link[yardstick:brier_survival]{yardstick::brier_survival()}}) is used.
\item For quantile regression, the weighted interval score
(\code{\link[yardstick:weighted_interval_score]{yardstick::weighted_interval_score()}}) is used.
}

Note that the metrics also determine what type of predictions are estimated
during tuning. For example, in a classification problem, if metrics are used
that are all associated with hard class predictions, the classification
probabilities are not created.

The out-of-sample estimates of these metrics are contained in a list column
called \code{.metrics}. This tibble contains a row for each metric and columns
for the value, the estimator type, and so on.

\code{\link[=collect_metrics]{collect_metrics()}} can be used for these objects to collapse the results
over the resampled (to obtain the final resampling estimates per tuning
parameter combination).
}

\section{Obtaining Predictions}{


When \code{control_grid(save_pred = TRUE)}, the output tibble contains a list
column called \code{.predictions} that has the out-of-sample predictions for each
parameter combination in the grid and each fold (which can be very large).

The elements of the tibble are tibbles with columns for the tuning
parameters, the row number from the original data object (\code{.row}), the
outcome data (with the same name(s) of the original data), and any columns
created by the predictions. For example, for simple regression problems, this
function generates a column called \code{.pred} and so on. As noted above, the
prediction columns that are returned are determined by the type of metric(s)
requested.

This list column can be \code{unnested} using \code{\link[tidyr:unnest]{tidyr::unnest()}} or using the
convenience function \code{\link[=collect_predictions]{collect_predictions()}}.
}

\section{Extracting Information}{


The \code{extract} control option will result in an additional function to be
returned called \code{.extracts}. This is a list column that has tibbles
containing the results of the user's function for each tuning parameter
combination. This can enable returning each model and/or recipe object that
is created during resampling. Note that this could result in a large return
object, depending on what is returned.

The control function contains an option (\code{extract}) that can be used to
retain any model or recipe that was created within the resamples. This
argument should be a function with a single argument. The value of the
argument that is given to the function in each resample is a workflow
object (see \code{\link[workflows:workflow]{workflows::workflow()}} for more information). Several
helper functions can be used to easily pull out the preprocessing
and/or model information from the workflow, such as
\code{\link[workflows:extract-workflow]{extract_preprocessor()}} and
\code{\link[workflows:extract-workflow]{extract_fit_parsnip()}}.

As an example, if there is interest in getting each parsnip model fit back,
one could use:
\preformatted{
  extract = function (x) extract_fit_parsnip(x)
}

Note that the function given to the \code{extract} argument is evaluated on
every model that is \emph{fit} (as opposed to every model that is \emph{evaluated}).
As noted above, in some cases, model predictions can be derived for
sub-models so that, in these cases, not every row in the tuning parameter
grid has a separate R object associated with it.

Finally, it is a good idea to include calls to \code{\link[=require]{require()}} for packages that
are used in the function. This helps prevent failures when using parallel
processing.
}

\examples{
\dontshow{if (tune:::should_run_examples() & rlang::is_installed("splines2")) withAutoprint(\{ # examplesIf}
library(recipes)
library(rsample)
library(parsnip)
library(workflows)

set.seed(6735)
folds <- vfold_cv(mtcars, v = 5)

spline_rec <- recipe(mpg ~ ., data = mtcars) |>
  step_spline_natural(disp) |>
  step_spline_natural(wt)

lin_mod <- linear_reg() |>
  set_engine("lm")

control <- control_resamples(save_pred = TRUE)

spline_res <- fit_resamples(lin_mod, spline_rec, folds, control = control)

spline_res

show_best(spline_res, metric = "rmse")

# You can also wrap up a preprocessor and a model into a workflow, and
# supply that to `fit_resamples()` instead. Here, a workflows "variables"
# preprocessor is used, which lets you supply terms using dplyr selectors.
# The variables are used as-is, no preprocessing is done to them.
wf <- workflow() |>
  add_variables(outcomes = mpg, predictors = everything()) |>
  add_model(lin_mod)

wf_res <- fit_resamples(wf, folds)
\dontshow{\}) # examplesIf}
}
\seealso{
\code{\link[=control_resamples]{control_resamples()}}, \code{\link[=collect_predictions]{collect_predictions()}}, \code{\link[=collect_metrics]{collect_metrics()}}
}
