If you have not done so already, please view the slides at https://wlandau.github.io/targets-tutorial for an introduction to the targets
R package.
In this notebook, we will explore Keras models that predict customer behavior, and we will express our implementation in 7 custom functions. These functions are the essential building blocks of the targets
workflows to come.
split_data()
: read the customer churn data and split it into a training set and a test set.prepare_recipe()
: get the data ready for the Keras models.define_model()
: define a Keras model.train_model()
: define a Keras model with define_model()
, fit it to the training data, and return the fitted model object.test_accuracy()
: get the accuracy of a fitted Keras model on the testing set.test_model()
: call train_model()
and then test_accuracy()
.retrain_run()
: train the highest-accuracy model we have found so far.Using the IBM Watson Telco Customer Churn dataset, we will train deep neural networks to classify customers. The goal is to predict who will cancel their subscription services such as internet and television. Cancellation, or "customer churn", is a problem that companies care about monitoring. For additional background on this example, please read https://blogs.rstudio.com/tensorflow/posts/2018-01-11-keras-customer-churn.
Our functions will need the following R packages. Run the code chunk below to load them now. (Click on the green arrow on the right.)
# Build and train deep neural nets. # https://keras.rstudio.com/index.html library(keras) # Custom data preprocessing procedures. # https://tidymodels.github.io/recipes/ library(recipes) # Data resampling. We will use it to split the customer churn dataset # into training and test sets for our deep learning models. # https://tidymodels.github.io/rsample library(rsample) # Multiple packages that support clean code and tidy data. # https://tidyverse.tidyverse.org/ library(tidyverse) # Tidy methods to measure model performance. # We will use it to compute accuracy on the testing set. # https://tidymodels.github.io/yardstick library(yardstick)
Check if TensorFlow is installed. The code below should display the TensorFlow version. Do not worry about other console messages.
library(tensorflow) tf_config()
split_data()
For machine learning, we need to split the customers (rows) into a training dataset and a testing dataset.
split_data <- function(churn_file) { read_csv(churn_file, col_types = cols()) %>% initial_split(prop = 0.7) # from the rsample package }
Try out the function.
churn_data <- split_data("data/churn.csv")
The training set has 2113 customers (rows) and the testing set has 4930.
print(churn_data)
Functions from rsample
can recover the training and testing sets.
training(churn_data)
testing(churn_data)
The dataset has 21 variables (columns).
# View(training(churn_data)) glimpse(training(churn_data))
Churn
is our response variable, and customerID
identifies customers.
training(churn_data) %>% select(customerID, Churn) %>% print()
The rest of the variables are covariates.
PhoneService
, MultipleLines
, InternetService
, OnlineSecurity
, OnlineBackup
, TechSupport
, DeviceProtection
, StreamingTV
, and StreamingMovies
.Contract
, PaymentMethod
, PaperlessBilling
, tenure
, MonthlyCharges
, and TotalCharges
.gender
, SeniorCitizen
, Partner
, and Dependents
.prepare_recipe()
prepare_recipe()
gets the data ready for the models. It accepts a dataset with a train/test split and returns a recipe object generated by the recipes
package.
prepare_recipe <- function(churn_data) { churn_data %>% # Just preprocess the training data. training() %>% # Start defining a new recipe. recipe(Churn ~ .) %>% # Remove the customerID variable from the data. step_rm(customerID) %>% # Remove missing values. step_naomit(all_outcomes(), all_predictors()) %>% # Partition the tenure variable into 6 bins. step_discretize(tenure, options = list(cuts = 6)) %>% # Take the log of TotalCharges to strengthen the association with Churn. step_log(TotalCharges) %>% # Encode the Churn variable as a 0-1 indicator variable. step_mutate(Churn = ifelse(Churn == "Yes", 1, 0)) %>% # Encode each categorical variable as a collection of 0-1 indicators. step_dummy(all_nominal(), -all_outcomes()) %>% # Center all covariates. step_center(all_predictors(), -all_outcomes()) %>% # Scale all covariates. step_scale(all_predictors(), -all_outcomes()) %>% # Run the recipe on the data. prep() }
Let's try out the function to make sure it works.
churn_recipe <- prepare_recipe(churn_data) print(churn_recipe)
Later on, we will need to retrieve the preprocessed training data with juice()
.
juice(churn_recipe, all_outcomes())
juice(churn_recipe, all_predictors())
Keras will want our predictors to be in matrix form.
juice(churn_recipe, all_predictors(), composition = "matrix")[1:6, 1:4]
When we compute accuracy later on, we will use bake()
to preprocess the testing data.
bake(churn_recipe, testing(churn_data))
define_model()
Before we fit a model, we need to define it. define_model()
function encapsulates our Keras model definition. It serves as custom shorthand that will make our other functions easier to read.
define_model <- function(churn_recipe, units1, units2, act1, act2, act3) { input_shape <- ncol( juice(churn_recipe, all_predictors(), composition = "matrix") ) out <- keras_model_sequential() %>% layer_dense( units = units1, kernel_initializer = "uniform", activation = act1, input_shape = input_shape ) %>% layer_dropout(rate = 0.1) %>% layer_dense( units = units2, kernel_initializer = "uniform", activation = act2 ) %>% layer_dropout(rate = 0.1) %>% layer_dense( units = 1, kernel_initializer = "uniform", activation = act3 ) out }
Let's check if it returns the model definition we expect.
define_model(churn_recipe, 16, 16, "relu", "relu", "sigmoid") %>% print()
train_model()
Next, we need to fit a model and return the fitted model object.
train_model <- function( churn_recipe, units1 = 16, units2 = 16, act1 = "relu", act2 = "relu", act3 = "sigmoid" ) { model <- define_model(churn_recipe, units1, units2, act1, act2, act3) compile( model, optimizer = "adam", loss = "binary_crossentropy", metrics = c("accuracy") ) x_train_tbl <- juice( churn_recipe, all_predictors(), composition = "matrix" ) y_train_vec <- juice(churn_recipe, all_outcomes()) %>% pull() fit( object = model, x = x_train_tbl, y = y_train_vec, batch_size = 32, epochs = 32, validation_split = 0.3, verbose = 0 ) model }
Try it out.
model <- train_model(churn_recipe) print(model)
test_accuracy()
This function takes model object from train_model()
and computes the accuracy on the testing data.
test_accuracy <- function(churn_data, churn_recipe, churn_model) { testing_data <- bake(churn_recipe, testing(churn_data)) x_test_tbl <- testing_data %>% select(-Churn) %>% as.matrix() y_test_vec <- testing_data %>% select(Churn) %>% pull() yhat_keras_class_vec <- churn_model %>% predict_classes(x_test_tbl) %>% as.factor() %>% fct_recode(yes = "1", no = "0") yhat_keras_prob_vec <- churn_model %>% predict_proba(x_test_tbl) %>% as.vector() test_truth <- y_test_vec %>% as.factor() %>% fct_recode(yes = "1", no = "0") estimates_keras_tbl <- tibble( truth = test_truth, estimate = yhat_keras_class_vec, class_prob = yhat_keras_prob_vec ) estimates_keras_tbl %>% conf_mat(truth, estimate) %>% summary() %>% filter(.metric == "accuracy") %>% pull(.estimate) }
Try it out.
test_accuracy(churn_data, churn_recipe, model)
test_model()
test_model()
is the top-level modeling function we will use in targets
. It trains a model and reports its accuracy on the test dataset. It uses the previously defined train_model()
and test_accuracy()
functions.
test_model <- function( churn_data, churn_recipe, units1 = 16, units2 = 16, act1 = "relu", act2 = "relu", act3 = "sigmoid" ) { model <- train_model(churn_recipe, units1, units2, act1, act2, act3) accuracy <- test_accuracy(churn_data, churn_recipe, model) tibble( accuracy = accuracy, units1 = units1, units2 = units2, act1 = act1, act2 = act2, act3 = act3 ) }
Try it out.
run_relu <- test_model(act1 = "relu", churn_data, churn_recipe) run_sigmoid <- test_model(act1 = "sigmoid", churn_data, churn_recipe) run_relu
retrain_run()
At the end of the workflow, we want the trained model object for the best run so far. For efficiency reasons, we have been discarding our trained model objects up until this point, so we need to retrain the model with the highest accuracy. Below, our retrain_run()
function accepts a data frame from test_model()
and returns a trained Keras model object.
retrain_run <- function(churn_run, churn_recipe) { train_model( churn_recipe, churn_run$units1, churn_run$units2, churn_run$act1, churn_run$act2, churn_run$act3 ) }
Try it out. First, get the best model run so far.
best_run <- bind_rows(run_relu, run_sigmoid) %>% top_n(1, accuracy) %>% head(1) best_run
Then, retrain the model from that run.
retrain_run(best_run, churn_recipe)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.