Package {kerasnip}


Type: Package
Title: A Bridge Between 'keras' and 'tidymodels'
Version: 0.2.0
Description: Provides a seamless bridge between 'keras' and the 'tidymodels' frameworks. It allows for the dynamic creation of 'parsnip' model specifications for 'keras' models.
Depends: R (≥ 4.1.0)
Encoding: UTF-8
License: MIT + file LICENSE
URL: https://davidrsch.github.io/kerasnip/, https://github.com/davidrsch/kerasnip
BugReports: https://github.com/davidrsch/kerasnip/issues
Imports: abind, generics, parsnip (≥ 1.0.0), rlang, keras3, tibble, purrr, dplyr, cli, recipes, reticulate, lobstr
Config/testthat/edition: 3
Suggests: testthat (≥ 3.0.0), bundle, butcher, modeldata, tidymodels, finetune, tune, dials, workflows, rsample, stacks, knitr, lme4, rmarkdown, future, ggplot2, mgcv, probably, tailor, hardhat, tidyr
VignetteBuilder: knitr
Config/roxygen2/version: 8.0.0
NeedsCompilation: no
Packaged: 2026-09-03 16:51:57 UTC; david
Author: David Díaz ORCID iD [aut, cph, cre]
Maintainer: David Díaz <daviddrsch@gmail.com>
Repository: CRAN
Date/Publication: 2026-09-03 17:20:02 UTC

Augment Method for kerasnip_output_view Objects

Description

Binds predict(x, new_data, type = "numeric")'s .pred column with new_data, mirroring workflows:::augment.workflow(). Used internally by int_conformal_split.kerasnip_output_view(), which needs both the prediction and new_data's truth column in one data frame.

Usage

## S3 method for class 'kerasnip_output_view'
augment(x, new_data, ...)

Arguments

x

A kerasnip_output_view.

new_data

A data frame of predictors, including x$output's truth column.

...

Not used.

Value

new_data with a .pred column prepended.


Augment Method for kerasnip_step_view Objects

Description

Binds predict(x, new_data, type = "numeric")'s .pred column with the step's truth (from kerasnip_step_truth()) and new_data, mirroring workflows:::augment.workflow(). Used internally by int_conformal_split.kerasnip_step_view(). Rows step_sequence() drops for lacking a full window of history are dropped here too, to stay aligned with predict()'s row count.

Usage

## S3 method for class 'kerasnip_step_view'
augment(x, new_data, ...)

Arguments

x

A kerasnip_step_view.

new_data

A data frame of raw predictors (and the original outcome column step_lead() was applied to).

...

Not used.

Value

A tibble: .pred, the step's truth column (named x$outcome_col), and new_data's columns, aligned to the rows that survived windowing.


Butcher axe methods for kerasnip_model_fit

Description

These methods allow butcher::butcher() to reduce the memory footprint of fitted kerasnip model objects. The Keras model itself (stored as raw bytes in ⁠$fit$keras_bytes⁠) is always preserved so that predict() continues to work after butchering.

The main saving comes from axe_data(), which removes the training history object (⁠$fit$history⁠). For long training runs this can be several MB.

Usage

## S3 method for class 'kerasnip_model_fit'
axe_data(x, verbose = FALSE, ...)

## S3 method for class 'kerasnip_model_fit'
axe_env(x, verbose = FALSE, ...)

## S3 method for class 'kerasnip_model_fit'
axe_call(x, verbose = FALSE, ...)

## S3 method for class 'kerasnip_model_fit'
axe_ctrl(x, verbose = FALSE, ...)

## S3 method for class 'kerasnip_model_fit'
axe_fitted(x, verbose = FALSE, ...)

Arguments

x

A kerasnip_model_fit object.

verbose

Logical. Print information about memory released and disabled functions. Default is FALSE.

...

Not used.

Value

An axed kerasnip_model_fit object with the butcher_kerasnip_model_fit class prepended.


Compile Keras Models Over a Grid of Hyperparameters

Description

Pre-compiles Keras models for each hyperparameter combination in a grid.

This function is a powerful debugging tool to use before running a full tune::tune_grid(). It allows you to quickly validate multiple model architectures, ensuring they can be successfully built and compiled without the time-consuming process of actually fitting them. It helps catch common errors like incompatible layer shapes or invalid argument values early.

Usage

compile_keras_grid(spec, grid, x, y)

Arguments

spec

A parsnip model specification created by create_keras_sequential_spec() or create_keras_functional_spec().

grid

A tibble or data.frame containing the grid of hyperparameters to evaluate. Each row represents a unique model architecture to be compiled. Must have at least one row. To build the model once using only the arguments already set on spec (e.g. for architecture inspection), pass tibble::tibble(.rows = 1L).

x

A data frame or matrix of predictors. This is used to infer the input_shape for the Keras model.

y

A vector or factor of outcomes. This is used to infer the output shape and the default loss function for the Keras model.

Details

Compile and Validate Keras Model Architectures

The function iterates through each row of the provided grid. For each hyperparameter combination, it attempts to build and compile the Keras model defined by the spec. The process is wrapped in a try-catch block to gracefully handle and report any errors that occur during model instantiation or compilation.

The output is a tibble that mirrors the input grid, with additional columns containing the compiled model object or the error message, making it easy to inspect which architectures are valid.

Value

A tibble with the following columns:

Examples


if (requireNamespace("keras3", quietly = TRUE)) {
library(keras3)
library(parsnip)
library(dials)

# 1. Define layer blocks
input_block <- function(model, input_shape) {
  keras_model_sequential(input_shape = input_shape)
}
hidden_block <- function(model, units = 32) {
  model |> layer_dense(units = units, activation = "relu")
}
output_block <- function(model, num_classes) {
  model |> layer_dense(units = num_classes, activation = "softmax")
}

# 2. Define a kerasnip model specification
create_keras_sequential_spec(
  model_name = "my_mlp_grid",
  layer_blocks = list(
    input = input_block,
    hidden = hidden_block,
    output = output_block
  ),
  mode = "classification"
)

mlp_spec <- my_mlp_grid(
  hidden_units = tune(),
  compile_loss = "categorical_crossentropy",
  compile_optimizer = "adam"
)

# 3. Create a hyperparameter grid
# Include an invalid value (-10) to demonstrate error handling
param_grid <- tibble::tibble(
  hidden_units = c(32, 64, -10)
)

# 4. Prepare dummy data
x_train <- matrix(rnorm(100 * 10), ncol = 10)
y_train <- factor(sample(0:1, 100, replace = TRUE))

# 5. Compile models over the grid
compiled_grid <- compile_keras_grid(
  spec = mlp_spec,
  grid = param_grid,
  x = x_train,
  y = y_train
)

print(compiled_grid)
remove_keras_spec("my_mlp_grid")

# 6. Inspect the results
# The row with `hidden_units = -10` will show an error.
}


Create a Custom Keras Functional API Model Specification for Tidymodels

Description

This function acts as a factory to generate a new parsnip model specification based on user-defined blocks of Keras layers using the Functional API. This allows for creating complex, tunable architectures with non-linear topologies that integrate seamlessly with the tidymodels ecosystem.

Usage

create_keras_functional_spec(
  model_name,
  layer_blocks,
  mode = c("regression", "classification"),
  ...,
  env = parent.frame()
)

Arguments

model_name

A character string for the name of the new model specification function (e.g., "custom_resnet"). This should be a valid R function name.

layer_blocks

A named list of functions where each function defines a "block" (a node) in the model graph. The list names are crucial as they define the names of the nodes. The arguments of each function define how the nodes are connected. See the "Model Graph Connectivity" section for details.

mode

A character string, either "regression" or "classification".

...

Reserved for future use. Currently not used.

env

The environment in which to create the new model specification function and its associated update() method. Defaults to the calling environment (parent.frame()).

Details

This function generates all the boilerplate needed to create a custom, tunable parsnip model specification that uses the Keras Functional API. This is ideal for models with complex, non-linear topologies, such as networks with multiple inputs/outputs or residual connections.

The function inspects the arguments of your layer_blocks functions and makes them available as tunable parameters in the generated model specification, prefixed with the block's name (e.g., dense_units). Common training parameters such as fit_epochs and learn_rate are also added.

Value

Invisibly returns NULL. Its primary side effect is to create a new model specification function (e.g., custom_resnet()) in the specified environment and register the model with parsnip so it can be used within the tidymodels framework.

Model Graph Connectivity

kerasnip builds the model's directed acyclic graph by inspecting the arguments of each function in the layer_blocks list. The connection logic is as follows:

  1. The names of the elements in the layer_blocks list define the names of the nodes in your graph (e.g., main_input, dense_path, output).

  2. The names of the arguments in each block function specify its inputs. A block function like ⁠my_block <- function(input_a, input_b, ...)⁠ declares that it needs input from the nodes named input_a and input_b. kerasnip will automatically supply the output tensors from those nodes when calling my_block.

There are two special requirements:

A key feature is the automatic creation of ⁠num_{block_name}⁠ arguments (e.g., num_dense_path). This allows you to control how many times a block is repeated, making it easy to tune the depth of your network. A block can only be repeated if it has exactly one input from another block in the graph.

The new model specification function and its update() method are created in the environment specified by the env argument.

Saving and Reloading Models

To save a fitted workflow and reload it in a new R session, use bundle::bundle() before saving — this is required to preserve the Keras model weights:

library(bundle)
bundled <- bundle(fitted_workflow)
saveRDS(bundled, "model.rds")

# New session:
library(kerasnip); library(bundle)
fitted_workflow <- unbundle(readRDS("model.rds"))
predict(fitted_workflow, new_data = test_data)  # works

Plain saveRDS() without bundle() does not preserve Keras weights, but predict() will still auto-register the parsnip model type from metadata stored on the spec.

See Also

remove_keras_spec(), parsnip::new_model_spec(), create_keras_sequential_spec()

Examples


if (requireNamespace("keras3", quietly = TRUE)) {
  library(keras3)
  library(parsnip)

  # 1. Define block functions. These are the building blocks of our model.
  # An input block that receives the data's shape automatically.
  input_block <- function(input_shape) layer_input(shape = input_shape)

  # A dense block with a tunable `units` parameter.
  dense_block <- function(tensor, units) {
    tensor |> layer_dense(units = units, activation = "relu")
  }

  # A block that adds two tensors together (for the residual connection).
  add_block <- function(input_a, input_b) layer_add(list(input_a, input_b))

  # An output block for regression.
  output_block_reg <- function(tensor) layer_dense(tensor, units = 1)

  # 2. Create the spec. The `layer_blocks` list defines the graph.
  create_keras_functional_spec(
    model_name = "my_resnet_spec",
    layer_blocks = list(
      # The names of list elements are the node names.
      main_input = input_block,

      # The argument `main_input` connects this block to the input node.
      dense_path = function(main_input, units = 32) {
        dense_block(main_input, units)
      },

      # This block's arguments connect it to the original input AND the dense
      # layer.
      add_residual = function(main_input, dense_path) {
        add_block(main_input, dense_path)
      },

      # This block must be named 'output'. It connects to the residual add
      # layer.
      output = function(add_residual) output_block_reg(add_residual)
    ),
    mode = "regression"
  )

  # 3. Use the newly created specification function!
  # The `dense_path_units` argument was created automatically.
  model_spec <- my_resnet_spec(dense_path_units = 64, fit_epochs = 10)

  # You could also tune the number of dense layers since it has a single
  # input:
  # model_spec <- my_resnet_spec(num_dense_path = 2, dense_path_units = 32)

  print(model_spec)
  remove_keras_spec("my_resnet_spec")
  # tune::tunable(model_spec)
}


Create a Custom Keras Sequential Model Specification for Tidymodels

Description

This function acts as a factory to generate a new parsnip model specification based on user-defined blocks of Keras layers using the Sequential API. This is the ideal choice for creating models that are a simple, linear stack of layers. For models with complex, non-linear topologies, see create_keras_functional_spec().

Usage

create_keras_sequential_spec(
  model_name,
  layer_blocks,
  mode = c("regression", "classification"),
  ...,
  env = parent.frame()
)

Arguments

model_name

A character string for the name of the new model specification function (e.g., "custom_cnn"). This should be a valid R function name.

layer_blocks

A named, ordered list of functions. Each function defines a "block" of Keras layers. The function must take a Keras model object as its first argument and return the modified model. Other arguments to the function will become tunable parameters in the final model specification.

mode

A character string, either "regression" or "classification".

...

Reserved for future use. Currently not used.

env

The environment in which to create the new model specification function and its associated update() method. Defaults to the calling environment (parent.frame()).

Details

This function generates all the boilerplate needed to create a custom, tunable parsnip model specification that uses the Keras Sequential API.

The function inspects the arguments of your layer_blocks functions (ignoring special arguments like input_shape and num_classes) and makes them available as arguments in the generated model specification, prefixed with the block's name (e.g., dense_units).

The new model specification function and its update() method are created in the environment specified by the env argument.

Value

Invisibly returns NULL. Its primary side effect is to create a new model specification function (e.g., my_mlp()) in the specified environment and register the model with parsnip so it can be used within the tidymodels framework.

Model Architecture (Sequential API)

kerasnip builds the model by applying the functions in layer_blocks in the order they are provided. Each function receives the Keras model built by the previous function and returns a modified version.

  1. The first block must initialize the model (e.g., with keras_model_sequential()). It can accept an input_shape argument, which kerasnip will provide automatically during fitting.

  2. Subsequent blocks add layers to the model.

  3. The final block should add the output layer. For classification, it can accept a num_classes argument, which is provided automatically.

A key feature of this function is the automatic creation of ⁠num_{block_name}⁠ arguments (e.g., num_hidden). This allows you to control how many times each block is repeated, making it easy to tune the depth of your network.

Saving and Reloading Models

To save a fitted workflow and reload it in a new R session, use bundle::bundle() before saving — this is required to preserve the Keras model weights:

library(bundle)
bundled <- bundle(fitted_workflow)
saveRDS(bundled, "model.rds")

# New session:
library(kerasnip); library(bundle)
fitted_workflow <- unbundle(readRDS("model.rds"))
predict(fitted_workflow, new_data = test_data)  # works

Plain saveRDS() without bundle() does not preserve Keras weights, but predict() will still auto-register the parsnip model type from metadata stored on the spec.

See Also

remove_keras_spec(), parsnip::new_model_spec(), create_keras_functional_spec()

Examples


if (requireNamespace("keras3", quietly = TRUE)) {
library(keras3)
library(parsnip)
library(dials)

# 1. Define layer blocks for a complete model.
# The first block must initialize the model. `input_shape` is passed
# automatically.
input_block <- function(model, input_shape) {
  keras_model_sequential(input_shape = input_shape)
}
# A block for hidden layers. `units` will become a tunable parameter.
hidden_block <- function(model, units = 32) {
  model |> layer_dense(units = units, activation = "relu")
}

# The output block. `num_classes` is passed automatically for classification.
output_block <- function(model, num_classes) {
  model |> layer_dense(units = num_classes, activation = "softmax")
}

# 2. Create the spec, providing blocks in the correct order.
create_keras_sequential_spec(
model_name = "my_mlp_seq_spec",
  layer_blocks = list(
    input = input_block,
    hidden = hidden_block,
    output = output_block
  ),
  mode = "classification"
)

# 3. Use the newly created specification function!
# Note the new arguments `num_hidden` and `hidden_units`.
model_spec <- my_mlp_seq_spec(
  num_hidden = 2,
  hidden_units = 64,
  fit_epochs = 10,
  learn_rate = 0.01
)

print(model_spec)
remove_keras_spec("my_mlp_seq_spec")
}


Extract Keras Training History

Description

Extracts and returns the training history from a parsnip model_fit object created by kerasnip.

Usage

extract_keras_history(object)

Arguments

object

A model_fit object produced by a kerasnip specification.

Details

Extract Keras Training History

The history object contains the metrics recorded during model training, such as loss and accuracy, for each epoch. This is highly useful for visualizing the training process and diagnosing issues like overfitting. The returned object can be plotted directly.

Value

A keras_training_history object. You can call plot() on this object to visualize the learning curves.

See Also

keras_evaluate, extract_keras_model


Extract Keras Model from a Fitted Kerasnip Object

Description

Extracts and returns the underlying Keras model object from a parsnip model_fit object created by kerasnip.

Usage

extract_keras_model(object)

Arguments

object

A model_fit object produced by a kerasnip specification.

Details

Extract the Raw Keras Model from a Kerasnip Fit

This is useful when you need to work directly with the Keras model object for tasks like inspecting layer weights, creating custom plots, or passing it to other Keras-specific functions.

Value

The raw Keras model object (keras_model).

See Also

keras_evaluate, extract_keras_history


Extract Mold Method for kerasnip_output_view Objects

Description

Returns the wrapped workflow's mold with ⁠$outcomes⁠ (and, if present, ⁠$blueprint$ptypes$outcomes⁠) sliced down to x$output's single column, so downstream code that reads names(extract_mold(x)$outcomes) (such as probably::int_conformal_split()) sees a single-outcome fit.

Usage

## S3 method for class 'kerasnip_output_view'
extract_mold(x, ...)

Arguments

x

A kerasnip_output_view.

...

Not used.

Value

A hardhat mold with a single outcome column.


Extract Valid Grid from Compilation Results

Description

This helper function filters the results from compile_keras_grid() to return a new hyperparameter grid containing only the combinations that compiled successfully.

Usage

extract_valid_grid(compiled_grid)

Arguments

compiled_grid

A tibble, the result of a call to compile_keras_grid().

Details

Filter a Grid to Only Valid Hyperparameter Sets

After running compile_keras_grid(), you can use this function to remove problematic hyperparameter combinations before proceeding to the full tune::tune_grid().

Value

A tibble containing the subset of the original grid that resulted in a successful model compilation. The compiled_model and error columns are removed, leaving a clean grid ready for tuning.

Examples


if (requireNamespace("keras3", quietly = TRUE)) {
  library(keras3)
  library(parsnip)
  library(dials)

  # 1. Define layer blocks
  input_block <- function(model, input_shape) {
    keras_model_sequential(input_shape = input_shape)
  }
  hidden_block <- function(model, units = 32) {
    model |> layer_dense(units = units, activation = "relu")
  }
  output_block <- function(model, num_classes) {
    model |> layer_dense(units = num_classes, activation = "softmax")
  }

  # 2. Define a kerasnip model specification
  create_keras_sequential_spec(
    model_name = "my_mlp_grid_2",
    layer_blocks = list(
      input = input_block,
      hidden = hidden_block,
      output = output_block
    ),
    mode = "classification"
  )

  mlp_spec <- my_mlp_grid_2(
    hidden_units = tune(),
    compile_loss = "categorical_crossentropy",
    compile_optimizer = "adam"
  )

  # 3. Create a hyperparameter grid
  param_grid <- tibble::tibble(
    hidden_units = c(32, 64, -10)
  )

  # 4. Prepare dummy data
  x_train <- matrix(rnorm(100 * 10), ncol = 10)
  y_train <- factor(sample(0:1, 100, replace = TRUE))

  # 5. Compile models over the grid
  compiled_grid <- compile_keras_grid(
    spec = mlp_spec,
    grid = param_grid,
    x = x_train,
    y = y_train
  )

  # 6. Extract the valid grid
  valid_grid <- extract_valid_grid(compiled_grid)
  print(valid_grid)
  remove_keras_spec("my_mlp_grid_2")
}


Fit Method for kerasnip Spec Objects

Description

S3 method for fit() dispatched on kerasnip_spec objects. Delegates to the standard parsnip fit.model_spec() and then tags the result with the kerasnip_model_fit class so that predict.kerasnip_model_fit() is dispatched on subsequent calls.

kerasnip_spec is stripped from the class before NextMethod() to prevent parsnip's internal specific_model() helper from returning more than one model-class entry, which would break registry lookups. The custom metadata attributes remain on the object and are thus stored inside the resulting model_fit$spec.

Usage

## S3 method for class 'kerasnip_spec'
fit(object, ...)

Arguments

object

A kerasnip_spec model specification.

...

Passed to parsnip::fit.model_spec().

Value

A model_fit object with the additional kerasnip_model_fit class prepended to its class vector.


Fit Method for kerasnip_tailored_workflow Objects

Description

Trains the underlying multi-output/multistep workflow, then fits object$tailor against the target output's/step's predictions (via kerasnip_output_view()/kerasnip_step_view()) on data_calibration if supplied, otherwise on data.

Usage

## S3 method for class 'kerasnip_tailored_workflow'
fit(object, data, ..., data_calibration = NULL)

Arguments

object

A kerasnip_tailored_workflow, from kerasnip_add_tailor().

data

The training data.

...

Passed to fit() on the underlying workflow.

data_calibration

Optional calibration data for the tailor; defaults to data if not supplied.

Value

A kerasnip_tailored_fit, to be used with predict().


fit_xy Method for kerasnip Spec Objects

Description

S3 method for fit_xy() dispatched on kerasnip_spec objects. Workflows route through fit_xy rather than fit, so this method ensures the kerasnip_model_fit class is attached in the workflow fitting path as well.

kerasnip_spec is stripped from the class before NextMethod() to prevent parsnip's internal specific_model() helper from returning more than one model-class entry, which would break registry lookups. The custom metadata attributes remain on the object and are thus stored inside the resulting model_fit$spec.

Usage

## S3 method for class 'kerasnip_spec'
fit_xy(object, ...)

Arguments

object

A kerasnip_spec model specification.

...

Passed to parsnip::fit_xy.model_spec().

Value

A model_fit object with the additional kerasnip_model_fit class prepended to its class vector.


Internal Fitting Engine for Functional API Models

Description

This function serves as the internal engine for fitting kerasnip models that are based on the Keras functional API. It is not intended to be called directly by the user. The function is invoked by parsnip::fit() when a kerasnip functional model specification is used.

Usage

generic_functional_fit(x, y, layer_blocks, ...)

Arguments

x

A data frame of predictors, passed down from parsnip's data.frame fit interface (already separated from the outcome).

y

A vector or data frame of outcomes, passed down from parsnip's data.frame fit interface.

layer_blocks

A named list of layer block functions. This is passed internally from the parsnip model specification.

...

Additional arguments passed down from the model specification. These can include:

  • Layer Parameters: Arguments for the layer blocks, prefixed with the block name (e.g., dense_units = 64).

  • Architecture Parameters: Arguments to control the number of times a block is repeated, in the format ⁠num_{block_name}⁠ (e.g., num_dense = 2).

  • Compile Parameters: Arguments to customize model compilation, prefixed with compile_ (e.g., compile_loss = "mae", compile_optimizer = "sgd").

  • Fit Parameters: Arguments to customize model fitting, prefixed with fit_ (e.g., fit_callbacks = list(...), fit_class_weight = list(...)).

Details

Generic Fitting Function for Functional Keras Models

The function orchestrates the three main steps of the model fitting process:

  1. Build and Compile: It calls build_compile_func_model() to construct the Keras model architecture based on the provided layer_blocks and hyperparameters.

  2. Process Data: It preprocesses the input (x) and output (y) data into the format expected by Keras.

  3. Fit Model: It calls keras3::fit() with the compiled model and processed data, passing along any fitting-specific arguments (e.g., fit_epochs, fit_batch_size, fit_callbacks).

Value

A list containing the fitted model and other metadata. This list is stored in the fit slot of the parsnip model fit object. The list contains the following elements:

Examples

# This function is not called directly by users.
# It is called internally by `parsnip::fit()`.
# For example:

library(parsnip)
# create_keras_functional_spec(...) defines my_functional_model

# spec <- my_functional_model(hidden_units = 128, fit_epochs = 10) |>
#   set_engine("keras")

# # This call to fit() would invoke generic_functional_fit() internally
# fitted_model <- fit(spec, y ~ x, data = training_data)


Internal Fitting Engine for Sequential API Models

Description

This function serves as the internal engine for fitting kerasnip models that are based on the Keras sequential API. It is not intended to be called directly by the user. The function is invoked by parsnip::fit() when a kerasnip sequential model specification is used.

Usage

generic_sequential_fit(x, y, layer_blocks, ...)

Arguments

x

A data frame of predictors, passed down from parsnip's data.frame fit interface (already separated from the outcome).

y

A vector or data frame of outcomes, passed down from parsnip's data.frame fit interface.

layer_blocks

A named list of layer block functions. This is passed internally from the parsnip model specification.

...

Additional arguments passed down from the model specification. These can include:

  • Layer Parameters: Arguments for the layer blocks, prefixed with the block name (e.g., dense_units = 64).

  • Architecture Parameters: Arguments to control the number of times a block is repeated, in the format ⁠num_{block_name}⁠ (e.g., num_dense = 2).

  • Compile Parameters: Arguments to customize model compilation, prefixed with compile_ (e.g., compile_loss = "mae", compile_optimizer = "sgd").

  • Fit Parameters: Arguments to customize model fitting, prefixed with fit_ (e.g., fit_callbacks = list(...), fit_class_weight = list(...)).

Details

Generic Fitting Function for Sequential Keras Models

The function orchestrates the three main steps of the model fitting process:

  1. Build and Compile: It calls build_compile_seq_model() to construct the Keras model architecture based on the provided layer_blocks and hyperparameters.

  2. Process Data: It preprocesses the input (x) and output (y) data into the format expected by Keras.

  3. Fit Model: It calls keras3::fit() with the compiled model and processed data, passing along any fitting-specific arguments (e.g., fit_epochs, fit_batch_size, fit_callbacks).

Value

A list containing the fitted model and other metadata. This list is stored in the fit slot of the parsnip model fit object. The list contains the following elements:

Examples

# This function is not called directly by users.
# It is called internally by `parsnip::fit()`.
# For example:

library(parsnip)
# create_keras_sequential_spec(...) defines my_sequential_model

# spec <- my_sequential_model(hidden_1_units = 128, fit_epochs = 10) |>
#   set_engine("keras")

# # This call to fit() would invoke generic_sequential_fit() internally
# fitted_model <- fit(spec, y ~ x, data = training_data)


Get Parsnip's Model Environment

Description

This is an internal helper function to retrieve the environment where parsnip stores its model definitions. It is used to dynamically interact with the parsnip infrastructure.

Usage

get_model_env()

Value

The parsnip model environment.

Examples


model_env <- kerasnip::get_model_env()


Glance at a Fitted Kerasnip Model

Description

Returns a one-row tibble of summary statistics from the final training epoch: every metric the model was compiled with (e.g. loss, accuracy).

Usage

## S3 method for class 'kerasnip_model_fit'
glance(x, ...)

Arguments

x

A kerasnip_model_fit object.

...

Not used.

Value

A one-row tibble with one column per compiled metric. Returns an empty tibble if training history has been stripped (e.g. by butcher).


Inform About Compilation Errors

Description

This helper function inspects the results from compile_keras_grid() and prints a formatted, easy-to-read summary of any compilation errors that occurred.

Usage

inform_errors(compiled_grid, n = 10)

Arguments

compiled_grid

A tibble, the result of a call to compile_keras_grid().

n

A single integer for the maximum number of distinct errors to display in detail.

Details

Display a Summary of Compilation Errors

This is most useful for interactive debugging of complex tuning grids where some hyperparameter combinations may lead to invalid Keras models.

Value

Invisibly returns the input compiled_grid. Called for its side effect of printing a summary to the console.

Examples


if (requireNamespace("keras3", quietly = TRUE)) {
  library(keras3)
  library(parsnip)
  library(dials)

  # 1. Define layer blocks
  input_block <- function(model, input_shape) {
    keras_model_sequential(input_shape = input_shape)
  }
  hidden_block <- function(model, units = 32) {
    model |> layer_dense(units = units, activation = "relu")
  }
  output_block <- function(model, num_classes) {
    model |> layer_dense(units = num_classes, activation = "softmax")
  }

  # 2. Define a kerasnip model specification
  create_keras_sequential_spec(
    model_name = "my_mlp_grid_3",
    layer_blocks = list(
      input = input_block,
      hidden = hidden_block,
      output = output_block
    ),
    mode = "classification"
  )

  mlp_spec <- my_mlp_grid_3(
    hidden_units = tune(),
    compile_loss = "categorical_crossentropy",
    compile_optimizer = "adam"
  )

  # 3. Create a hyperparameter grid
  param_grid <- tibble::tibble(
    hidden_units = c(32, 64, -10)
  )

  # 4. Prepare dummy data
  x_train <- matrix(rnorm(100 * 10), ncol = 10)
  y_train <- factor(sample(0:1, 100, replace = TRUE))

  # 5. Compile models over the grid
  compiled_grid <- compile_keras_grid(
    spec = mlp_spec,
    grid = param_grid,
    x = x_train,
    y = y_train
  )

  # 6. Inform about errors
  inform_errors(compiled_grid)
  remove_keras_spec("my_mlp_grid_3")
}


Remap Layer Block Arguments for Model Specification

Description

Creates a wrapper function around a Keras layer block to rename its arguments. This is a powerful helper for defining the layer_blocks in create_keras_functional_spec() and create_keras_sequential_spec(), allowing you to connect reusable blocks into a model graph without writing verbose anonymous functions.

Usage

inp_spec(block, input_map)

Arguments

block

A function that defines a Keras layer or a set of layers. The first arguments should be the input tensor(s).

input_map

A single character string or a named character vector that specifies how to rename/remap the arguments of block.

Details

inp_spec() makes your model definitions cleaner and more readable. It handles the metaprogramming required to create a new function with the correct argument names, while preserving the original block's hyperparameters and their default values.

The function supports two modes of operation based on input_map:

  1. Single Input Renaming: If input_map is a single character string, the wrapper function renames the first argument of the block function to the provided string. This is the common case for blocks that take a single tensor input.

  2. Multiple Input Mapping: If input_map is a named character vector, the names must match the argument names of block and each value must be the name of an upstream layer block whose output should be fed into that argument. This orientation matches the syntax (e.g., c(numeric = "processed_numerical")). This is used for blocks with multiple inputs, like a concatenation layer.

Note: Prior releases accepted the opposite orientation (c(processed_numerical = "numeric")). Existing code written in that style must flip the names/values when upgrading to this version.

Value

A new function (a closure) that wraps the block function with renamed arguments, ready to be used in a layer_blocks list.

Examples


# --- Example Blocks ---
# A standard dense block with one input tensor and one hyperparameter.
dense_block <- function(tensor, units = 16) {
  tensor |> keras3::layer_dense(units = units, activation = "relu")
}

# A block that takes two tensors as input.
concat_block <- function(input_a, input_b) {
  keras3::layer_concatenate(list(input_a, input_b))
}

# An output block with one input.
output_block <- function(tensor) {
  tensor |> keras3::layer_dense(units = 1)
}

# --- Usage ---
layer_blocks <- list(
  main_input = keras3::layer_input,
  path_a = inp_spec(dense_block, "main_input"),
  path_b = inp_spec(dense_block, "main_input"),
  concatenated = inp_spec(
    concat_block,
    c(input_a = "path_a", input_b = "path_b")
  ),
  output = inp_spec(output_block, "concatenated")
)


Full Conformal Inference Method for kerasnip_output_view Objects

Description

Full (refit-per-candidate) conformal intervals for one output of a multi-output fit. This is kerasnip's own implementation (see the design note above kerasnip_mold_outcome_names()), not a reuse of probably's private internals, since those assume a single-outcome fit throughout. Only control$method = "grid" is supported.

Usage

## S3 method for class 'kerasnip_output_view'
int_conformal_full(object, train_data, ..., control = NULL)

Arguments

object

A kerasnip_output_view viewing a regression output.

train_data

The training data used to fit object's underlying model.

...

Not used.

control

A probably::control_conformal_full() object; defaults to method = "grid" if not supplied.

Value

A kerasnip_conformal_full/int_conformal_full object; call predict() on it to get intervals for new data.


Full Conformal Inference Method for kerasnip_step_view Objects

Description

Full (refit-per-candidate) conformal intervals for one forecast step of a multistep fit. Requires step_lead() and step_sequence() to share a single source column (true of every multistep model built with this package's own examples/vignette); see the design note above kerasnip_step_recipe_step(). Only control$method = "grid" is supported.

Usage

## S3 method for class 'kerasnip_step_view'
int_conformal_full(object, train_data, ..., control = NULL)

Arguments

object

A kerasnip_step_view.

train_data

The raw training data used to fit object's underlying model.

...

Not used.

control

A probably::control_conformal_full() object; defaults to method = "grid" if not supplied.

Value

A kerasnip_conformal_full_step/int_conformal_full object; call predict() on it to get intervals for new data (a raw continuation of train_data).


Split Conformal Inference Method for kerasnip_output_view Objects

Description

Calibration-set conformal intervals for one output of a multi-output fit. Mirrors probably's own (private) int_conformal_split.workflow(), using only hardhat::extract_mold() and generics::augment() (both implemented for this class), rather than probably's unexported internals.

Usage

## S3 method for class 'kerasnip_output_view'
int_conformal_split(object, cal_data, ...)

Arguments

object

A kerasnip_output_view.

cal_data

A data frame of calibration predictors and truth.

...

Not used.

Value

A conformal_reg_split/int_conformal_split object; predict() on it (from probably) works unmodified, since it dispatches back to predict.kerasnip_output_view().


Split Conformal Inference Method for kerasnip_step_view Objects

Description

Calibration-set conformal intervals for one forecast step of a multistep fit. Mirrors probably's own (private) int_conformal_split.workflow(), using only generics::augment() (implemented for this class via kerasnip_step_truth()), rather than probably's unexported internals.

Usage

## S3 method for class 'kerasnip_step_view'
int_conformal_split(object, cal_data, ...)

Arguments

object

A kerasnip_step_view.

cal_data

A data frame of raw calibration predictors (and the original outcome column step_lead() was applied to).

...

Not used.

Value

A conformal_reg_split/int_conformal_split object; predict() on it (from probably) works unmodified, since it dispatches back to predict.kerasnip_step_view().


Evaluate a Kerasnip Model

Description

This function provides an keras_evaluate() method for model_fit objects created by kerasnip. It preprocesses the new data into the format expected by Keras and then calls keras3::evaluate() on the underlying model to compute the loss and any other metrics.

Usage

keras_evaluate(object, x, y = NULL, ...)

Arguments

object

A model_fit object produced by a kerasnip specification.

x

A data frame or matrix of new predictor data.

y

A vector or data frame of new outcome data corresponding to x.

...

Additional arguments passed on to keras3::evaluate() (e.g., batch_size).

Details

Evaluate a Fitted Kerasnip Model on New Data

Value

A named list containing the evaluation results (e.g., loss, accuracy). The names are determined by the metrics the model was compiled with.

Examples


if (requireNamespace("keras3", quietly = TRUE)) {
library(keras3)
library(parsnip)

# 1. Define layer blocks
input_block <- function(model, input_shape) {
  keras_model_sequential(input_shape = input_shape)
}
hidden_block <- function(model, units = 32) {
  model |> layer_dense(units = units, activation = "relu")
}
output_block <- function(model, num_classes) {
  model |> layer_dense(units = num_classes, activation = "softmax")
}

# 2. Define and fit a model ----
create_keras_sequential_spec(
  model_name = "my_mlp_tools",
  layer_blocks = list(
    input = input_block,
    hidden = hidden_block,
    output = output_block
  ),
  mode = "classification"
)

mlp_spec <- my_mlp_tools(
  hidden_units = 32,
  compile_loss = "categorical_crossentropy",
  compile_optimizer = "adam",
  compile_metrics = "accuracy",
  fit_epochs = 5
) |> set_engine("keras")

x_train <- matrix(rnorm(100 * 10), ncol = 10)
y_train <- factor(sample(0:1, 100, replace = TRUE))
train_df <- data.frame(x = I(x_train), y = y_train)

fitted_mlp <- fit(mlp_spec, y ~ x, data = train_df)

# 3. Evaluate the model on new data ----
x_test <- matrix(rnorm(50 * 10), ncol = 10)
y_test <- factor(sample(0:1, 50, replace = TRUE))

eval_metrics <- keras_evaluate(fitted_mlp, x_test, y_test)
print(eval_metrics)

# 4. Extract the Keras model object ----
keras_model <- extract_keras_model(fitted_mlp)
summary(keras_model)

# 5. Extract the training history ----
history <- extract_keras_history(fitted_mlp)
plot(history)
remove_keras_spec("my_mlp_tools")
}


Dynamically Discovered Keras Objects

Description

These exported vectors contain the names of optimizers, losses, and metrics discovered from the installed keras3 package when kerasnip is loaded. This ensures that kerasnip is always up-to-date with your Keras version.

Usage

keras_optimizers

keras_losses

keras_metrics

Details

These objects are primarily used to provide the default values for the dials parameter functions, optimizer_function() and loss_function_keras(). This allows for tab-completion in IDEs and validation of optimizer and loss names when tuning models.

The discovery process in .onLoad() scrapes the keras3 namespace for functions matching ⁠optimizer_*⁠, ⁠loss_*⁠, and ⁠metric_*⁠ patterns.


Attach a tailor Post-Processor to One Output or Step of a Multi-Output or Multistep Workflow

Description

workflows::add_tailor() cannot be used on a kerasnip multi-output or multistep workflow: tailor::fit() selects outcome/estimate via [[, which requires exactly one, flat, numeric column, and both a multi-output recipe (output_1 + output_2 ~ .) and a multistep model's nested .pred list-column violate that (see vignette("multi_output_postprocessing")). kerasnip_add_tailor() is a kerasnip-owned analogue that attaches a tailor post-processor to a single named output or forecast step, using kerasnip_output_view() or kerasnip_step_view() internally.

Usage

kerasnip_add_tailor(x, tailor, output = NULL, step = NULL, var = NULL)

Arguments

x

An unfitted workflow whose model has more than one outcome (multi-output) or is a multistep forecasting model.

tailor

A tailor::tailor() specification.

output

A string, the name of the outcome column to post-process (multi-output models).

step

An integer, the forecast step to post-process (multistep models).

var

A string, the forecasted variable to post-process; only needed with step if the model forecasts more than one variable.

Details

At fit() time, the underlying model is trained as usual; the relevant view is then used to fit the tailor against that output's/step's predictions (on data_calibration if supplied, otherwise on data, mirroring workflows::add_tailor()'s data-usage convention). At predict() time, the full prediction is generated, the target output's/step's value(s) are replaced with the tailor-adjusted values, and everything else (other outputs; other steps in the same nested tibble) is left untouched.

Exactly one of output or step must be supplied: output for a multi-output model, step (and var, if more than one variable is forecast) for a multistep model.

Value

A kerasnip_tailored_workflow, to be trained with fit().

Examples

## Not run: 
tlr <- tailor::tailor() |> tailor::adjust_numeric_calibration()

# multi-output
tailored_wf <- kerasnip_add_tailor(wf, tlr, output = "output_1")

# multistep
tailored_wf <- kerasnip_add_tailor(wf, tlr, step = 2)

fit_obj <- fit(tailored_wf, data = train_data, data_calibration = cal_data)
predict(fit_obj, new_data = test_data)

## End(Not run)

View a Single Output of a Multi-Output kerasnip Fit

Description

tailor and probably are built around models with a single outcome column and a single .pred/.pred_class prediction column. A kerasnip multi-output model (e.g. a recipe with output_1 + output_2 ~ .) instead produces .pred_output_1, .pred_output_2, ... columns from multiple truth columns in one fit — the standard parsnip::maybe_multivariate() shape, but one tailor::fit()/workflows::add_tailor() call cannot consume it (it selects outcome/estimate via [[, which requires exactly one column).

kerasnip_output_view() wraps a fitted multi-output workflow together with one output name, presenting it as if it were an ordinary single-output fit: predict() returns standard .pred / .pred_class / ⁠.pred_<level>⁠ columns for that output alone, letting you calibrate or post-process each output separately with the usual tailor/probably calls (see vignette("multi_output_postprocessing")).

Usage

kerasnip_output_view(x, output)

Arguments

x

A fitted (trained) workflow whose model has more than one outcome column.

output

A string, the name of the outcome column to view.

Value

A kerasnip_output_view object.

Examples

## Not run: 
fit_obj <- fit(wf, data = train_data) # wf predicts output_1 and output_2
view_1 <- kerasnip_output_view(fit_obj, "output_1")
predict(view_1, new_data = test_data) # -> a single `.pred` column

## End(Not run)

Recover Truth Values for a Multistep Forecast Step

Description

A multistep model's per-step outcome columns (e.g. lead_2_value) are engineered by step_lead() from a single raw column, so they are not present in a user's raw data the way genuine multi-output columns are. This re-bakes the fitted recipe on new_data to recover the actual future value at kerasnip_step_view()'s step, for calibration/interval use. Rows too close to the end of new_data for the lead to be computed return NA (dropped automatically by calibration routines that call sort()/stats::complete.cases() on the result).

Usage

kerasnip_step_truth(view, new_data)

Arguments

view

A kerasnip_step_view.

new_data

A data frame of raw predictors (and the original outcome column step_lead() was applied to).

Value

A numeric vector, one truth value per row of new_data.


View a Single Forecast Step of a Multistep kerasnip Fit

Description

A kerasnip multistep (vector-valued) regression model returns a nested .pred list-column: one inner tibble per row, with a .step column plus one prediction column per forecasted variable. tailor/probably expect a single flat numeric .pred column instead — tailor::check_variable_type() requires is.numeric() on the outcome/estimate columns, which a list-column fails outright.

kerasnip_step_view() wraps a fitted multistep workflow together with one forecast step (and, if more than one variable is forecast, which variable), presenting it as an ordinary single-output fit: predict() returns a flat .pred column for that step alone.

Usage

kerasnip_step_view(x, step, var = NULL)

Arguments

x

A fitted (trained) workflow whose model is a multistep regression model (see create_keras_sequential_spec()/ create_keras_functional_spec() with a vector-valued output).

step

An integer, the forecast step to view.

var

A string, the forecasted variable to view. Required only if the model forecasts more than one variable; inferred otherwise.

Details

Unlike kerasnip_output_view(), a multistep model's per-step outcome columns (e.g. lead_1_value) are recipe-engineered from a single raw column via step_lead() — they are not present in a user's raw data the way genuine multi-output columns are. kerasnip_step_truth() recovers the true future value at a given step by re-baking the fitted recipe on raw data, which is what int_conformal_split() uses internally for this class.

probably::int_conformal_full() is also supported (see int_conformal_full.kerasnip_step_view()), with a materially different design from kerasnip_output_view()'s: refitting for a candidate value at this step means substituting it into the single raw column step_lead() derives every step's truth from, which shifts every nearby row's target too. It is only supported when step_lead() and step_sequence() share a single source column, matching all of kerasnip's own multistep examples.

Value

A kerasnip_step_view object.

Examples

## Not run: 
fit_obj <- fit(wf, data = train_data) # a multistep forecasting workflow
step_2 <- kerasnip_step_view(fit_obj, step = 2)
predict(step_2, new_data = test_data) # -> a single `.pred` column

## End(Not run)

Predict Confidence Intervals for Classification via LLA

Description

Predict-time entry point for classification confidence intervals. Called by parsnip via c(pkg = "kerasnip", fun = "laplace_conf_int_cls").

For each output, this uses Monte Carlo sampling from the Laplace posterior over logits, transforms to probability scale via sigmoid / softmax, and returns per-class quantile-based intervals.

Usage

laplace_conf_int_cls(object, x, laplace_data, lvl, level = 0.95)

Arguments

object

The raw Keras model (from object$fit$fit).

x

Processed predictor data (matrix or array).

laplace_data

A named list of Laplace posterior data (from object$fit$laplace).

lvl

Character vector of class level names (from object$fit$lvl).

level

Confidence level (default 0.95).

Value

For single-output: a data frame with per-class .pred_lower_Level and .pred_upper_Level columns.


Predict Confidence Intervals via Last-Layer Laplace Approximation

Description

Predict-time entry point for regression confidence intervals. Called by parsnip via c(pkg = "kerasnip", fun = "laplace_conf_int_reg").

For each output in the model, this builds the per-sample epistemic variance (uncertainty on E[Y|X]) from the stored Laplace posterior and returns symmetric Normal-based intervals at the requested confidence level.

Usage

laplace_conf_int_reg(object, x, laplace_data, level = 0.95)

Arguments

object

The raw Keras model (from object$fit$fit).

x

Processed predictor data (matrix or array).

laplace_data

A named list of Laplace posterior data, one entry per output (from object$fit$laplace). Each entry contains h_diag, tau, sigma_sq_noise, n_training, and combined_model.

level

Confidence level (default 0.95). Passed through from predict(..., type = "conf_int", level = 0.95).

Value

A named list of matrices (one per output), each with columns .pred, .pred_lower, and .pred_upper.


Predict Prediction Intervals for Classification via LLA

Description

Predict-time entry point for classification prediction intervals. Called by parsnip via c(pkg = "kerasnip", fun = "laplace_pred_int_cls").

After computing epistemic probability samples (as in conf_int), this draws class labels from Bernoulli(p_sample) or Categorical(p_sample) and returns per-class quantiles of the resulting indicator samples — matching the posterior predictive behaviour of Stan and BART classification engines.

Usage

laplace_pred_int_cls(object, x, laplace_data, lvl, level = 0.95)

Arguments

object

The raw Keras model (from object$fit$fit).

x

Processed predictor data (matrix or array).

laplace_data

A named list of Laplace posterior data (from object$fit$laplace).

lvl

Character vector of class level names (from object$fit$lvl).

level

Confidence level (default 0.95).

Value

For single-output: a data frame with per-class .pred_lower_Level and .pred_upper_Level columns.


Predict Prediction Intervals via Last-Layer Laplace Approximation

Description

Predict-time entry point for regression prediction intervals. Called by parsnip via c(pkg = "kerasnip", fun = "laplace_pred_int_reg").

For each output in the model, this builds the per-sample predictive variance (uncertainty on a new observation Y|X = epistemic variance + observation noise) from the stored Laplace posterior and returns symmetric Normal-based intervals at the requested level.

Usage

laplace_pred_int_reg(object, x, laplace_data, level = 0.95)

Arguments

object

The raw Keras model (from object$fit$fit).

x

Processed predictor data (matrix or array).

laplace_data

A named list of Laplace posterior data, one entry per output (from object$fit$laplace). Each entry contains h_diag, tau, sigma_sq_noise, n_training, and combined_model.

level

Confidence level (default 0.95). Passed through from predict(..., type = "conf_int", level = 0.95).

Value

A named list of matrices (one per output), each with columns .pred, .pred_lower, and .pred_upper.


Dials Parameter for Keras Loss Functions

Description

Dials Parameter for Keras Loss Functions

Usage

loss_function_keras(values = NULL)

Arguments

values

A character vector of possible loss functions. Defaults to all known losses (keras defaults + custom registered).

Value

A dials parameter object for Keras loss.


Check if a Kerasnip Model Specification Exists

Description

This is an internal helper function to check if a model specification has been registered in the parsnip model environment.

Usage

model_exists(model_name)

Arguments

model_name

A character string giving the name of the model specification function to check (e.g., "my_mlp").

Value

A logical value, TRUE if the model exists, FALSE otherwise.

Examples


if (requireNamespace("parsnip", quietly = TRUE)) {
  library(parsnip)

  # Check for a model that exists in parsnip
  model_exists("mlp")

  # Check for a model that does not exist
  model_exists("non_existent_model")
}


Dials Parameter for Keras Optimizers

Description

Dials Parameter for Keras Optimizers

Usage

optimizer_function(values = NULL)

Arguments

values

A character vector of possible optimizers. Defaults to all known optimizers (keras defaults + custom registered).

Value

A dials parameter object for Keras optimizers.


Predict Method for kerasnip_conformal_full Objects

Description

Computes full-conformal intervals for new_data, one grid search per row via kerasnip_grid_one_output_view().

Usage

## S3 method for class 'kerasnip_conformal_full'
predict(object, new_data, level = 0.95, ...)

Arguments

object

A kerasnip_conformal_full object, from int_conformal_full.kerasnip_output_view().

new_data

A data frame of predictors.

level

The conformal level.

...

Not used.

Value

A tibble with .pred_lower/.pred_upper columns, one row per row of new_data.


Predict Method for kerasnip_conformal_full_step Objects

Description

Computes full-conformal intervals for new_data (a raw continuation of the training data), one grid search per surviving window via kerasnip_grid_one_step_view().

Usage

## S3 method for class 'kerasnip_conformal_full_step'
predict(object, new_data, level = 0.95, ...)

Arguments

object

A kerasnip_conformal_full_step object, from int_conformal_full.kerasnip_step_view().

new_data

Raw data continuing the training series.

level

The conformal level.

...

Not used.

Value

A tibble with .pred_lower/.pred_upper columns, one row per window that survives step_sequence()'s history requirement.


Predict Method for kerasnip Model Fits

Description

S3 method for predict() dispatched on kerasnip_model_fit objects. Before delegating to the standard parsnip predict machinery, it checks whether the underlying model type is registered in the current parsnip session. If not (e.g. after loading a saved workflow in a new R session), it transparently replays the full parsnip registration using metadata stored on the spec object — requiring no manual step from the user.

Usage

## S3 method for class 'kerasnip_model_fit'
predict(object, new_data, ...)

Arguments

object

A kerasnip_model_fit object.

new_data

A data frame of predictors.

...

Passed to the parsnip predict method.

Details

The metadata needed for re-registration (kerasnip_layer_blocks, kerasnip_functional) is embedded on the spec object by the spec constructor function at call time. This means it is preserved across saveRDS()/readRDS() and bundle()/unbundle() round-trips.

For full model weight portability (i.e. to be able to predict() on new data in a new R session), use bundle::bundle() before saving. Plain saveRDS() preserves the spec structure and will auto-register, but the underlying Keras model weights are not portable without bundling.

Value

A tibble of predictions.


Predict Method for kerasnip_output_view Objects

Description

Predicts from the wrapped multi-output workflow, then selects and renames object$output's columns down to the standard single-output shape (.pred, .pred_class, ⁠.pred_<level>⁠, or .pred/.pred_lower/ .pred_upper), so the result reads like a single-output predict() call.

Usage

## S3 method for class 'kerasnip_output_view'
predict(object, new_data, type = NULL, ...)

Arguments

object

A kerasnip_output_view.

new_data

A data frame of predictors.

type

One of "numeric", "class", "prob", "conf_int", or "pred_int". Defaults to "class" for a classification view, "numeric" otherwise.

...

Passed to predict() on the wrapped workflow.

Value

A tibble in the standard single-output prediction shape.


Predict Method for kerasnip_step_view Objects

Description

Predicts from the wrapped multistep workflow, then extracts object$step's (and, if set, object$var's) value from every row's nested .pred tibble into a flat column, so the result reads like a single-output predict() call.

Usage

## S3 method for class 'kerasnip_step_view'
predict(object, new_data, type = "numeric", ...)

Arguments

object

A kerasnip_step_view.

new_data

A data frame of predictors.

type

One of "numeric", "conf_int", or "pred_int".

...

Passed to predict() on the wrapped workflow.

Value

A tibble with a .pred column ("numeric"), or .pred/ .pred_lower/.pred_upper ("conf_int"/"pred_int").


Predict Method for kerasnip_tailored_fit Objects

Description

Predicts from the underlying full workflow, applies the fitted tailor to the target output's/step's predictions, and splices the adjusted values back in: ⁠.pred_<output>⁠/⁠.pred_class_<output>⁠-suffixed columns for a multi-output model, or the matching .step entry in every row's nested tibble for a multistep model. Every other output/step is returned exactly as a plain predict() on the underlying fit would give it.

Usage

## S3 method for class 'kerasnip_tailored_fit'
predict(object, new_data, ...)

Arguments

object

A kerasnip_tailored_fit, from fit() on a kerasnip_tailored_workflow.

new_data

A data frame of predictors.

...

Not used.

Value

A tibble in the full multi-output/multistep prediction shape.


Process Predictor Input for Keras (Functional API)

Description

Preprocesses predictor data (x) into a format suitable for Keras models built with the Functional API. Handles both tabular data and list-columns of arrays (e.g., for images), supporting multiple inputs.

Usage

process_x_functional(x)

Arguments

x

A data frame or matrix of predictors.

Value

A list containing:


Process Predictor Input for Keras

Description

Preprocesses predictor data (x) into a format suitable for Keras models. Handles both tabular data and list-columns of arrays (e.g., for images).

Usage

process_x_sequential(x)

Arguments

x

A data frame or matrix of predictors.

Value

A list containing:


Process Outcome Input for Keras (Functional API)

Description

Preprocesses outcome data (y) into a format suitable for Keras models built with the Functional API. Handles both regression (numeric) and classification (factor) outcomes, including one-hot encoding for classification, and supports multiple outputs.

Usage

process_y_functional(
  y,
  is_classification = NULL,
  class_levels = NULL,
  layer_blocks = NULL
)

Arguments

y

A vector or data frame of outcomes.

is_classification

Logical, optional. If TRUE, treats y as classification. If FALSE, treats as regression. If NULL (default), it's determined from is.factor(y).

class_levels

Character vector, optional. The factor levels for classification outcomes. If NULL (default), determined from levels(y).

layer_blocks

A named list of layer block functions, optional. Used to disambiguate a multi-column y between the "N independent named output heads" case (one block per column name, e.g. output_1, output_2) and the "single vector-valued output" case (e.g. multi-step regression, a single block named "output" with units = ncol(y)). If NULL (default, and for any caller that predates this parameter), the original per-column-split behavior is preserved.

Value

A list containing:


Process Outcome Input for Keras

Description

Preprocesses outcome data (y) into a format suitable for Keras models. Handles both regression (numeric) and classification (factor) outcomes, including one-hot encoding for classification.

Usage

process_y_sequential(y, is_classification = NULL, class_levels = NULL)

Arguments

y

A vector of outcomes.

is_classification

Logical, optional. If TRUE, treats y as classification. If FALSE, treats as regression. If NULL (default), it's determined from is.factor(y).

class_levels

Character vector, optional. The factor levels for classification outcomes. If NULL (default), determined from levels(y).

Value

A list containing:


Register a Custom Keras Loss

Description

Allows users to register a custom loss function so it can be used by name within kerasnip model specifications and tuned with dials.

Usage

register_keras_loss(name, loss_fn)

Arguments

name

The name to register the loss under (character).

loss_fn

The loss function.

Details

Registered losses are stored in an internal environment. When a model is compiled, kerasnip will first check this internal registry for a loss matching the provided name before checking the keras3 package.

Value

No return value, called for side effects.

See Also

register_keras_optimizer(), register_keras_metric()


Register a Custom Keras Metric

Description

Allows users to register a custom metric function so it can be used by name within kerasnip model specifications.

Usage

register_keras_metric(name, metric_fn)

Arguments

name

The name to register the metric under (character).

metric_fn

The metric function.

Details

Registered metrics are stored in an internal environment. When a model is compiled, kerasnip will first check this internal registry for a metric matching the provided name before checking the keras3 package.

Value

No return value, called for side effects.

See Also

register_keras_optimizer(), register_keras_loss()


Register a Custom Keras Optimizer

Description

Allows users to register a custom optimizer function so it can be used by name within kerasnip model specifications and tuned with dials.

Usage

register_keras_optimizer(name, optimizer_fn)

Arguments

name

The name to register the optimizer under (character).

optimizer_fn

The optimizer function. It should return a Keras optimizer object.

Details

Registered optimizers are stored in an internal environment. When a model is compiled, kerasnip will first check this internal registry for an optimizer matching the provided name before checking the keras3 package.

The optimizer_fn can be a simple function or a partially applied function using purrr::partial(). This is useful for creating versions of Keras optimizers with specific settings.

Value

No return value, called for side effects.

See Also

register_keras_loss(), register_keras_metric()

Examples

if (requireNamespace("keras3", quietly = TRUE)) {
  # Register a custom version of Adam with a different default beta_1
  my_adam <- purrr::partial(keras3::optimizer_adam, beta_1 = 0.8)
  register_keras_optimizer("my_adam", my_adam)

  # Now "my_adam" can be used as a string in a model spec, e.g.,
  # my_model_spec(compile_optimizer = "my_adam")
}

Remove a Keras Model Specification and its Registrations

Description

This function completely removes a model specification that was previously created by create_keras_sequential_spec() or create_keras_functional_spec(). It cleans up both the function in the user's environment and all associated registrations within the parsnip package.

Usage

remove_keras_spec(model_name, env = parent.frame())

Arguments

model_name

A character string giving the name of the model specification function to remove (e.g., "my_mlp").

env

The environment from which to remove the function and its update() method. Defaults to the calling environment (parent.frame()).

Details

This function is essential for cleanly unloading a dynamically created model. It performs three main actions:

  1. It removes the model specification function (e.g., my_mlp()) and its corresponding update() method from the specified environment.

  2. It searches parsnip's internal model environment for all objects whose names start with the model_name and removes them. This purges the fit methods, argument definitions, and other registrations.

  3. It removes the model's name from parsnip's master list of models.

This function uses the un-exported get_model_env() to perform the cleanup.

Value

Invisibly returns TRUE after attempting to remove the objects.

See Also

create_keras_sequential_spec(), create_keras_functional_spec()

Examples


if (requireNamespace("keras3", quietly = TRUE)) {
  # First, create a dummy spec
  input_block <- function(model, input_shape) {
    keras3::keras_model_sequential(input_shape = input_shape)
  }
  dense_block <- function(model, units = 16) {
    model |> keras3::layer_dense(units = units)
  }
  create_keras_sequential_spec(
    "my_temp_model",
    list(
      input = input_block,
      dense = dense_block
    ),
    "regression"
  )

  # Check it exists in the environment and in parsnip
  exists("my_temp_model")
  "my_temp_model" %in% parsnip::show_engines("my_temp_model")$model

  # Now remove it
  remove_keras_spec("my_temp_model")

  # Check it's gone
  !exists("my_temp_model")
  !model_exists("my_temp_model")
}


set_args Method for kerasnip Spec Objects

Description

S3 method for set_args() dispatched on kerasnip_spec objects. parsnip::set_args.model_spec() calls new_model_spec(), which strips any extra classes and attributes. This wrapper saves and re-attaches the kerasnip_layer_blocks and kerasnip_functional metadata attributes (and the kerasnip_spec class) after NextMethod() has done its work.

Usage

## S3 method for class 'kerasnip_spec'
set_args(object, ...)

Arguments

object

A kerasnip_spec model specification.

...

Named model arguments to update, passed to parsnip::set_args.model_spec().

Value

A model_spec object with the kerasnip_spec class and metadata attributes re-attached.


set_engine Method for kerasnip Spec Objects

Description

S3 method for set_engine() dispatched on kerasnip_spec objects. parsnip::set_engine.model_spec() internally calls new_model_spec(), which re-creates the spec from scratch with only c(cls, "model_spec") as the class vector — stripping kerasnip_spec and any custom attributes. This wrapper preserves the kerasnip_layer_blocks and kerasnip_functional metadata attributes and re-attaches them (along with the kerasnip_spec class) after NextMethod() has done its work.

Usage

## S3 method for class 'kerasnip_spec'
set_engine(object, engine, ...)

Arguments

object

A kerasnip_spec model specification.

engine

A character string naming the engine (e.g., "keras").

...

Additional engine-specific arguments passed to parsnip::set_engine.model_spec().

Value

A model_spec object with the kerasnip_spec class and metadata attributes re-attached.


Collapse Predictors into a single list-column

Description

step_collapse() creates a a specification of a recipe step that will convert a group of predictors into a single list-column. This is useful for custom models that need the predictors in a different format.

Usage

step_collapse(
  recipe,
  ...,
  role = "predictor",
  trained = FALSE,
  columns = NULL,
  new_col = "predictor_matrix",
  skip = FALSE,
  id = recipes::rand_id("collapse")
)

Arguments

recipe

A recipe object. The step will be added to the sequence of operations for this recipe.

...

One or more selector functions to choose which variables are affected by the step. See ⁠[selections()]⁠ for more details. For the tidy method, these are not currently used.

role

For model terms created by this step, what analysis role should they be assigned?. By default, the new columns are used as predictors.

trained

A logical to indicate if the quantities for preprocessing have been estimated.

columns

A character string of the selected variable names. This is NULL until the step is trained by ⁠[prep.recipe()]⁠.

new_col

A character string for the name of the new list-column. The default is "predictor_matrix".

skip

A logical. Should the step be skipped when the recipe is baked by ⁠[bake.recipe()]⁠? While all operations are baked when prep is run, skipping when bake is run may be other times when it is desirable to skip a processing step.

id

A character string that is unique to this step to identify it.

Value

An updated version of recipe with the new step added to the sequence of existing steps (if any). For the tidy method, a tibble with columns terms (the selected column names), value (the name of the destination list-column), and id (the step identifier).

Examples

library(recipes)

# 2 predictors
dat <- data.frame(
  x1 = 1:10,
  x2 = 11:20,
  y = 1:10
)

rec <- recipe(y ~ ., data = dat) %>%
  step_collapse(x1, x2, new_col = "pred") %>%
  prep()

bake(rec, new_data = NULL)

Create a Lead Predictor

Description

step_lead() creates a specification of a recipe step that will create one or more new columns of data that are leading (i.e. future) values of existing columns. This is the target-side companion to ⁠[recipes::step_lag()]⁠ (which only supports positive lag/past values, not lead/future values) and is intended for building multi-step-ahead forecasting targets, e.g. step_lead(y, lead = 1:6) produces the next six values of y as separate columns, one per row.

Usage

step_lead(
  recipe,
  ...,
  lead = 1,
  prefix = "lead_",
  default = NA,
  role = "outcome",
  trained = FALSE,
  columns = NULL,
  keep_original_cols = TRUE,
  skip = FALSE,
  id = recipes::rand_id("lead")
)

Arguments

recipe

A recipe object. The step will be added to the sequence of operations for this recipe.

...

One or more selector functions to choose which variables are leading. See ⁠[selections()]⁠ for more details. For the tidy method, these are not currently used.

lead

A vector of nonnegative integers. Each value produces a leading column for each selected variable.

prefix

A prefix added to the leading columns names. The default naming convention is ⁠<prefix><lead value>_<original variable name>⁠, e.g. lead_1_value.

default

Value to fill in the trailing rows that don't have a complete future window (analogous to default in ⁠[recipes::step_lag()]⁠). Defaults to NA.

role

For model terms created by this step, what analysis role should they be assigned?. By default, the new columns are used as outcomes.

trained

A logical to indicate if the quantities for preprocessing have been estimated.

columns

A character string of the selected variable names. This is NULL until the step is trained by ⁠[prep.recipe()]⁠.

keep_original_cols

A logical to keep the original variables in the output. Defaults to TRUE.

skip

A logical. Should the step be skipped when the recipe is baked by ⁠[bake.recipe()]⁠? While all operations are baked when prep is run, skipping when bake is run may be other times when it is desirable to skip a processing step.

id

A character string that is unique to this step to identify it.

Details

Combine with ⁠[recipes::step_naomit()]⁠ (e.g. step_naomit(starts_with(prefix))) to drop the trailing rows that don't have a full future window, mirroring how ⁠[step_sequence()]⁠'s padding = "drop" removes rows lacking a full past window.

Value

An updated version of recipe with the new step added to the sequence of existing steps (if any). For the tidy method, a tibble with columns terms (the selected column names), value (the name of the resulting leading column), and id (the step identifier).

Examples

library(recipes)

dat <- data.frame(y = 1:10)

rec <- recipe(y ~ ., data = dat) %>%
  step_lead(y, lead = 1:2) %>%
  prep()

bake(rec, new_data = NULL)

Build a Sliding Window of Predictors for Sequence Models

Description

step_sequence() creates a specification of a recipe step that converts one or more ordered numeric predictor columns into a single list-column of ⁠(timesteps, features)⁠ matrices, one per row. This is the shape expected by recurrent layer blocks (e.g. keras3::layer_lstm(), keras3::layer_gru()) used with create_keras_functional_spec() or create_keras_sequential_spec().

Usage

step_sequence(
  recipe,
  ...,
  timesteps,
  role = "predictor",
  trained = FALSE,
  columns = NULL,
  new_col = "sequence_matrix",
  padding = c("drop", "zero"),
  skip = FALSE,
  id = recipes::rand_id("sequence")
)

Arguments

recipe

A recipe object. The step will be added to the sequence of operations for this recipe.

...

One or more selector functions to choose which (already time-ordered) numeric variables are windowed. See ⁠[selections()]⁠ for more details. All selected columns become "features" in the resulting window. For the tidy method, these are not currently used.

timesteps

A single integer. The sliding window length (number of past rows, including the current one) to include in each window.

role

For model terms created by this step, what analysis role should they be assigned?. By default, the new column is used as a predictor.

trained

A logical to indicate if the quantities for preprocessing have been estimated.

columns

A character string of the selected variable names. This is NULL until the step is trained by ⁠[prep.recipe()]⁠.

new_col

A character string for the name of the new list-column. The default is "sequence_matrix".

padding

One of "drop" (default) or "zero". Rows without a full timesteps history need special handling: "drop" removes them from the data (as ⁠[recipes::step_naomit()]⁠ does), while "zero" left-pads the missing history with rows of zeros so no rows are dropped.

skip

A logical. Should the step be skipped when the recipe is baked by ⁠[bake.recipe()]⁠? While all operations are baked when prep is run, skipping when bake is run may be other times when it is desirable to skip a processing step.

id

A character string that is unique to this step to identify it.

Value

An updated version of recipe with the new step added to the sequence of existing steps (if any). For the tidy method, a tibble with columns terms (the selected column names), value (the name of the destination list-column), timesteps, and id (the step identifier).

Examples

library(recipes)

dat <- data.frame(x1 = 1:10, x2 = 11:20, y = 1:10)

rec <- recipe(y ~ ., data = dat) %>%
  step_sequence(x1, x2, timesteps = 3, new_col = "window") %>%
  prep()

bake(rec, new_data = NULL)

Tidy a Fitted Kerasnip Model

Description

Returns a tibble with one row per layer of the underlying Keras model, summarising the layer name, Python class, and parameter count.

Usage

## S3 method for class 'kerasnip_model_fit'
tidy(x, ...)

Arguments

x

A kerasnip_model_fit object.

...

Not used.

Value

A tibble with columns layer (character), class (character), and n_params (integer).