This function takes a model specification and a recipe, fits the model on the training data, and returns predictions on the testing data.
Examples
# Example usage of the `train_and_predict` function
library(testthat)
library(parsnip)
library(recipes)
library(workflows)
library(dplyr)
library(rsample)
set.seed(123)
data <- tibble(
class = sample(c("A", "B"), 150, replace = TRUE),
feature1 = rnorm(150),
feature2 = rnorm(150)
)
# Split the data into training and testing sets
data_split <- initial_split(data, prop = 0.8)
data_train <- training(data_split)
data_test <- testing(data_split)
# Define the model specification
model_spec <- decision_tree() %>%
set_engine("rpart") %>%
set_mode("classification")
# Define the recipe (preprocessing)
recipe <- recipe(class ~ feature1 + feature2, data = data_train) %>%
step_normalize(all_numeric())
# Run the function
predictions <- train_and_predict(model_spec, data_train, data_test, recipe)
head(predictions)
#> # A tibble: 6 × 4
#> .pred_class class feature1 feature2
#> <fct> <chr> <dbl> <dbl>
#> 1 B A 0.994 -0.789
#> 2 A B 0.548 -0.502
#> 3 B A -0.600 1.90
#> 4 B B 2.19 -0.101
#> 5 B A -0.710 -0.376
#> 6 A B 0.257 -0.562