Model Step 1 - Train and Deploy Model

Published

April 8, 2025

This notebook trains a model to predict the number of bikes at a given bike docking station. The model is trained using the bike_model_data table from Content DB. The trained model is then:

Get data

Connect to the database:

con <- DBI::dbConnect(
  odbc::odbc(),
  Driver      = "postgresql",
  Server      = Sys.getenv("DB_SERVER"),
  Port        = "5432",
  Database    = "soleng",
  UID         = Sys.getenv("DB_USER"),
  PWD         = Sys.getenv("DB_PASSWORD"),
  BoolsAsChar = "",
  timeout     = 10
)

Split the data into a train/test split:

all_days <- tbl(con, DBI::Id(schema="content", name="bike_model_data"))

# Get a vector that contains all of the dates.
dates <- all_days %>%
  distinct(date) %>%
  collect() %>%
  arrange(desc(date)) %>%
  pull(date) %>%
  as.Date()

# Split the data into test and train.
n_days_test <- 2
n_days_to_train <- 10

# TODO: FIX THIS. UPSTREAM DATA STOPPED PROVIDING HOURLY DATA. HAD TO PIN TO FIXED DATE RANGE FOR MODEL.
train_end_date <- as.Date("2024-01-05")
train_start_date <- as.Date("2023-12-10")
# train_end_date <- dates[n_days_test + 1]
# train_start_date <- train_end_date - n_days_to_train

# Training data split.
train_data <- all_days %>%
  filter(
    date >= train_start_date,
    date <= train_end_date
  ) %>%
  distinct() %>%
  collect()

start = min(train_data$date)
end = max(train_data$date)
num_obs = scales::comma(nrow(train_data))

print(glue::glue(
  "The model will be trained on data from {start} to {end} ",
  "({num_obs} observations). "))
## The model will be trained on data from 2023-12-10 to 2024-01-05 (190,569 observations).

# Test data split.
test_data <- all_days %>%
  filter(date > train_end_date) %>%
  distinct() %>%
  collect()

start = min(test_data$date)
end = max(test_data$date)
num_obs = scales::comma(nrow(test_data))

print(glue::glue(
  "The model will be tested on data from {start} to {end} ",
  "({num_obs} observations). "))
## The model will be tested on data from 2024-01-06 to 2025-03-24 (2,076,875 observations).

Train the model

Data preprocessing

Define a recipe to clean the data.

# Define a recipe to clean the data.
recipe_spec <- 
  recipe(n_bikes ~ ., data = train_data) %>% 
  step_dummy(dow) %>%
  step_integer(id, date)

# Preview the cleaned training data.
recipe_spec %>% 
  prep(train_data) %>% 
  bake(head(train_data)) %>%
  glimpse()
## Rows: 6
## Columns: 13
## $ id            <int> 1, 1, 1, 1, 1, 1
## $ hour          <dbl> 0, 0, 0, 0, 0, 0
## $ date          <int> 1, 2, 3, 4, 6, 7
## $ month         <dbl> 12, 12, 12, 12, 12, 12
## $ lat           <dbl> 38.87035, 38.87035, 38.87035, 38.87035, 38.87035, 38.870…
## $ lon           <dbl> -76.94528, -76.94528, -76.94528, -76.94528, -76.94528, -…
## $ n_bikes       <dbl> 1, 1, 1, 0, 0, 0
## $ dow_Monday    <dbl> 0, 1, 0, 0, 0, 0
## $ dow_Saturday  <dbl> 0, 0, 0, 0, 0, 1
## $ dow_Sunday    <dbl> 1, 0, 0, 0, 0, 0
## $ dow_Thursday  <dbl> 0, 0, 0, 0, 0, 0
## $ dow_Tuesday   <dbl> 0, 0, 1, 0, 0, 0
## $ dow_Wednesday <dbl> 0, 0, 0, 1, 0, 0

Fit model

Fit a random forest model:

model_spec <- 
  rand_forest() %>%
  set_mode("regression") %>%
  set_engine("ranger")

model_workflow <- 
  workflow() %>%
  add_recipe(recipe_spec) %>%
  add_model(model_spec)

model_fit <- fit(model_workflow, data = train_data)
model_fit
## ══ Workflow [trained] ══════════════════════════════════════════════════════════
## Preprocessor: Recipe
## Model: rand_forest()
## 
## ── Preprocessor ────────────────────────────────────────────────────────────────
## 2 Recipe Steps
## 
## • step_dummy()
## • step_integer()
## 
## ── Model ───────────────────────────────────────────────────────────────────────
## Ranger result
## 
## Call:
##  ranger::ranger(x = maybe_data_frame(x), y = y, num.threads = 1,      verbose = FALSE, seed = sample.int(10^5, 1)) 
## 
## Type:                             Regression 
## Number of trees:                  500 
## Sample size:                      190569 
## Number of independent variables:  12 
## Mtry:                             3 
## Target node size:                 5 
## Variable importance mode:         none 
## Splitrule:                        variance 
## OOB prediction error (MSE):       8.415987 
## R squared (OOB):                  0.7462415

Model evaluation

predictions <- predict(model_fit, test_data)

results <- test_data %>%
  mutate(preds = predictions$.pred)

oos_metrics(results$n_bikes, results$preds)
## # A tibble: 1 × 4
##    rmse   mae   ccc    r2
##   <dbl> <dbl> <dbl> <dbl>
## 1  4.76  3.77 0.458 0.244

Model deployment

vetiver

Create a vetiver model object.

model_name <- "bike_predict_model_r"
pin_name <- glue("katie.masiello@posit.co/{model_name}")

# Get the train and test data ranges. This will be passed into the pin metadata
# so that other scripts can access this information.
date_metadata <- list(
  train_dates = c(
    as.character(min(train_data$date)), 
    as.character(max(train_data$date))
  ),
  test_dates = c(
    as.character(min(test_data$date)), 
    as.character(max(test_data$date))
  )
)

print(date_metadata)
## $train_dates
## [1] "2023-12-10" "2024-01-05"
## 
## $test_dates
## [1] "2024-01-06" "2025-03-24"

# Create the vetiver model.
v <- vetiver_model(
  model_fit, 
  model_name,
  versioned = TRUE,
  save_ptype = train_data %>%
    head(1) %>%
    select(-n_bikes),
  metadata = date_metadata
)

v
## 
## ── bike_predict_model_r ─ <bundled_workflow> model for deployment 
## A ranger regression modeling workflow using 7 features

pins

Save the model as a pin to Posit Connect:

# Use Posit Connect as a board.
board <- pins::board_connect(
  server = Sys.getenv("CONNECT_SERVER"),
  key = Sys.getenv("CONNECT_API_KEY"),
  versioned = TRUE
)
# Write the model to the board.
board %>%
 vetiver_pin_write(vetiver_model = v)

plumber

Then, deploy the model as a plumber API to Posit Connect.

# Add server
rsconnect::addServer(
  url = "https://pub.current.posit.team/__api__",
  name = "pub.current"
)

# Add account
rsconnect::connectApiUser(
  account = "katie.masiello@posit.co",
  server = "pub.current",
  apiKey = Sys.getenv("CONNECT_API_KEY"),
)

# Deploy to Connect
vetiver_deploy_rsconnect(
  board = board,
  name = pin_name,
  appId = "442",
  launch.browser = FALSE,
  appTitle = "Bikeshare Prediction: 03b - Model - API",
  predict_args = list(debug = FALSE),
  account = "katie.masiello@posit.co",
  server =  "pub.current"
)
## Building Plumber API...
## Bundle created with R version 4.4.1 is compatible with environment Kubernetes::654654567442.dkr.ecr.us-east-2.amazonaws.com/ptd-adhoc-pct:content-r4.4.1-py3.10.14-quarto1.4.557 with R version 4.4.1 from /opt/R/4.4.1/bin/R 
## Bundle requested R version 4.4.1; using /opt/R/4.4.1/bin/R from Kubernetes::654654567442.dkr.ecr.us-east-2.amazonaws.com/ptd-adhoc-pct:content-r4.4.1-py3.10.14-quarto1.4.557 which has version 4.4.1
## Performing manifest.json to packrat transformation.
## Determining session server location ...
## [rsc-session] Content GUID: 6570e768-2118-4e5c-aee5-97b7027ab1b0
## 
## [rsc-session] Content ID: 442
## 
## [rsc-session] Bundle ID: 3270
## 2025/04/08 15:58:09.049538728 [rsc-session] Job Key: VSrpHdcG8uo7Gunl
## 
## Connecting to session server http://service-b6751c68-677c-444c-a3df-fa9b45ffdf4e.posit-team:50734 ...
## Connected to session server http://service-b6751c68-677c-444c-a3df-fa9b45ffdf4e.posit-team:50734
## Running on host: packrat-restore-zvk4b-gdrg2
## 2025/04/08 15:58:09.581548119 Process ID: 39
## 
## Linux distribution: Ubuntu 22.04.5 LTS (jammy)
## 
## Running as user: uid=999 gid=999 groups=999
## 
## Connect version: 2025.03.0
## 
## LANG: en_US.UTF-8
## 
## Working directory: /opt/rstudio-connect/mnt/app
## 
## Using R 4.4.1
## 
## R.home(): /opt/R/4.4.1/lib/R
## 
## Using user agent string: 'RStudio R (4.4.1 x86_64-pc-linux-gnu x86_64 linux-gnu)' 
## 
## Configuring packrat to use available credentials for private repository access.
## 
## # Validating R library read / write permissions --------------------------------
## 
## Using R library for packrat bootstrap: /opt/rstudio-connect/mnt/R/654654567442.dkr.ecr.us-east-2.amazonaws.com_ptd-adhoc-pct__content-r4.4.1-py3.10.14-quarto1.4.557/4.4.1
## 
## # Validating managed packrat installation --------------------------------------
## 2025/04/08 15:58:09.597886501 Vendored packrat archive: /opt/rstudio-connect/ext/R/packrat_0.9.2.9000_70625806c44bda42a7f3aeaa92ee65542cc590be.tar.gz
## 
## Vendored packrat SHA: 70625806c44bda42a7f3aeaa92ee65542cc590be
## 
## Managed packrat SHA:  70625806c44bda42a7f3aeaa92ee65542cc590be
## 
## Managed packrat version: 0.9.2.9000
## 
## Managed packrat is up-to-date.
## 2025/04/08 15:58:09.609470545 # Validating packrat cache read / write permissions ----------------------------
## 
## Using packrat cache directory: /opt/rstudio-connect/mnt/packrat/654654567442.dkr.ecr.us-east-2.amazonaws.com_ptd-adhoc-pct__content-r4.4.1-py3.10.14-quarto1.4.557/4.4.1
## 2025/04/08 15:58:09.774943211 # Setting packrat options and preparing lockfile -------------------------------
## 
## Audited package hashes with local packrat installation.
## 
## # Resolving R package repositories ---------------------------------------------
## 
## Received repositories from Connect's configuration:
## 
## - CRAN = "https://pkg.current.posit.team/cran/latest"
## 2025/04/08 15:58:10.005755233 - RSPM = "https://pkg.current.posit.team/cran/latest"
## 
## Rewrote Posit Package Manager URLs to install binary packages:
## 
## - Rewrote "CRAN" from "https://pkg.current.posit.team/cran/latest" to "https://pkg.current.posit.team/cran/__linux__/jammy/latest".
## 
## - Rewrote "RSPM" from "https://pkg.current.posit.team/cran/latest" to "https://pkg.current.posit.team/cran/__linux__/jammy/latest".
## 
## Received repositories from published content:
## 
## - CRAN = "https://cloud.r-project.org"
## 
## Combining repositories from configuration and content.
## 
## Packages will be installed using the following repositories:
## 
## - CRAN = "https://pkg.current.posit.team/cran/__linux__/jammy/latest"
## 
## - RSPM = "https://pkg.current.posit.team/cran/__linux__/jammy/latest"
## 
## - CRAN.1 = "https://cloud.r-project.org"
## 
## # Installing required R packages with `packrat::restore()` ---------------------
## 
## Installing KernSmooth (2.23-22) ... 
## 
##  OK (symlinked cache)
## 
## Installing MASS (7.3-61) ... 
## 
##  OK (symlinked cache)
## 
## Installing R6 (2.5.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing RColorBrewer (1.1-3) ... 
## 
##  OK (symlinked cache)
## 
## Installing Rcpp (1.0.13) ... 
## 
##  OK (symlinked cache)
## 
## Installing SQUAREM (2021.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing bit (4.5.0) ... 
## 
##  OK (symlinked cache)
## 
## Installing cli (3.6.3) ... 
## 
##  OK (symlinked cache)
## 
## Installing clipr (0.8.0) ... 
## 
##  OK (symlinked cache)
## 
## Installing codetools (0.2-20) ... 
## 
##  OK (symlinked cache)
## 
## Installing colorspace (2.1-1) ... 
## 
##  OK (symlinked cache)
## 
## Installing cpp11 (0.5.0) ... 
## 
##  OK (symlinked cache)
## 
## Installing crayon (1.5.3) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.524695514 Installing curl (5.2.3) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.531793468 Installing data.table (1.16.0) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.538880963 Installing digest (0.6.36) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.546679091 Installing fansi (1.0.6) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.553571186 Installing farver (2.1.2) ... 
## 
##  OK (symlinked cache)
## 
## Installing fastmap (1.2.0) ... 
## 
##  OK (symlinked cache)
## 
## Installing fs (1.6.4) ... 
## 
##  OK (symlinked cache)
## 
## Installing generics (0.1.3) ... 
## 
##  OK (symlinked cache)
## 
## Installing glue (1.7.0) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.588464998 Installing gower (1.0.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing isoband (0.2.7) ... 
## 
##  OK (symlinked cache)
## 
## Installing jsonlite (1.8.9) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.610060371 Installing labeling (0.4.3) ... 
## 
##  OK (symlinked cache)
## 
## Installing lattice (0.22-6) ... 
## 
##  OK (symlinked cache)
## 
## Installing listenv (0.9.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing magrittr (2.0.3) ... 
## 
##  OK (symlinked cache)
## 
## Installing mime (0.12) ... 
## 
##  OK (symlinked cache)
## 
## Installing nnet (7.3-19) ... 
## 
##  OK (symlinked cache)
## 
## Installing numDeriv (2016.8-1.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing parallelly (1.38.0) ... 
## 
##  OK (symlinked cache)
## 
## Installing pkgconfig (2.0.3) ... 
## 
##  OK (symlinked cache)
## 
## Installing prettyunits (1.2.0) ... 
## 
##  OK (symlinked cache)
## 
## Installing rapidoc (9.3.4) ... 
## 
##  OK (symlinked cache)
## 
## Installing rappdirs (0.3.3) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.700851617 Installing rlang (1.1.4) ... 
## 
##  OK (symlinked cache)
## 
## Installing rpart (4.1.23) ... 
## 
##  OK (symlinked cache)
## 
## Installing shape (1.4.6.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing sodium (1.3.2) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.749428932 Installing stringi (1.8.4) ... 
## 
##  OK (symlinked cache)
## 
## Installing swagger (5.17.14.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing sys (3.4.2) ... 
## 
##  OK (symlinked cache)
## 
## Installing timeDate (4041.110) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.778119382 Installing utf8 (1.2.4) ... 
## 
##  OK (symlinked cache)
## 
## Installing viridisLite (0.4.2) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.793057067 Installing whisker (0.4.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing withr (3.0.1) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.806741017 Installing yaml (2.3.10) ... 
## 
##  OK (symlinked cache)
## 
## Installing class (7.3-22) ... 
## 
##  OK (symlinked cache)
## 
## Installing RcppEigen (0.3.4.0.2) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.827836386 Installing bit64 (4.5.2) ... 
## 
##  OK (symlinked cache)
## 
## Installing globals (0.16.3) ... 
## 
##  OK (symlinked cache)
## 
## Installing munsell (0.5.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing timechange (0.3.0) ... 
## 
##  OK (symlinked cache)
## 
## Installing tzdb (0.4.0) ... 
## 
##  OK (symlinked cache)
## 
## Installing progressr (0.14.0) ... 
## 
##  OK (symlinked cache)
## 
## Installing webutils (1.2.2) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.878204480 Installing Matrix (1.7-0) ... 
## 
##  OK (symlinked cache)
## 
## Installing nlme (3.1-166) ... 
## 
##  OK (symlinked cache)
## 
## Installing ellipsis (0.3.2) ... 
## 
##  OK (symlinked cache)
## 
## Installing later (1.3.2) ... 
## 
##  OK (symlinked cache)
## 
## Installing lifecycle (1.0.4) ... 
## 
##  OK (symlinked cache)
## 
## Installing lobstr (1.1.2) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.919547841 Installing diagram (1.6.5) ... 
## 
##  OK (symlinked cache)
## 
## Installing askpass (1.2.0) ... 
## 
##  OK (symlinked cache)
## 
## Installing future (1.34.0) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.940496202 Installing lubridate (1.9.3) ... 
## 
##  OK (symlinked cache)
## 
## Installing ranger (0.16.0) ... 
## 
##  OK (symlinked cache)
## 
## Installing survival (3.7-0) ... 
## 
##  OK (symlinked cache)
## 
## Installing mgcv (1.9-1) ... 
## 
##  OK (symlinked cache)
## 
## Installing promises (1.3.0) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:10.975220530 Installing gtable (0.3.5) ... 
## 
##  OK (symlinked cache)
## 
## Installing scales (1.3.0) ... 
## 
##  OK (symlinked cache)
## 
## Installing vctrs (0.6.5) ... 
## 
##  OK (symlinked cache)
## 
## Installing openssl (2.2.0) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:11.003067472 Installing future.apply (1.11.2) ... 
## 
##  OK (symlinked cache)
## 
## Installing httpuv (1.6.15) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:11.016453103 Installing clock (0.7.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing hms (1.1.3) ... 
## 
##  OK (symlinked cache)
## 
## Installing pillar (1.9.0) ... 
## 
##  OK (symlinked cache)
## 
## Installing purrr (1.0.2) ... 
## 
##  OK (symlinked cache)
## 
## Installing stringr (1.5.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing tidyselect (1.2.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing httr (1.4.7) ... 
## 
##  OK (symlinked cache)
## 
## Installing lava (1.8.0) ... 
## 
##  OK (symlinked cache)
## 
## Installing plumber (1.2.2) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:11.079125290 Installing progress (1.2.3) ... 
## 
##  OK (symlinked cache)
## 
## Installing tibble (3.2.1) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:11.093385992 Installing bundle (0.1.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing prodlim (2024.06.25) ... 
## 
##  OK (symlinked cache)
## 
## Installing butcher (0.3.4) ... 
## 
##  OK (symlinked cache)
## 
## Installing cereal (0.1.0) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:11.122426253 Installing dplyr (1.1.4) ... 
## 
##  OK (symlinked cache)
## 
## Installing ggplot2 (3.5.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing hardhat (1.4.0) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:11.144274738 Installing modelenv (0.1.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing pins (1.3.0) ... 
## 
##  OK (symlinked cache)
## 2025/04/08 15:58:11.158386392 Installing vroom (1.6.5) ... 
## 
##  OK (symlinked cache)
## 
## Installing ipred (0.9-15) ... 
## 
##  OK (symlinked cache)
## 
## Installing tidyr (1.3.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing readr (2.1.5) ... 
## 
##  OK (symlinked cache)
## 
## Installing parsnip (1.2.1) ... 
## 
##  OK (symlinked cache)
## 
## Installing recipes (1.1.0) ... 
## 
##  OK (symlinked cache)
## 
## Installing vetiver (0.2.5) ... 
## 
##  OK (symlinked cache)
## 
## Installing workflows (1.1.4) ... 
## 
##  OK (symlinked cache)
## 
## Completed packrat build using Kubernetes::654654567442.dkr.ecr.us-east-2.amazonaws.com/ptd-adhoc-pct:content-r4.4.1-py3.10.14-quarto1.4.557 against R version: '4.4.1'
## Stopped session pings to http://service-b6751c68-677c-444c-a3df-fa9b45ffdf4e.posit-team:50734
## Launching Plumber API...
DBI::dbDisconnect(con)