-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path1-functions.Rmd
374 lines (300 loc) · 9.96 KB
/
1-functions.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
---
title: "Custom functions for the customer churn workflow"
output: html_document
---
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.
# About
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.
1. `split_data()`: read the customer churn data and split it into a training set and a test set.
2. `prepare_recipe()`: get the data ready for the Keras models.
3. `define_model()`: define a Keras model.
4. `train_model()`: define a Keras model with `define_model()`, fit it to the training data, and return the fitted model object.
5. `test_accuracy()`: get the accuracy of a fitted Keras model on the testing set.
6. `test_model()`: call `train_model()` and then `test_accuracy()`.
7. `retrain_run()`: train the highest-accuracy model we have found so far.
# Customer churn
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>.
# Packages
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.)
```{r, message = FALSE}
# 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.
```{r, message = FALSE}
library(tensorflow)
tf_config()
```
# `split_data()`
For machine learning, we need to split the customers (rows) into a training dataset and a testing dataset.
```{r}
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.
```{r}
churn_data <- split_data("data/churn.csv")
```
The testing set has 2113 customers (rows) and the training set has 4930.
```{r}
print(churn_data)
```
Functions from [`rsample`](https://tidymodels.github.io/rsample) can recover the training and testing sets.
```{r}
training(churn_data)
```
```{r}
testing(churn_data)
```
The dataset has 21 variables (columns).
```{r}
# View(training(churn_data))
glimpse(training(churn_data))
```
`Churn` is our response variable, and `customerID` identifies customers.
```{r}
training(churn_data) %>%
select(customerID, Churn) %>%
print()
```
The rest of the variables are covariates.
- Subscriptions services: `PhoneService`, `MultipleLines`, `InternetService`, `OnlineSecurity`, `OnlineBackup`, `TechSupport`, `DeviceProtection`, `StreamingTV`, and `StreamingMovies`.
- Account information: `Contract`, `PaymentMethod`, `PaperlessBilling`, `tenure`, `MonthlyCharges`, and `TotalCharges`.
- Demographic information: `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.
```{r}
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.
```{r}
churn_recipe <- prepare_recipe(churn_data)
print(churn_recipe)
```
Later on, we will need to retrieve the preprocessed training data with `juice()`.
```{r}
juice(churn_recipe, all_outcomes())
```
```{r}
juice(churn_recipe, all_predictors())
```
Keras will want our predictors to be in matrix form.
```{r}
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.
```{r}
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.
```{r}
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.
```{r}
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.
```{r}
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.
```{r}
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.
```{r}
test_accuracy <- function(churn_data, churn_recipe, 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 <- model %>%
predict(x_test_tbl) %>%
`>`(0.5) %>%
as.integer() %>%
as.factor() %>%
fct_recode(yes = "1", no = "0")
yhat_keras_prob_vec <-
model %>%
predict(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.
```{r}
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.
```{r}
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.
```{r, output = FALSE}
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.
```{r}
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.
```{r}
best_run <- bind_rows(run_relu, run_sigmoid) %>%
top_n(1, accuracy) %>%
head(1)
best_run
```
Then, retrain the model from that run.
```{r}
retrain_run(best_run, churn_recipe)
```