Model Specifications with parsnip
Specify model types and engines independently from the training step.
Model Specifications with parsnip is a free R Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is parsnip?
parsnip provides a unified interface to hundreds of model engines. Instead of learning the unique syntax of each package (glm(), randomForest(), e1071::svm()), you write one consistent specification and tell parsnip which engine to use underneath.
This means you can swap engines — e.g. from glm to stan for Bayesian logistic regression — by changing one argument.
library(parsnip)
# The same interface, different engines
logistic_reg() |> set_engine('glm') # base R
logistic_reg() |> set_engine('glmnet') # regularized
logistic_reg() |> set_engine('stan') # Bayesianlogistic_reg() for Classification
logistic_reg() specifies a logistic regression model for binary classification. Chain set_engine('glm') to use R's built-in GLM engine, and set_mode('classification') to explicitly declare the task type.
The mode ('classification' or 'regression') is required for model types that support both.
log_spec <- logistic_reg() |>
set_engine('glm') |>
set_mode('classification')
print(log_spec)
# Logistic Regression Model Specification (classification)
# Computational engine: glmrand_forest() with tune()
rand_forest() specifies a random forest. Parameters like mtry (number of features per split) and trees can be fixed or set to tune() as a placeholder for hyperparameter search.
When you pass tune(), tidymodels will search over a grid of values during cross-validation tuning.
rf_spec <- rand_forest(
mtry = tune(),
trees = 500,
min_n = tune()
) |>
set_engine('ranger', importance = 'impurity') |>
set_mode('classification')
print(rf_spec)linear_reg() for Regression
linear_reg() specifies a linear regression model. Using set_engine('lm') uses ordinary least squares, while set_engine('glmnet') enables L1/L2 regularization via the penalty and mixture parameters.
# OLS linear regression
lm_spec <- linear_reg() |>
set_engine('lm')
# Ridge regression (penalty > 0, mixture = 0)
ridge_spec <- linear_reg(penalty = 0.01, mixture = 0) |>
set_engine('glmnet')
# Lasso (penalty > 0, mixture = 1)
lasso_spec <- linear_reg(penalty = tune(), mixture = 1) |>
set_engine('glmnet')boost_tree() — Gradient Boosting
boost_tree() specifies a gradient boosted tree model. You can target the xgboost, lightgbm, or C5.0 engine. Tunable parameters include tree_depth, learn_rate, and loss_reduction.
xgb_spec <- boost_tree(
trees = 500,
tree_depth = tune(),
learn_rate = tune(),
loss_reduction = tune()
) |>
set_engine('xgboost') |>
set_mode('classification')
print(xgb_spec)fit() — Train the Model
fit(spec, formula, data) trains the model specification on actual data. parsnip translates the spec into the appropriate engine call internally. The result is a fitted parsnip model object.
lm_spec <- linear_reg() |> set_engine('lm')
# Fit the model on training data
lm_fit <- fit(lm_spec, mpg ~ wt + hp + cyl, data = mtcars)
# The fitted object wraps the engine result
print(lm_fit)
# Access the underlying lm object
extract_fit_engine(lm_fit)fit_xy() — Matrix Interface
fit_xy(spec, x, y) is an alternative to fit(spec, formula, data). It accepts a predictor matrix x and a response vector y directly, which is useful when your data is already preprocessed into a numeric matrix (common with neural networks or XGBoost).
x_train <- train_baked |> select(-price)
y_train <- train_baked$price
lm_spec <- linear_reg() |> set_engine('lm')
# Matrix-style fit
lm_fit_xy <- fit_xy(lm_spec, x = x_train, y = y_train)
print(lm_fit_xy)translate() — See Engine Code
translate(spec) shows you exactly what parsnip will call under the hood for a given engine. This is invaluable for debugging or understanding how your parsnip spec maps to the engine's native interface.
rf_spec <- rand_forest(mtry = 3, trees = 500) |>
set_engine('ranger') |>
set_mode('classification')
# See what ranger() call will be generated
translate(rf_spec)
# ranger::ranger(formula = ..., data = ...,
# num.trees = 500, mtry = 3, ...)predict() with parsnip
All parsnip fitted models share the same predict() interface. For classification, type = 'class' returns the predicted class and type = 'prob' returns class probabilities. This consistency is one of parsnip's major advantages.
log_fit <- fit(logistic_reg() |> set_engine('glm') |> set_mode('classification'),
species ~ ., data = train_df)
# Predicted classes
predict(log_fit, new_data = test_df, type = 'class')
# Predicted probabilities
predict(log_fit, new_data = test_df, type = 'prob')augment() — Predictions Joined to Data
augment(fitted_model, new_data) appends prediction columns directly to the input data frame. This is convenient for evaluation: the result contains both the true values and predictions side by side, ready for metric calculations.
log_fit <- fit(
logistic_reg() |> set_engine('glm') |> set_mode('classification'),
species ~ ., data = train_df
)
# Get predictions joined to test data
results <- augment(log_fit, new_data = test_df)
head(results[, c('species', '.pred_class', '.pred_setosa')])Comparing Model Specs
One of the main benefits of parsnip is rapid model comparison. You define multiple specs, fit them all to the same data, and compare metrics. Because the interface is identical, swapping models requires changing only the spec definition.
specs <- list(
lm = linear_reg() |> set_engine('lm'),
ridge = linear_reg(penalty = 0.01, mixture = 0) |> set_engine('glmnet'),
rf = rand_forest(trees = 200) |> set_engine('ranger') |> set_mode('regression')
)
fits <- lapply(specs, fit, mpg ~ ., data = train_mtcars)
preds <- lapply(fits, predict, new_data = test_mtcars)
rmse_vals <- sapply(preds, function(p) {
sqrt(mean((p$.pred - test_mtcars$mpg)^2))
})
print(rmse_vals)Quick Check
In parsnip, what does translate(spec) return?
parsnip Recap
Key takeaways from Model Specifications with parsnip:
- parsnip provides a unified interface: specify the model type, engine, and mode separately.
set_engine()selects the underlying package;set_mode()selects classification or regression.- Use
tune()as a placeholder for hyperparameters to be searched later. fit(spec, formula, data)trains the model;fit_xy(spec, x, y)accepts matrices.predict(fit, new_data, type)is consistent across all engines.translate(spec)shows the engine call for debugging.augment(fit, new_data)appends predictions to the data frame.
# Parsnip model comparison template
spec <- rand_forest(trees = 500, mtry = tune()) |>
set_engine('ranger', importance = 'impurity') |>
set_mode('classification')
print(translate(spec))
# When mtry is fixed:
spec_fixed <- rand_forest(trees = 500, mtry = 5) |>
set_engine('ranger') |>
set_mode('classification')
fit_fixed <- fit(spec_fixed, label ~ ., data = train_df)Frequently asked questions
Is the “Model Specifications with parsnip” lesson free?
Yes — the full text of “Model Specifications with parsnip” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.
What will I learn in “Model Specifications with parsnip”?
Specify model types and engines independently from the training step. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start R Academy?
No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Model Specifications with parsnip” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this R Academy lesson?
Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Feature Engineering with recipes
- Model Specifications with parsnip
- Workflows: Combining Recipes and Models
- Resampling and Cross-Validation with rsample