Bank Marketing - Part 3 - Keeping up with the times - Sliding and Expanding Window Models

The Timeline of the Calls

In Part 1, we recovered the year of each call from the order of the calls. Here are the calls and the subscription rate in each month:

p1 <- ggplot(dfMonthly, aes(x = year_month, y = calls)) +
  geom_col(fill = "#00AED8") +
  scale_y_continuous(labels = scales::label_comma()) +
  scale_x_date(date_breaks = "3 months", date_labels = "%b %Y") +
  labs(x = NULL, y = "Calls", title = "Number of calls in each month")
p2 <- ggplot(dfMonthly, aes(x = year_month, y = rate)) +
  geom_line(color = "#F37735") + geom_point(aes(size = calls), color = "#F37735", show.legend = FALSE) +
  scale_y_continuous(labels = scales::label_percent()) +
  scale_x_date(date_breaks = "3 months", date_labels = "%b %Y") +
  labs(x = NULL, y = "Subscription rate", title = "Subscription rate in each month (point size: number of calls)")
cowplot::plot_grid(plotlist = list(p1, p2), ncol = 1, align = "v")

Most of the calls were made in 2008, when few clients said yes. From the middle of 2009, the bank made far fewer calls, and about half of them succeeded. So a model trained on the past learns from a very different situation from the one that it has to predict.

How the Windows Work

Each cycle has two parts:

  • A training window of past months. We choose the hyperparameters with cross validation on these calls only, and train the final model on all of them.
  • A testing period of the next 3 months. The model predicts these calls, which it has never seen.

Then we move forward by 3 months. The first testing period starts in June 2009, the first month with 12 full months of calls before it, and the last one ends in November 2010, the last month of the data. The two kinds of windows use the same testing periods:

  • The sliding window is the 12 calendar months before the testing period. Some months have no calls, so a window can have fewer than 12 months of calls.
  • The expanding window starts with the same 12 months, and keeps all the months since then. So in the first cycle, the two windows are the same, and the first cycle is run only once.
dfCycles %>%
  mutate(training = paste(format(train_first, "%b %Y"), "-", format(train_last, "%b %Y")),
         training_calls = scales::label_comma()(train_calls),
         training_rate = scales::label_percent(accuracy = 0.1)(train_rate)) %>%
  select(window, cycle, test_first, test_last, test_calls, test_rate, training, training_calls, training_rate) %>%
  pivot_wider(names_from = window, values_from = c(training, training_calls, training_rate)) %>%
  transmute(Cycle = cycle,
            `Testing months` = if_else(test_first == test_last, format(test_first, "%b %Y"),
                                       paste(format(test_first, "%b %Y"), "-", format(test_last, "%b %Y"))),
            `Testing calls` = scales::label_comma()(test_calls),
            `Testing rate` = scales::label_percent(accuracy = 0.1)(test_rate),
            `Sliding window` = training_sliding, `Calls` = training_calls_sliding, `Rate` = training_rate_sliding,
            `Expanding window` = training_expanding, `Calls ` = training_calls_expanding, `Rate ` = training_rate_expanding) %>%
  knitr::kable(align = c("r", "l", "r", "r", "l", "r", "r", "l", "r", "r"))
Cycle Testing months Testing calls Testing rate Sliding window Calls Rate Expanding window Calls Rate
1 Jun 2009 - Aug 2009 1,662 35.7% Jun 2008 - May 2009 28,452 7.7% Jun 2008 - May 2009 28,452 7.7%
2 Sep 2009 - Nov 2009 1,070 42.4% Oct 2008 - Aug 2009 13,886 13.8% Jun 2008 - Aug 2009 30,114 9.2%
3 Dec 2009 172 51.2% Dec 2008 - Nov 2009 11,274 19.0% Jun 2008 - Nov 2009 31,184 10.4%
4 Mar 2010 - May 2010 650 56.8% Mar 2009 - Dec 2009 11,436 19.5% Jun 2008 - Dec 2009 31,356 10.6%
5 Jun 2010 - Aug 2010 773 52.1% Jun 2009 - May 2010 3,554 42.3% Jun 2008 - May 2010 32,006 11.5%
6 Sep 2010 - Nov 2010 635 47.4% Sep 2009 - Aug 2010 2,665 49.3% Jun 2008 - Aug 2010 32,779 12.5%
dfCycles %>%
  select(window, cycle, train_first, train_last, test_first, test_last) %>%
  pivot_longer(-c(window, cycle), names_to = c("part", ".value"), names_sep = "_") %>%
  mutate(part = if_else(part == "train", "training window", "testing period"),
         last = last %m+% months(1),
         window = factor(window, levels = c("sliding", "expanding"), labels = c("Sliding windows", "Expanding windows"))) %>%
  ggplot(aes(y = factor(cycle), xmin = first, xmax = last, color = part)) +
  geom_linerange(linewidth = 5) +
  facet_wrap(~ window, ncol = 1) +
  scale_y_discrete(limits = rev) +
  scale_x_date(date_breaks = "3 months", date_labels = "%b %Y") +
  scale_color_manual(values = c("training window" = "#00AED8", "testing period" = "#F37735"), name = NULL) +
  labs(x = NULL, y = "Cycle", title = "Training windows and testing periods")

What’s notable?

  • The sliding windows shrink from 28,452 calls in the first cycle to 2,665 in the last, because the bank made fewer calls each year. The expanding windows grow, but only to 32,779, because the later months have few calls.
  • The subscription rate in the sliding windows rises from 7.7% to 49.3%, close to the rates of the testing periods. In the expanding windows, it only reaches 12.5%, because most of their calls are always from 2008, when few clients said yes.
  • Cycle 3 tests only December 2009, because there were no calls in January and February 2010.

In each cycle, the code checks that every training call was made before every testing call, and that no call is in both. Everything that the model learns, including the hyperparameters and the preparation of the features (such as the dummy variables and which features are skewed), comes from the training window only.

Feature Sets

We compare three sets of features:

  • client and campaign: the features of the client and of the call, such as age, job, contact, month and the history of previous campaigns. No economic features.
  • + economic levels: the same features plus the five economic features, as in Part 2.
  • + economic trends: the client and campaign features plus three features that describe how things changed, instead of their levels: euribor_change, the change of the Euribor rate; employed_change, the change of the number of employees; and prev_month_rate, the subscription rate in the last month that the model knows.

For the calls in a testing period, the trend features compare with the last month of the training window, the last month that the bank knows when it trains the model. So the model does not use the results of other calls in the testing period.

p1 <- ggplot(dfMonthly, aes(x = year_month, y = euribor_mean)) +
  geom_line(color = "#00AED8") + geom_point(color = "#00AED8") +
  scale_x_date(date_breaks = "3 months", date_labels = "%b %Y") +
  labs(x = NULL, y = "3 month Euribor (%)", title = "Average 3 month Euribor in each month") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
p2 <- ggplot(dfMonthly %>% filter(!is.na(prev_month_rate)), aes(x = rate, y = prev_month_rate)) +
  geom_abline(lty = 2) +
  geom_point(aes(size = calls), color = "#F37735", alpha = 0.7, show.legend = FALSE) +
  scale_x_continuous(labels = scales::label_percent()) +
  scale_y_continuous(labels = scales::label_percent()) +
  labs(x = "Subscription rate in the month", y = "Rate in the previous month with calls",
       title = "Subscription rate vs the previous month")
cowplot::plot_grid(plotlist = list(p1, p2), ncol = 2)

Results

All the Testing Periods Together

We put the predictions of all the testing periods together, 4,962 calls in total, and measure each window, model and feature set. We also measure the ROC AUC within each month and take the average. This shows how well a model ranks the clients within a month, which is what a bank needs to decide whom to call that month.

dfOverall <- dfWindowPred %>%
  group_by(window, model, feature_set) %>%
  summarise(roc_auc = roc_auc_vec(y, .pred_yes),
            pr_auc = pr_auc_vec(y, .pred_yes),
            mn_log_loss = mn_log_loss_vec(y, .pred_yes),
            mean_predicted = mean(.pred_yes),
            actual_rate = mean(y == "yes"),
            .groups = "drop") %>%
  left_join(dfWindowPred %>%
              group_by(window, model, feature_set, year_month) %>%
              summarise(month_roc_auc = roc_auc_vec(y, .pred_yes), .groups = "drop") %>%
              group_by(window, model, feature_set) %>%
              summarise(monthly_roc_auc = mean(month_roc_auc), .groups = "drop"),
            by = c("window", "model", "feature_set")) %>%
  mutate(window = factor(window, levels = c("sliding", "expanding")),
         feature_set = factor(feature_set, levels = names(lFeatureSets))) %>%
  arrange(window, model, feature_set)

dfOverall %>%
  mutate(across(c(roc_auc, pr_auc, mn_log_loss, monthly_roc_auc), ~ round(.x, 3)),
         across(c(mean_predicted, actual_rate), ~ scales::label_percent(accuracy = 0.1)(.x))) %>%
  select(window, model, feature_set, roc_auc, monthly_roc_auc, pr_auc, mn_log_loss, mean_predicted, actual_rate) %>%
  # in the HTML table, each cell's text is on a line of its own, and Hugo would turn a line that starts with "+" into a
  # bulleted list, so the text is wrapped in a <span>
  mutate(feature_set = paste0("<span>", feature_set, "</span>")) %>%
  # an HTML table, so that the browser sizes the columns to their contents, and the headers break where they should;
  # text columns are aligned left, and number columns right, with their headers
  knitr::kable(format = "html", escape = FALSE, align = c("l", "l", "l", "r", "r", "r", "r", "r", "r"),
               col.names = c("Window", "Model", "Features", "ROC<br>AUC", "Average ROC AUC<br>within a month", "PR<br>AUC",
                             "Log<br>loss", "Average predicted<br>probability", "Actual<br>subscription rate"))
Window Model Features ROC
AUC
Average ROC AUC
within a month
PR
AUC
Log
loss
Average predicted
probability
Actual
subscription rate
sliding glmnet client and campaign 0.655 0.678 0.621 0.762 27.4% 44.5%
sliding glmnet + economic levels 0.596 0.683 0.519 1.337 50.7% 44.5%
sliding glmnet + economic trends 0.588 0.678 0.521 0.902 45.9% 44.5%
sliding xgboost client and campaign 0.650 0.677 0.615 0.764 27.7% 44.5%
sliding xgboost + economic levels 0.638 0.669 0.598 0.721 31.7% 44.5%
sliding xgboost + economic trends 0.573 0.650 0.519 0.716 47.1% 44.5%
expanding glmnet client and campaign 0.659 0.659 0.612 0.834 22.3% 44.5%
expanding glmnet + economic levels 0.592 0.684 0.521 1.170 53.9% 44.5%
expanding glmnet + economic trends 0.628 0.660 0.592 0.763 46.9% 44.5%
expanding xgboost client and campaign 0.653 0.652 0.613 0.810 24.2% 44.5%
expanding xgboost + economic levels 0.613 0.655 0.571 0.751 30.3% 44.5%
expanding xgboost + economic trends 0.582 0.645 0.520 0.711 49.8% 44.5%
overall <- function(window, model, feature_set, metric) {
  dfOverall[[metric]][dfOverall$window == window & dfOverall$model == model & dfOverall$feature_set == feature_set]
}
# the best window, model and feature set, by ROC AUC over all the testing periods together
best_row <- dfOverall %>% slice_max(roc_auc, n = 1)

# expanding minus sliding, for each model and feature set
dfWindowComparison <- dfOverall %>%
  select(window, model, feature_set, roc_auc, monthly_roc_auc) %>%
  pivot_wider(names_from = window, values_from = c(roc_auc, monthly_roc_auc)) %>%
  mutate(roc_diff = roc_auc_expanding - roc_auc_sliding,
         monthly_diff = monthly_roc_auc_expanding - monthly_roc_auc_sliding)

What’s notable?

  • On calls that they have not seen, from the next 3 months, all the models do much worse than in Part 2: their ROC AUC is between 0.573 and 0.659, compared with about 0.80 on the random testing set of Part 2. The best is glmnet with the client and campaign features and the expanding window, with 0.659, just ahead of the same model with the sliding window (0.655).
  • Within a month, the sliding windows rank the clients better: the average ROC AUC within a month is higher with the sliding window for 5 of the 6 combinations of model and features.
  • The economic features do not help, with either kind of window. With their levels, glmnet has the worst log loss, because it predicts far too many subscribers in some months.
  • Without the economic features, the models expect far fewer subscribers than there are, and more so with the expanding window: an average predicted probability of 22% with the expanding window and 27% with the sliding window for glmnet, compared with the actual rate of 44%.

Cycle by Cycle

dfCycleResults <- dfWindowPred %>%
  group_by(window, cycle, model, feature_set) %>%
  summarise(roc_auc = roc_auc_vec(y, .pred_yes), .groups = "drop") %>%
  mutate(window = factor(window, levels = c("sliding", "expanding")),
         feature_set = factor(feature_set, levels = names(lFeatureSets)))

ggplot(dfCycleResults, aes(x = cycle, y = roc_auc, color = window)) +
  geom_hline(yintercept = 0.5, lty = 2) +
  geom_line() + geom_point(size = 2) +
  facet_grid(model ~ feature_set) +
  scale_x_continuous(breaks = unique(dfCycles$cycle)) +
  scale_color_manual(values = c("sliding" = "#00AED8", "expanding" = "#F37735"), name = "Window") +
  labs(x = "Cycle", y = "ROC AUC on the testing period", title = "ROC AUC in each testing period",
       subtitle = "The dashed line is a random ranking")

What’s notable?

  • In cycle 1, the two windows are the same, and so are the results.
  • In cycles 2 to 4, the two windows give similar results, and the expanding window is sometimes a little better: it has more calls, and the situation has not yet changed much.
  • In the last two cycles, the sliding window is better for almost every model and feature set: an average ROC AUC of 0.744 with the sliding window, compared with 0.698 with the expanding window. By then, the clients behave very differently from 2008. The sliding window has forgotten 2008, but most of the calls in the expanding window are still from 2008.
  • With both kinds of windows, the period matters much more than the model or the features.

Predicted and Actual Subscription Rates

A bank also needs to know how many subscribers to expect, for example to plan its staff. Here is the average predicted probability in each testing month, compared with the actual subscription rate:

dfWindowPred %>%
  mutate(window = factor(window, levels = c("sliding", "expanding"), labels = c("Sliding window", "Expanding window")),
         feature_set = factor(feature_set, levels = names(lFeatureSets))) %>%
  group_by(window, model, feature_set, year_month) %>%
  summarise(predicted = mean(.pred_yes), actual = mean(y == "yes"), .groups = "drop") %>%
  ggplot(aes(x = year_month)) +
  geom_line(aes(y = actual), color = "black", linewidth = 1) +
  geom_line(aes(y = predicted, color = feature_set)) +
  geom_point(aes(y = predicted, color = feature_set), size = 1.5) +
  facet_grid(window ~ model) +
  scale_y_continuous(labels = scales::label_percent()) +
  scale_x_date(date_breaks = "3 months", date_labels = "%b %Y") +
  scale_color_quant(palette = "metro", name = "Features") +
  labs(x = NULL, y = "Subscription rate", title = "Predicted (colors) and actual (black) subscription rate in each testing month") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

What’s notable?

  • Without the economic features, the models with expanding windows predict too few subscribers in almost every cycle, because their training windows are dominated by the low subscription rates of 2008. The sliding windows catch up with the actual rate in the last cycles.
  • With the levels of the economic features, glmnet swings widely with both kinds of windows: in September to November 2009, it predicts that almost every client will say yes. In those months, interest rates were lower than in any month of its training window, so it extended a straight-line trend that no longer applied (as in Part 2).
  • With the trend features, the predictions are closer to the actual rate on average, but they jump from one cycle to the next.

The Hyperparameters Change from Cycle to Cycle

These are the hyperparameters of xgboost chosen in each cycle, with the client and campaign features:

dfCycleParams %>%
  filter(model == "xgboost", feature_set == best_row$feature_set) %>%
  unnest(params) %>%
  mutate(window = factor(window, levels = c("sliding", "expanding"))) %>%
  arrange(window, cycle) %>%
  transmute(Window = window, Cycle = cycle, min_n, tree_depth, learn_rate = signif(learn_rate, 3),
            `Cross validated ROC AUC in the training window` = round(cv_roc_auc, 3)) %>%
  knitr::kable()
Window Cycle min_n tree_depth learn_rate Cross validated ROC AUC in the training window
sliding 1 23 2 0.0032 0.619
sliding 2 40 1 0.0395 0.692
sliding 3 39 12 0.0035 0.755
sliding 4 39 12 0.0035 0.759
sliding 5 23 2 0.0032 0.634
sliding 6 23 15 0.0089 0.693
expanding 1 23 2 0.0032 0.619
expanding 2 39 12 0.0035 0.680
expanding 3 39 12 0.0035 0.706
expanding 4 39 12 0.0035 0.723
expanding 5 39 12 0.0035 0.747
expanding 6 39 12 0.0035 0.757

What’s notable?

  • With the expanding windows, xgboost settles on almost the same hyperparameters from cycle 2 on, because each window adds only a few calls to the many calls of 2008. With the sliding windows, the best hyperparameters change more, from very shallow trees to deep trees, because each window is a different period.
  • The cross validated ROC AUC within the expanding windows rises steadily, but the ROC AUC on the next 3 months does not follow it. Cross validation within a window measures how well a model fits that window, not how well it predicts the next months.
  • Either way, the hyperparameters must be chosen again in each cycle, on the training window only, rather than reused from Part 2, where they were chosen on calls from the whole period.

Sliding or Expanding?

dfWindowComparison %>%
  mutate(across(where(is.numeric), ~ round(.x, 3)),
         feature_set = paste0("<span>", feature_set, "</span>")) %>%
  select(model, feature_set, roc_auc_sliding, roc_auc_expanding, monthly_roc_auc_sliding, monthly_roc_auc_expanding) %>%
  knitr::kable(format = "html", escape = FALSE, align = c("l", "l", "r", "r", "r", "r"),
               col.names = c("Model", "Features", "ROC AUC<br>sliding", "ROC AUC<br>expanding",
                             "Average ROC AUC within<br>a month, sliding", "Average ROC AUC within<br>a month, expanding"))
Model Features ROC AUC
sliding
ROC AUC
expanding
Average ROC AUC within
a month, sliding
Average ROC AUC within
a month, expanding
glmnet client and campaign 0.655 0.659 0.678 0.659
glmnet + economic levels 0.596 0.592 0.683 0.684
glmnet + economic trends 0.588 0.628 0.678 0.660
xgboost client and campaign 0.650 0.653 0.677 0.652
xgboost + economic levels 0.638 0.613 0.669 0.655
xgboost + economic trends 0.573 0.582 0.650 0.645
  • Over all the testing periods together, the expanding window ranks the clients slightly better for 4 of the 6 combinations, but the differences are small: 0.040 at most.
  • Within a month, which is what matters to decide whom to call, the sliding window is better for 5 of the 6 combinations.
  • The sliding window adapts faster when the behavior of the clients changes, as in the last two cycles, and its predictions of the number of subscribers are generally closer to the actual numbers.
  • The sliding window is also cheaper: tuning and training took about 21 minutes for all the cycles, compared with about 40 minutes for the expanding windows, which have more calls.

So in this dataset, forgetting the old past helps. An expanding window would be the better choice when the past stays relevant, or when there is too little recent data.

This comparison looks back at the whole period, so it is a lesson learned with hindsight. A bank in the middle of 2009 could not have known that the sliding window would do better in 2010. It could only have chosen the kind of window from the past results available at the time, just as we chose the hyperparameters from the training window only.

The same applies to a middle way between the two kinds of windows: keeping all the past calls, but giving the recent calls more weight. How much more weight is another choice that must be made from past data at each point in time, for example by testing a few weights on the last months of the training window. If we chose it knowing how the subscription rate changed later, the model would look better than any model that a bank could have built.

With Perfect Foresight

In Part 2, we chose the hyperparameters by cross validation on a random sample of the calls of the whole period, including the calls that we predict here. So those hyperparameters were chosen with knowledge of the future (perfect foresight), which a bank never has. How much better would the models do with them?

Here, we train the models in every cycle with the hyperparameters of Part 2, without tuning, on the same training windows, and test them on the same testing periods. For glmnet, they are a penalty of 1e-10 and a mixture of 1. For xgboost, they are min_n = 23, tree_depth = 4 and learn_rate = 0.0254.

summarise_predictions <- function(dfPred) {
  dfPred %>%
    group_by(window, model, feature_set) %>%
    summarise(roc_auc = roc_auc_vec(y, .pred_yes), log_loss = mn_log_loss_vec(y, .pred_yes), .groups = "drop") %>%
    left_join(dfPred %>%
                group_by(window, model, feature_set, year_month) %>%
                summarise(month_roc_auc = roc_auc_vec(y, .pred_yes), .groups = "drop") %>%
                group_by(window, model, feature_set) %>%
                summarise(monthly_roc_auc = mean(month_roc_auc), .groups = "drop"),
              by = c("window", "model", "feature_set"))
}

dfForesightComparison <- bind_rows(tuned = summarise_predictions(dfWindowPred),
                                   foresight = summarise_predictions(dfForesightPred), .id = "hyperparameters") %>%
  pivot_wider(names_from = hyperparameters, values_from = c(roc_auc, monthly_roc_auc, log_loss)) %>%
  mutate(window = factor(window, levels = c("sliding", "expanding")),
         feature_set = factor(feature_set, levels = names(lFeatureSets)),
         roc_gain = roc_auc_foresight - roc_auc_tuned,
         monthly_gain = monthly_roc_auc_foresight - monthly_roc_auc_tuned) %>%
  arrange(window, model, feature_set)

dfForesightComparison %>%
  mutate(across(where(is.numeric), ~ round(.x, 3)),
         feature_set = paste0("<span>", feature_set, "</span>")) %>%
  select(window, model, feature_set, roc_auc_tuned, roc_auc_foresight, monthly_roc_auc_tuned, monthly_roc_auc_foresight,
         log_loss_tuned, log_loss_foresight) %>%
  knitr::kable(format = "html", escape = FALSE, align = c("l", "l", "l", "r", "r", "r", "r", "r", "r"),
               col.names = c("Window", "Model", "Features", "ROC AUC<br>tuned", "ROC AUC<br>foresight",
                             "Average ROC AUC within<br>a month, tuned", "Average ROC AUC within<br>a month, foresight",
                             "Log loss<br>tuned", "Log loss<br>foresight"))
Window Model Features ROC AUC
tuned
ROC AUC
foresight
Average ROC AUC within
a month, tuned
Average ROC AUC within
a month, foresight
Log loss
tuned
Log loss
foresight
sliding glmnet client and campaign 0.655 0.657 0.678 0.676 0.762 0.760
sliding glmnet + economic levels 0.596 0.591 0.683 0.683 1.337 1.396
sliding glmnet + economic trends 0.588 0.588 0.678 0.676 0.902 0.930
sliding xgboost client and campaign 0.650 0.653 0.677 0.662 0.764 0.758
sliding xgboost + economic levels 0.638 0.645 0.669 0.656 0.721 0.724
sliding xgboost + economic trends 0.573 0.563 0.650 0.629 0.716 0.754
expanding glmnet client and campaign 0.659 0.659 0.659 0.660 0.834 0.832
expanding glmnet + economic levels 0.592 0.590 0.684 0.685 1.170 1.169
expanding glmnet + economic trends 0.628 0.626 0.660 0.660 0.763 0.766
expanding xgboost client and campaign 0.653 0.651 0.652 0.653 0.810 0.811
expanding xgboost + economic levels 0.613 0.631 0.655 0.662 0.751 0.729
expanding xgboost + economic trends 0.582 0.586 0.645 0.635 0.711 0.764

In this table, tuned means the hyperparameters chosen in each cycle on the training window only, and foresight the hyperparameters of Part 2.

What’s notable?

  • The hyperparameters chosen with perfect foresight do not make the models better. Over all the testing periods together, they give a higher ROC AUC for only 5 of the 12 combinations of window, model and features, and the average difference is +0.001 (from -0.010 to +0.018).
  • Within a month, they are better for 5 of the 12 combinations, and slightly worse on average (-0.004).
  • So the large difference between Part 2 (a ROC AUC of about 0.80) and this post (about 0.65) does not come from the hyperparameters. It comes from the data: in Part 2, the models learned from calls of the same months as the calls that they predicted. Knowing the future hyperparameters is worth almost nothing; knowing the future clients is worth a lot.
  • The models are not very sensitive to the exact hyperparameters here. Choosing them again in each cycle mainly protects us from a lookahead: it costs much more time (about 61 minutes for all the cycles, compared with 3 minutes to train the models with fixed hyperparameters), but it is the only choice that a bank could make in practice.

Comparison with Part 2

The three ways of testing the models give very different answers:

  • On a random testing set from the same period (Part 2), the best models had a ROC AUC of about 0.80.
  • When we trained on the first 75% of the calls and tested on the last 25% (Part 2), the ROC AUC was between 0.28 and 0.71, depending on the model and the features. But the hyperparameters had been chosen on calls from the whole period.
  • With sliding and expanding windows, where every choice is made on past calls only, the ROC AUC over all the testing periods is between 0.573 and 0.659.

The testing periods are not exactly the same (the later calls of Part 2 start in May 2009, and the testing periods here start in June 2009), so the numbers cannot be compared exactly. But the message is clear: the random testing set of Part 2 gave a much too good picture of how the models would predict future calls. And as we saw above, the hyperparameters of Part 2, chosen with perfect foresight, explain almost none of the difference.

How a Bank Could Use the Models

Even with modest ROC AUCs, the models are useful within a month. If the bank calls the 20% of each month’s clients with the highest probabilities, using the glmnet model with the client and campaign features and the expanding window:

dfTopCalls <- dfWindowPred %>%
  filter(window == best_row$window, model == best_row$model, feature_set == best_row$feature_set) %>%
  group_by(year_month) %>%
  arrange(desc(.pred_yes), .by_group = TRUE) %>%
  mutate(called = row_number() <= ceiling(0.2 * n())) %>%
  ungroup()

top_reach <- sum(dfTopCalls$y == "yes" & dfTopCalls$called) / sum(dfTopCalls$y == "yes")
top_rate <- mean(dfTopCalls$y[dfTopCalls$called] == "yes")
all_rate <- mean(dfTopCalls$y == "yes")
  • It reaches 31% of the subscribers with 20% of the calls.
  • 68% of these calls end with a yes, compared with 44% of all the calls in the testing periods: 1.5 times as many.

This is a smaller gain than in Part 2, where the top 20% reached about two thirds of the subscribers. But it is an honest estimate of what the bank could expect from a model trained on the past.

Conclusions

  • When the data covers a period of time, the way we test a model matters as much as the model itself. A random testing set lets the model learn from the same period that it is tested on, and it gives a much too good picture.
  • In a walk-forward evaluation, every step that learns from data, including the choice of the hyperparameters, the preparation of the features and the features that describe the recent past, must use the training window only. Then the testing period is truly unseen.
  • On truly unseen calls, the models rank the clients within a month moderately well, and calling the top 20% of each month gives about 1.5 times the success rate of calling at random.
  • The economic features, which looked so useful in Part 2, do not help a model that predicts the future: the economy of the next months is outside what the model has seen.
  • Even the hyperparameters of Part 2, chosen with perfect foresight, do not make the models better. The models of Part 2 looked good because they learned from the same months that they were tested on, not because of their hyperparameters.
  • Looking back at this period, a sliding window of recent months adapted faster than an expanding window of all the past months when the behavior of the clients changed, ranked the clients within a month better, and cost less to train. At the time, a bank could not have known this in advance. In practice, it should train its models again often, on recent calls, and watch how well they predict each new month.

Appendix: Window Code

This code runs the sliding and expanding windows. It takes more than an hour, so it does not run each time we build this page. Instead, the page saves the results in the file Bank_Windows.Rda, together with a fingerprint (a hash) of the inputs: the clean data from Part 1 and the code itself. When we build the page again, it calculates the fingerprint again:

  • If the fingerprint is the same, the page loads the saved results in a few seconds.
  • If the data or any part of the code has changed, the page runs the windows again and saves the new results.

Changes to the comments or the spacing of the code do not count as changes. To run the windows again without any change, delete Bank_Windows.Rda.

These steps prepare the data, the features, the cycles and the models:

# How the window code is built:
#   1. Each cycle has a training window and a testing period of the next 3 months, and the next cycle starts 3 months
#      later. Two kinds of training windows are compared on the same testing periods:
#        sliding:   the 12 calendar months before the testing period.
#        expanding: all the months from the first usable month (June 2008) to the month before the testing period.
#                   It starts with the same 12 months as the sliding window, and grows by 3 months in each cycle.
#      Hyperparameters are tuned within each training window only, so no information from the testing period or later
#      is used (no lookahead). The Part 2 hyperparameters are not reused, because they were tuned on calls from the
#      whole period.
#   2. Within a training window, the hyperparameters are tuned by racing with 5-fold cross validation, as in Part 2.
#      The folds are random within the window: they do not need to respect time, because all of them come before the
#      testing period.
#   3. Three feature sets are compared: the client and campaign features only, these plus the five economic features
#      (their levels, as in Part 2), and these plus three trend features that describe how the economy and the campaign
#      changed (see "Trend features").
#   4. Two models are compared: glmnet (regularized logistic regression) and xgboost. Plain logistic regression is not
#      used, because the later training windows have only a few thousand calls and ~50 predictors, where an
#      unregularized model is unstable. ranger is not used, because it was the slowest to tune in Part 2, and it did
#      not do better than xgboost.
#   5. The cycles run one after another; within a cycle, the tuning runs in parallel (see "Parallel backend").
#   6. A cycle whose training window and testing period are the same as those of an earlier cycle is not run again:
#      its results are reused. This is the case for the first cycle, where both windows are the same 12 months.

# load the clean dataset and the dates of the calls from Part 1 (bank_data_file is set in the "window_cache" chunk)
load(bank_data_file)

dfCalls <- dfClean %>%
    inner_join(dfCallDates, by = "Id") %>%
    arrange(Id)

# Trend features
########################################################################################################################################################
# Calculated from past months only:
#   euribor_change:  the 3 month Euribor on the day of the call, minus its average in a reference month.
#   employed_change: the number of employees (nr.employed) at the time of the call, minus its average in the
#                    reference month.
#   prev_month_rate: the subscription rate in the reference month.
# For the calls in a training window, the reference month is the previous month with calls (some months have no calls:
# January, February and September 2008). For the calls in a testing period, it is the last month of the training
# window, for all 3 testing months (see "Run the cycles"). Otherwise, in the 2nd and 3rd testing months,
# prev_month_rate would use the results of calls in the testing period, which the model must not see.
# Euribor and employment on the day of a call are published economic data, known at the time of the call.
# The first month, May 2008, has no previous month, so its calls are left out.
dfMonthly <- dfCalls %>%
    group_by(year_month) %>%
    summarise(calls = n(), rate = mean(y == "yes"), euribor_mean = mean(euribor3m), employed_mean = mean(nr.employed)) %>%
    arrange(year_month) %>%
    mutate(prev_euribor = lag(euribor_mean), prev_employed = lag(employed_mean), prev_month_rate = lag(rate))

dfCalls <- dfCalls %>%
    inner_join(dfMonthly %>% select(year_month, prev_euribor, prev_employed, prev_month_rate), by = "year_month") %>%
    mutate(euribor_change = euribor3m - prev_euribor,
           employed_change = nr.employed - prev_employed) %>%
    select(-prev_euribor, -prev_employed) %>%
    filter(!is.na(prev_month_rate))

vFeaturesEconomic <- c("emp.var.rate", "cons.price.idx", "cons.conf.idx", "euribor3m", "nr.employed")
vFeaturesTrend <- c("euribor_change", "employed_change", "prev_month_rate")

# predictors left out of each feature set (Id, year and year_month are never predictors)
lFeatureSets <- list("client and campaign" = c(vFeaturesEconomic, vFeaturesTrend),
                     "+ economic levels" = vFeaturesTrend,
                     "+ economic trends" = vFeaturesEconomic)


# Cycles
########################################################################################################################################################
# The first testing period starts 12 calendar months after the first usable month (June 2008), so that every training
# window has at least 12 full months. Each cycle tests the next 3 months, and the next cycle starts 3 months later,
# until the last month of the data. Both kinds of windows use the same testing periods.
first_month <- min(dfCalls$year_month)
last_month <- max(dfCalls$year_month)
dfTestPeriods <- tibble(test_start = seq(first_month %m+% months(12), last_month, by = "3 months")) %>%
    mutate(cycle = row_number(), test_end = test_start %m+% months(2))
dfCycles <- bind_rows(sliding = dfTestPeriods %>% mutate(train_start = test_start %m-% months(12)),
                      expanding = dfTestPeriods %>% mutate(train_start = first_month),
                      .id = "window") %>%
    mutate(train_end = test_start %m-% months(1),
           train_first = as.Date(NA), train_last = as.Date(NA), test_first = as.Date(NA), test_last = as.Date(NA),
           train_calls = NA_integer_, train_rate = NA_real_, test_calls = NA_integer_, test_rate = NA_real_)

# Preprocessing Recipe
########################################################################################################################################################
# As in Part 2: dummy variables, log of right-skewed features, and removal of single-value predictors and exact linear
# combinations. It is prepared on the training window of each cycle only, and so is the choice of the skewed features.
vFeaturesClientNum <- c("age", "campaign", "previous")
get_preprocessing_recipe <- function(df) {

    vFeaturesSkew <- df %>%
        select(all_of(vFeaturesClientNum)) %>%
        select_if(function(Z) timeDate::skewness(Z, na.rm = T) > 0.75) %>%
        colnames()

    recipe(y ~ ., data = df) %>%
        update_role(Id, year, year_month, new_role = "ID") %>%
        step_mutate_at(all_of(vFeaturesSkew), fn = ~ log(. + 1)) %>%
        step_dummy(all_nominal_predictors()) %>%
        step_zv(all_predictors()) %>%
        step_intercept() %>%
        step_lincomb(all_numeric_predictors()) %>%
        step_rm(any_of("intercept")) %>%
        prep()
}

# Models and grids
########################################################################################################################################################
class_metrics <- metric_set(roc_auc, pr_auc, mn_log_loss)

get_model_spec <- function(modelType) {
    switch(modelType,
           glmnet = logistic_reg(mode = "classification", penalty = tune(), mixture = tune()) %>%
               set_engine("glmnet"),
           xgboost = boost_tree(mode = "classification", trees = 1000, min_n = tune(), tree_depth = tune(),
                                learn_rate = tune()) %>%
               set_engine("xgboost", nthread = 1))
}

# The same grids as in Part 2 (glmnet: 20 penalties x 5 mixtures; xgboost: a space-filling grid over the same ranges),
# with 10 instead of 25 xgboost combinations, because the tuning runs 18 times (6 cycles x 3 feature sets). In a test
# run with 4 xgboost combinations, xgboost already took 9 minutes over the 18 tuning runs. The ranges are not narrowed
# with what Part 2 found, because Part 2 tuned on calls from the whole period (that would be a lookahead).
get_model_param_grid <- function(modelType, randomSeed = 2300) {
    if(modelType == "glmnet") {
        return(grid_regular(penalty(), mixture(), levels = c(penalty = 20, mixture = 5)))
    }
    set.seed(randomSeed)
    grid_space_filling(parameters(min_n(), tree_depth(), learn_rate(range = c(-2.5, -0.5))), size = 10, type = "max_entropy")
}

# !! puts the names in vExclude into the workflow itself. Without it, the workflow keeps a reference to the variable,
# which the parallel workers cannot find.
get_workflow <- function(model_spec, vExclude) {
    workflow() %>%
        add_variables(outcomes = y, predictors = c(-Id, -year, -year_month, -any_of(!!vExclude))) %>%
        add_model(model_spec)
}

# Tune a model on the training window with racing, train it with the best combination on the whole window, and
# predict the testing period
tune_fit_predict <- function(dfTrain_Proc, dfTest_Proc, modelType, vExclude, randomSeed = 2300) {

    model_spec <- get_model_spec(modelType)
    set.seed(randomSeed)
    folds <- vfold_cv(dfTrain_Proc, v = 5, strata = y)
    race <- get_workflow(model_spec, vExclude) %>%
        finetune::tune_race_anova(resamples = folds,
                                  grid = get_model_param_grid(modelType, randomSeed),
                                  metrics = class_metrics,
                                  control = finetune::control_race(burn_in = 3, parallel_over = "everything"))
    params_best <- select_best(race, metric = "roc_auc")
    set.seed(randomSeed)
    model_final <- get_workflow(model_spec, vExclude) %>%
        finalize_workflow(params_best) %>%
        fit(data = dfTrain_Proc)

    list(params = params_best %>% select(-.config),
         cv_roc_auc = show_best(race, metric = "roc_auc", n = 1)$mean,
         predictions = dfTest_Proc %>%
             select(Id, year_month, y) %>%
             mutate(.pred_yes = predict(model_final, dfTest_Proc, type = "prob")$.pred_yes))
}


# Parallel backend
########################################################################################################################################################
# As in Part 2: workers are capped at cores - 1 and at what fits in 70% of the available RAM, at 0.75 GB per worker.
gb_per_worker <- 0.75
gb_available <- ps::ps_system_memory()$avail / 1024^3
num_workers <- max(1, min(parallel::detectCores() - 1, floor(0.7 * gb_available / gb_per_worker)))
message(sprintf("Using %d parallel workers (%.1f GB RAM available)", num_workers, gb_available))
plan(multisession, workers = num_workers)

These steps run the cycles of both kinds of windows:

# Run the cycles
########################################################################################################################################################
lResults <- list()
lDone <- list()     # results of each training window and testing period that has been run, to reuse them
dfTimings <- tibble(window = character(), cycle = integer(), model = character(), feature_set = character(),
                    seconds = numeric(), reused = logical())
for (i in seq_len(nrow(dfCycles))) {

    cycle <- dfCycles[i, ]
    cycle_key <- paste(cycle$train_start, cycle$train_end, cycle$test_start, cycle$test_end)
    dfTrain <- dfCalls %>% filter(year_month >= cycle$train_start, year_month <= cycle$train_end)
    dfTest <- dfCalls %>% filter(year_month >= cycle$test_start, year_month <= cycle$test_end)

    # The testing period must be unseen: every training call comes before every testing call, and no call is in both
    stopifnot(max(dfTrain$year_month) < min(dfTest$year_month),
              length(intersect(dfTrain$Id, dfTest$Id)) == 0)

    # Trend features of the testing calls, relative to the last month of the training window (see "Trend features")
    reference_month <- dfMonthly %>% filter(year_month == max(dfTrain$year_month))
    dfTest <- dfTest %>%
        mutate(euribor_change = euribor3m - reference_month$euribor_mean,
               employed_change = nr.employed - reference_month$employed_mean,
               prev_month_rate = reference_month$rate)

    preprocessing_recipe <- get_preprocessing_recipe(dfTrain)
    dfTrain_Proc <- bake(preprocessing_recipe, new_data = NULL)
    dfTest_Proc <- bake(preprocessing_recipe, new_data = dfTest)

    for (feature_set in names(lFeatureSets)) {
        for (modelType in c("glmnet", "xgboost")) {
            task_key <- paste(cycle_key, feature_set, modelType)
            reused <- !is.null(lDone[[task_key]])
            t0 <- Sys.time()
            if (!reused) {
                lDone[[task_key]] <- tune_fit_predict(dfTrain_Proc, dfTest_Proc, modelType, lFeatureSets[[feature_set]])
            }
            result <- lDone[[task_key]]
            dfTimings <- dfTimings %>% add_row(window = cycle$window, cycle = cycle$cycle, model = modelType,
                                               feature_set = feature_set, reused = reused,
                                               seconds = as.numeric(difftime(Sys.time(), t0, units = "secs")))
            lResults[[length(lResults) + 1]] <- list(window = cycle$window, cycle = cycle$cycle, model = modelType,
                                                     feature_set = feature_set, params = result$params,
                                                     cv_roc_auc = result$cv_roc_auc, predictions = result$predictions)
        }
    }
    dfCycles$train_first[i] <- min(dfTrain$year_month)
    dfCycles$train_last[i] <- max(dfTrain$year_month)
    dfCycles$test_first[i] <- min(dfTest$year_month)
    dfCycles$test_last[i] <- max(dfTest$year_month)
    dfCycles$train_calls[i] <- nrow(dfTrain)
    dfCycles$train_rate[i] <- mean(dfTrain$y == "yes")
    dfCycles$test_calls[i] <- nrow(dfTest)
    dfCycles$test_rate[i] <- mean(dfTest$y == "yes")
}

plan(sequential)

# predictions for every call of every testing period, by window, model and feature set
dfWindowPred <- map_dfr(lResults, ~ .x$predictions %>% mutate(window = .x$window, cycle = .x$cycle, model = .x$model,
                                                              feature_set = .x$feature_set))

# the hyperparameters chosen in each cycle, with their cross validated ROC AUC within the training window
dfCycleParams <- map_dfr(lResults, ~ tibble(window = .x$window, cycle = .x$cycle, model = .x$model,
                                            feature_set = .x$feature_set, cv_roc_auc = .x$cv_roc_auc,
                                            params = list(.x$params)))

# the results that the post uses, which are saved to Bank_Windows.Rda
vWindowResults <- c("dfWindowPred", "dfCycleParams", "dfCycles", "dfMonthly", "dfTimings", "num_workers",
                    "vFeaturesEconomic", "vFeaturesTrend", "lFeatureSets")

And this code decides whether to load the saved results or to run the windows:

# The clean dataset and the dates of the calls from Part 1
bank_data_file <- "../bank-marketing-part1-eda/Bank_Marketing_Clean.Rda"

# Fingerprint (hash) of the inputs: the data that the code uses, and the code of the "window_setup" and "window_runs"
# chunks. Comments and spacing are removed from the code first, so editing them does not start a new run.
envData <- new.env()
load(bank_data_file, envir = envData)
window_steps <- c(knitr::knit_code$get("window_setup"), knitr::knit_code$get("window_runs"))
window_hash <- rlang::hash(list(data = list(envData$dfClean, envData$dfCallDates),
                                code = deparse(parse(text = window_steps, keep.source = FALSE))))

# If the saved results were made from the same inputs, load them. Otherwise, run the windows again and save the new
# results together with the fingerprint of their inputs.
envSaved <- new.env()
if (file.exists("Bank_Windows.Rda")) load("Bank_Windows.Rda", envir = envSaved)
if (identical(envSaved$window_hash, window_hash)) {
  list2env(as.list(envSaved), envir = environment())
} else {
  eval(parse(text = window_steps))
  save(list = c(vWindowResults, "window_hash"), file = "Bank_Windows.Rda")
}
rm(envData, envSaved)

Perfect Foresight Code

This code trains the models with the hyperparameters chosen in Part 2, in every cycle of both kinds of windows. It uses the data, the features, the cycles and the functions of the steps above. Its results are saved in Bank_Foresight.Rda, with their own fingerprint, which also includes the hyperparameters of Part 2.

# Perfect foresight: the hyperparameters chosen in Part 2
########################################################################################################################################################
# Part 2 chose the hyperparameters by cross validation on a random sample of the calls of the whole period, including
# the testing periods here, so they were chosen with knowledge of the future (perfect foresight). Here, each model is
# trained in every cycle with those hyperparameters, without tuning, on the same training windows as above, and tested
# on the same testing periods. Part 2 tuned the models with all the features (like the "+ economic levels" set); the
# same hyperparameters are used with every feature set.
envPart2 <- new.env()
load(part2_tuning_file, envir = envPart2)
lParamsForesight <- list(glmnet = envPart2$param_best_glmnet, xgboost = envPart2$param_best_xgboost)
rm(envPart2)

# Train a model with the given hyperparameters on the training window, and predict the testing period
fit_predict_fixed <- function(dfTrain_Proc, dfTest_Proc, modelType, vExclude, params, randomSeed = 2300) {

    set.seed(randomSeed)
    model_final <- get_workflow(get_model_spec(modelType), vExclude) %>%
        finalize_workflow(params) %>%
        fit(data = dfTrain_Proc)
    dfTest_Proc %>%
        select(Id, year_month, y) %>%
        mutate(.pred_yes = predict(model_final, dfTest_Proc, type = "prob")$.pred_yes)
}

# The same steps as in "Run the cycles", with the fixed hyperparameters instead of tuning. The 6 models of a cycle
# (2 models x 3 feature sets) are trained in parallel. As above, a cycle with the same training window and testing
# period as an earlier cycle (the first cycle) reuses its results.
lForesight <- list()
lDoneForesight <- list()
dfForesightTimings <- tibble(window = character(), cycle = integer(), seconds = numeric(), reused = logical())
for (i in seq_len(nrow(dfCycles))) {

    cycle <- dfCycles[i, ]
    cycle_key <- paste(cycle$train_start, cycle$train_end, cycle$test_start, cycle$test_end)
    reused <- !is.null(lDoneForesight[[cycle_key]])
    t0 <- Sys.time()

    if (!reused) {
        dfTrain <- dfCalls %>% filter(year_month >= cycle$train_start, year_month <= cycle$train_end)
        dfTest <- dfCalls %>% filter(year_month >= cycle$test_start, year_month <= cycle$test_end)

        # The testing period must be unseen: every training call comes before every testing call, and no call is in both
        stopifnot(max(dfTrain$year_month) < min(dfTest$year_month),
                  length(intersect(dfTrain$Id, dfTest$Id)) == 0)

        # Trend features of the testing calls, relative to the last month of the training window (see "Trend features")
        reference_month <- dfMonthly %>% filter(year_month == max(dfTrain$year_month))
        dfTest <- dfTest %>%
            mutate(euribor_change = euribor3m - reference_month$euribor_mean,
                   employed_change = nr.employed - reference_month$employed_mean,
                   prev_month_rate = reference_month$rate)

        preprocessing_recipe <- get_preprocessing_recipe(dfTrain)
        dfTrain_Proc <- bake(preprocessing_recipe, new_data = NULL)
        dfTest_Proc <- bake(preprocessing_recipe, new_data = dfTest)

        dfTasks <- expand_grid(feature_set = names(lFeatureSets), model = c("glmnet", "xgboost"))
        lPred <- furrr::future_map2(dfTasks$feature_set, dfTasks$model, function(feature_set, modelType) {
            fit_predict_fixed(dfTrain_Proc, dfTest_Proc, modelType, lFeatureSets[[feature_set]],
                              lParamsForesight[[modelType]]) %>%
                mutate(feature_set = feature_set, model = modelType)
        }, .options = furrr::furrr_options(seed = TRUE, packages = c("tidymodels", "glmnet", "xgboost")))
        lDoneForesight[[cycle_key]] <- bind_rows(lPred)
    }

    dfForesightTimings <- dfForesightTimings %>%
        add_row(window = cycle$window, cycle = cycle$cycle, reused = reused,
                seconds = as.numeric(difftime(Sys.time(), t0, units = "secs")))
    lForesight[[i]] <- lDoneForesight[[cycle_key]] %>% mutate(window = cycle$window, cycle = cycle$cycle)
}

plan(sequential)

# predictions for every call of every testing period, by window, model and feature set
dfForesightPred <- bind_rows(lForesight)

# the results that the post uses, which are saved to Bank_Foresight.Rda
vForesightResults <- c("dfForesightPred", "dfForesightTimings", "lParamsForesight")

And this code decides whether to load the saved results or to train the models again:

# The clean dataset from Part 1 and the tuning results of Part 2
bank_data_file <- "../bank-marketing-part1-eda/Bank_Marketing_Clean.Rda"
part2_tuning_file <- "../bank-marketing-part2-models/Bank_Tuning.Rda"

# Fingerprint (hash) of the inputs: the data, the hyperparameters of Part 2, and the code of the "window_setup" and
# "foresight_steps" chunks. Comments and spacing are removed from the code first.
envData <- new.env()
load(bank_data_file, envir = envData)
load(part2_tuning_file, envir = envData)
foresight_code <- c(knitr::knit_code$get("window_setup"), knitr::knit_code$get("foresight_steps"))
foresight_hash <- rlang::hash(list(data = list(envData$dfClean, envData$dfCallDates),
                                   params = list(envData$param_best_glmnet, envData$param_best_xgboost),
                                   code = deparse(parse(text = foresight_code, keep.source = FALSE))))

# If the saved results were made from the same inputs, load them. Otherwise, train the models again in a separate
# environment (so that the setup steps do not replace the results of the windows that this page has loaded), and save
# the new results together with the fingerprint of their inputs.
envSaved <- new.env()
if (file.exists("Bank_Foresight.Rda")) load("Bank_Foresight.Rda", envir = envSaved)
if (identical(envSaved$foresight_hash, foresight_hash)) {
  list2env(as.list(envSaved), envir = environment())
} else {
  envRun <- new.env()
  eval(parse(text = foresight_code), envir = envRun)
  envRun$foresight_hash <- foresight_hash
  save(list = c(envRun$vForesightResults, "foresight_hash"), envir = envRun, file = "Bank_Foresight.Rda")
  list2env(mget(envRun$vForesightResults, envir = envRun), envir = environment())
  rm(envRun)
}
rm(envData, envSaved)

Related