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
)Model Step 1 - Train and Deploy Model
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:
- pinned to Posit Connect
- deployed as a plumber API to Posit Connect using vetiver.
Get data
Connect to the database:
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 (186,971 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-11-13 (2,225,229 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, 0Fit 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: 186971
## Number of independent variables: 12
## Mtry: 3
## Target node size: 5
## Variable importance mode: none
## Splitrule: variance
## OOB prediction error (MSE): 8.182708
## R squared (OOB): 0.7496369Model 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.81 3.80 0.443 0.219Model 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-11-13"
# 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 featurespins
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::e0104ce5-5024-43cd-b374-12c7d9bf0ea4 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::e0104ce5-5024-43cd-b374-12c7d9bf0ea4 which has version 4.4.1
## Performing manifest.json to packrat transformation.
## Determining session server location ...
## [connect-session] Content GUID: 6570e768-2118-4e5c-aee5-97b7027ab1b0
## [connect-session] Content ID: 442
## [connect-session] Bundle ID: 8848
## [connect-session] Job Key: Gf6ddejp7eKBgzlU
## [connect-session] WARNING: Publishing with rsconnect or Publisher, upgrade for the generated manifest.json to follow version constraints best practices.
## [connect-session] For more details on version matching, see https://docs.posit.co/connect/admin/r/#r-version-matching
## Running on host: packrat-restore-t72kt-c9fbr
## Process ID: 31
## Linux distribution: Ubuntu 22.04.5 LTS (jammy)
## Running as user: uid=999 gid=999 groups=999
## Connect version: 2025.09.1
## 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 --------------------------------------
## Vendored packrat archive: /opt/rstudio-connect/ext/R/packrat_0.9.2.9000_b44ff11f4c1e42a04461e2d46673512d8d900eb5.tar.gz
## Vendored packrat SHA: b44ff11f4c1e42a04461e2d46673512d8d900eb5
## Managed packrat SHA: b44ff11f4c1e42a04461e2d46673512d8d900eb5
## Managed packrat version: 0.9.2.9000
## Managed packrat is up-to-date.
## # 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
## # Setting packrat options and preparing lockfile -------------------------------
## Audited package hashes with local packrat installation.
## # Resolving R package repositories ---------------------------------------------
## Received repositories from Connect's configuration:
## - RSPM = "https://pkg.current.posit.team/cran/__linux__/jammy/latest"
## - CRAN = "https://pkg.current.posit.team/cran/__linux__/jammy/latest"
## Connecting to session server http://service-b28a503a-798b-4e05-9c0e-a211654d29b1.posit-team:50734 ...
## Connected to session server http://service-b28a503a-798b-4e05-9c0e-a211654d29b1.posit-team:50734
## 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:
## - RSPM = "https://pkg.current.posit.team/cran/__linux__/jammy/latest"
## - CRAN = "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)
## Installing curl (5.2.3) ...
## OK (symlinked cache)
## Installing data.table (1.16.0) ...
## OK (symlinked cache)
## Installing digest (0.6.36) ...
## OK (symlinked cache)
## Installing fansi (1.0.6) ...
## OK (symlinked cache)
## 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)
## Installing gower (1.0.1) ...
## OK (symlinked cache)
## Installing isoband (0.2.7) ...
## OK (symlinked cache)
## Installing jsonlite (1.8.9) ...
## OK (symlinked cache)
## 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)
## 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)
## 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)
## Installing utf8 (1.2.4) ...
## OK (symlinked cache)
## Installing viridisLite (0.4.2) ...
## OK (symlinked cache)
## Installing whisker (0.4.1) ...
## OK (symlinked cache)
## Installing withr (3.0.1) ...
## OK (symlinked cache)
## 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)
## 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)
## 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)
## Installing diagram (1.6.5) ...
## OK (symlinked cache)
## Installing askpass (1.2.0) ...
## OK (symlinked cache)
## Installing future (1.34.0) ...
## OK (symlinked cache)
## 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)
## 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)
## Installing future.apply (1.11.2) ...
## OK (symlinked cache)
## Installing httpuv (1.6.15) ...
## OK (symlinked cache)
## 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)
## Installing progress (1.2.3) ...
## OK (symlinked cache)
## Installing tibble (3.2.1) ...
## OK (symlinked cache)
## 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)
## Installing dplyr (1.1.4) ...
## OK (symlinked cache)
## Installing ggplot2 (3.5.1) ...
## OK (symlinked cache)
## Installing hardhat (1.4.0) ...
## OK (symlinked cache)
## Installing modelenv (0.1.1) ...
## OK (symlinked cache)
## Installing pins (1.3.0) ...
## OK (symlinked cache)
## 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::e0104ce5-5024-43cd-b374-12c7d9bf0ea4 against R version: '4.4.1'
## Stopped session pings to http://service-b28a503a-798b-4e05-9c0e-a211654d29b1.posit-team:50734
## Launching Plumber API...DBI::dbDisconnect(con)