Predictive Modeling Basics (tidymodels)
9 min read
Welcome to the world of predictive modeling in R! If you've ever wanted to build models that can make predictions, you're in the right place. We'll be using the tidymodels framework, which is a collection of packages that make machine learning in R elegant and organized.
Think of building a predictive model like training a new employee for a very specific task. You need to give them the right data to learn from, a clear set of instructions, and a way to evaluate their performance. tidymodels provides all the tools you need for this process in a clean and consistent way.
1. The tidymodels Ecosystem: A Modern Approach to ML in R π
Before tidymodels, the landscape of machine learning in R was a bit like the Wild West. Many different packages existed for modeling, but they all had their own syntax and way of doing things. This made it challenging to switch between different models and to have a reproducible workflow.
The Problem: A lack of a standardized workflow for building and evaluating machine learning models in R.
The Solution: tidymodels swoops in to save the day! It provides a unified and consistent interface for all the steps involved in building a predictive model. It's a "meta-package," meaning it's a collection of several smaller packages that work together harmoniously.
Getting Started: Installation
First things first, let's get tidymodels installed on your machine. It's as simple as running a single line of code in your R console.
install.packages("tidymodels")Once the installation is complete, you can load the core packages into your R session with:
library(tidymodels)You'll see a message listing the attached packages. These are the core tools you'll be using for your modeling adventures. Some of the key players you'll get to know are:
rsample: For splitting your data into training and testing sets.recipes: For preprocessing your data to get it ready for modeling.parsnip: For creating a unified interface to various model specifications.workflows: For bundling your preprocessing and model fitting steps together.yardstick: For evaluating how well your model is performing.
Fun Fact: The developer of tidymodels, Max Kuhn, also created the popular caret package. He took the lessons learned from caret to build the more modern and streamlined tidymodels framework.
2. Data Splitting: Training vs. Testing Sets π°
Imagine you're preparing for an exam. You have a set of practice questions (the training set) that you use to learn the material. Then, on exam day, you're given a new set of questions you've never seen before (the testing set) to see how well you've actually learned the concepts.
In machine learning, we do the same thing with our data. We split it into two parts:
- Training Set: This is the majority of your data (usually 70-80%) that you use to "train" your model. The model will learn the patterns and relationships within this data.
- Testing Set: This is the remaining portion of your data that the model has never seen. We use this to evaluate how well our model generalizes to new, unseen data. This gives us an unbiased estimate of our model's performance in the real world.
The Problem: How can we be sure our model will perform well on new data it has never encountered?
The Solution: Splitting our data into training and testing sets. This allows us to assess the model's predictive power on unseen data.
Let's see how to do this with tidymodels using the initial_split() function from the rsample package.
# Load the tidymodels library
library(tidymodels)
# Let's use the built-in 'iris' dataset for this example
data(iris)
# Set a seed for reproducibility so we all get the same split
set.seed(123)
# Split the data into 75% for training and 25% for testing
iris_split <- initial_split(iris, prop = 0.75)
# Create the training and testing data frames
iris_train <- training(iris_split)
iris_test <- testing(iris_split)
# Let's check the dimensions of our new datasets
dim(iris_train)
dim(iris_test)In this example, we split the famous iris dataset. 75% of the data is now in iris_train, and the other 25% is in iris_test. Now we can train our model on iris_train and later evaluate its performance on iris_test.
3. Creating Recipes for Data Preprocessing π³
Before you start cooking, you need to prepare your ingredients. You might need to chop vegetables, marinate meat, or preheat the oven. Similarly, before you feed your data into a model, you often need to do some preprocessing.
The Problem: Raw data is often messy and not in the ideal format for modeling. It might have missing values, categorical variables that need to be converted to numbers, or numeric variables with vastly different scales.
The Solution: The recipes package in tidymodels provides a powerful and intuitive way to define a series of preprocessing steps. Think of it as writing down a recipe for how to prepare your data.
A recipe consists of a series of steps that will be applied to your data. Some common preprocessing steps include:
- Imputation: Filling in missing values.
- Dummy Coding: Converting categorical variables into a numeric format.
- Normalization/Scaling: Putting all numeric variables on the same scale.
Let's create a simple recipe for our iris dataset. We'll predict the Species based on the other four numeric variables. Our recipe will center and scale all the numeric predictors.
# Define the recipe
iris_recipe <- recipe(Species ~ ., data = iris_train) %>%
step_center(all_predictors()) %>%
step_scale(all_predictors())
# Now we need to "prep" the recipe with the training data.
# This step estimates the required quantities from the training data (e.g., means and standard deviations for centering and scaling)
iris_recipe_prepped <- prep(iris_recipe, training = iris_train)
# We can then "bake" the prepped recipe on our training and testing data
# This applies the prepared transformations
iris_train_preprocessed <- bake(iris_recipe_prepped, new_data = iris_train)
iris_test_preprocessed <- bake(iris_recipe_prepped, new_data = iris_test)
# Let's look at the first few rows of our preprocessed training data
head(iris_train_preprocessed)By using a recipe, we ensure that the same preprocessing steps are applied consistently to both our training and testing data. This is crucial for avoiding data leakage and getting a reliable estimate of our model's performance.
4. Fitting a Model: Linear and Logistic Regression π
Now for the exciting part: fitting a model! This is where our machine "learns" from the data. We'll start with two of the most fundamental and widely used models: linear regression and logistic regression.
Linear Regression: Used when your outcome variable (the thing you're trying to predict) is a continuous number (e.g., predicting the price of a house).
Logistic Regression: Used when your outcome variable is categorical (e.g., predicting whether an email is spam or not spam).
The Problem: How do we specify and train a model on our preprocessed data?
The Solution: The parsnip package provides a tidy and consistent interface for specifying models. You first define the type of model you want to use, then you set the "engine" (the underlying R package that will be used to fit the model), and finally, you fit() the model to your data.
Linear Regression Example
Let's try to predict the Petal.Length from the Petal.Width in our training data.
# 1. Define the model specification
lm_spec <- linear_reg() %>%
set_engine("lm") # "lm" stands for linear model, which is the standard in R
# 2. Create a workflow that bundles our recipe and model
lm_workflow <- workflow() %>%
add_recipe(iris_recipe) %>%
add_model(lm_spec)
# 3. Fit the model to the training data
lm_fit <- fit(lm_workflow, data = iris_train)
# We can now view the model's results
lm_fitLogistic Regression Example
Now, let's go back to our original goal of predicting the Species of the iris flower, which is a categorical variable.
# 1. Define the model specification for logistic regression
log_spec <- logistic_reg() %>%
set_engine("glm") # "glm" stands for generalized linear model
# 2. Create a workflow
log_workflow <- workflow() %>%
add_recipe(iris_recipe) %>%
add_model(log_spec)
# 3. Fit the model
log_fit <- fit(log_workflow, data = iris_train)
# View the results
log_fitNotice how similar the process is for both linear and logistic regression! This is the power of parsnip and workflows β providing a consistent structure for different models.
5. Evaluating Model Performance with Metrics π
We've trained our models, but how do we know if they are any good? We need to evaluate their performance on the unseen test data.
The Problem: We need a way to quantify how well our model is making predictions.
The Solution: The yardstick package provides a set of functions for calculating various performance metrics. The choice of metric depends on whether you have a regression or a classification problem.
Evaluating the Linear Regression Model
For our linear regression model, we can use metrics like Root Mean Squared Error (RMSE) and R-squared.
# Make predictions on the test data
lm_predictions <- predict(lm_fit, new_data = iris_test)
# Combine the predictions with the actual values
lm_results <- bind_cols(lm_predictions, iris_test %>% select(Petal.Length))
# Calculate the metrics
rmse(lm_results, truth = Petal.Length, estimate = .pred)
rsq(lm_results, truth = Petal.Length, estimate = .pred)Evaluating the Logistic Regression Model
For our logistic regression model (a classification problem), we can look at metrics like accuracy and create a confusion matrix.
# Make predictions
log_predictions <- predict(log_fit, new_data = iris_test)
# Combine predictions with actual values
log_results <- bind_cols(log_predictions, iris_test %>% select(Species))
# Calculate accuracy
accuracy(log_results, truth = Species, estimate = .pred_class)
# Create a confusion matrix
conf_mat(log_results, truth = Species, estimate = .pred_class)The confusion matrix gives you a detailed breakdown of where your model is making correct and incorrect predictions for each class.
And that's a wrap on the basics of predictive modeling with tidymodels! You've learned how to go from raw data to a trained and evaluated model in a structured and reproducible way. This foundation will serve you well as you explore more complex models and machine learning techniques. Happy modeling! π
π Extra Reading and References:
- Tidymodels Official Website: https://www.tidymodels.org/
- "Tidy Modeling with R" Book: https://www.tmwr.org/
- Getting Started with tidymodels: https://www.tidymodels.org/start/
- A Gentle Introduction to tidymodels: https://rviews.rstudio.com/2019/06/19/a-gentle-introduction-to-tidymodels/
Challenge
Challenge: Build a Complete Tidymodels Regression Pipeline
Your task is to construct a complete machine learning pipeline using the tidymodels framework to predict a target variable. You are working with a pre-loaded data frame named customer_data.
Data Frame Context:
customer_data: Contains information about customers.- Columns:
total_spend(numeric): The outcome variable you need to predict.age(numeric): Customer's age.income(numeric): Customer's annual income.plan_type(character/factor): The type of plan the customer is on (e.g., 'basic', 'premium').
Requirements:
- Load the
tidymodelsmeta-package. - Perform an initial stratified split of the
customer_dataon thetotal_spendvariable. The split should allocate 80% of the data for training. Assign the split object todata_split, and createtrain_dataandtest_dataframes. - Define a preprocessing recipe assigned to
spend_recipe. The recipe should modeltotal_spendas the outcome. It must include steps to one-hot encode theplan_typevariable and normalize all numeric predictors. - Specify a linear regression model using
parsnip. Set its computational engine to"lm". Assign this model specification tolm_model_spec. - Create a
workflowobject namedspend_workflowthat bundles the recipe (spend_recipe) and the model specification (lm_model_spec). - Fit the
spend_workflowto thetrain_data. Assign the resulting fitted workflow tospend_fit. - Use the fitted model to generate predictions on the
test_data. Create a new tibble namedfinal_resultsthat contains the originaltotal_spendfrom the test set and the predicted values (in a column named.pred). - Using the
final_resultstibble, calculate the Root Mean Squared Error (RMSE) and R-squared (rsq) metrics.
Expected result
Your final code should define a complete and logical tidymodels workflow. The script must create the following objects with the exact names specified:
data_split: Anrsplitobject created usinginitial_split.train_dataandtest_data: Data frames derived fromdata_split.spend_recipe: Arecipeobject that correctly specifies the formula and includesstep_dummyforplan_typeandstep_normalizeforageandincome.lm_model_spec: Alinear_regmodel specification created withparsnip, with its engine set to"lm".spend_workflow: Aworkflowobject containing the recipe and model specification.spend_fit: The fitted workflow object resulting from applyingfit()tospend_workflowandtrain_data.final_results: A tibble created by usingpredict()onspend_fitwithtest_dataand binding the results to the test set, containing columnstotal_spendand.pred.- The final lines of your code should use
yardstickfunctionsrmse()andrsq()to compute metrics on thefinal_resultstibble.