<- DBI::dbConnect(
con ::odbc(),
odbcDriver = "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:
<- tbl(con, DBI::Id(schema="content", name="bike_model_data"))
all_days
# Get a vector that contains all of the dates.
<- all_days %>%
dates distinct(date) %>%
collect() %>%
arrange(desc(date)) %>%
pull(date) %>%
as.Date()
# Split the data into test and train.
<- 2
n_days_test <- 10
n_days_to_train
<- dates[n_days_test + 1]
train_end_date <- train_end_date - n_days_to_train
train_start_date
# Training data split.
<- all_days %>%
train_data filter(
>= train_start_date,
date <= train_end_date
date %>%
) distinct() %>%
collect()
= min(train_data$date)
start = max(train_data$date)
end = scales::comma(nrow(train_data))
num_obs
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 2025-01-04 to 2025-01-14 (8,609 observations).
# Test data split.
<- all_days %>%
test_data filter(date > train_end_date) %>%
distinct() %>%
collect()
= min(test_data$date)
start = max(test_data$date)
end = scales::comma(nrow(test_data))
num_obs
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 2025-01-15 to 2025-01-16 (1,566 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, 5, 6
## $ month <dbl> 1, 1, 1, 1, 1, 1
## $ 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, 1, 1, 1
## $ dow_Monday <dbl> 0, 0, 1, 0, 0, 0
## $ dow_Saturday <dbl> 1, 0, 0, 0, 0, 0
## $ dow_Sunday <dbl> 0, 1, 0, 0, 0, 0
## $ dow_Thursday <dbl> 0, 0, 0, 0, 0, 1
## $ dow_Tuesday <dbl> 0, 0, 0, 1, 0, 0
## $ dow_Wednesday <dbl> 0, 0, 0, 0, 1, 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)
<- fit(model_workflow, data = train_data)
model_fit
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: 8609
## Number of independent variables: 12
## Mtry: 3
## Target node size: 5
## Variable importance mode: none
## Splitrule: variance
## OOB prediction error (MSE): 15.4447
## R squared (OOB): 0.2880662
Model evaluation
<- predict(model_fit, test_data)
predictions
<- test_data %>%
results 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.52 3.59 0.249 0.171
Model deployment
vetiver
Create a vetiver
model object.
<- "bike_predict_model_r"
model_name <- glue("katie.masiello@posit.co/{model_name}")
pin_name
# Get the train and test data ranges. This will be passed into the pin metadata
# so that other scripts can access this information.
<- list(
date_metadata 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] "2025-01-04" "2025-01-14"
##
## $test_dates
## [1] "2025-01-15" "2025-01-16"
# Create the vetiver model.
<- vetiver_model(
v
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.
<- pins::board_connect(
board 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
::addServer(
rsconnecturl = "https://pub.current.posit.team/__api__",
name = "pub.current"
)
# Add account
::connectApiUser(
rsconnectaccount = "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
## 2025/01/17 16:55:59.750895457 [rsc-session] Bundle ID: 1916
## 2025/01/17 16:55:59.750897807 [rsc-session] Job Key: lXpbapk84P62ll0X
## Connecting to session server http://service-a8e1bed6-2796-4e8f-a34d-9e676de35b8b.posit-team:50734 ...
## Connected to session server http://service-a8e1bed6-2796-4e8f-a34d-9e676de35b8b.posit-team:50734
## Running on host: packrat-restore-5sghb-7fdml
## 2025/01/17 16:56:00.233934010 Process ID: 39
## Linux distribution: Ubuntu 22.04.5 LTS (jammy)
## Running as user: uid=999 gid=999 groups=999
## 2025/01/17 16:56:00.241511561 Connect version: 2024.11.0
## 2025/01/17 16:56:00.241534152 LANG: en_US.UTF-8
## 2025/01/17 16:56:00.241551436 Working directory: /opt/rstudio-connect/mnt/app
## Using R 4.4.1
## 2025/01/17 16:56:00.241762110 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)'
## 2025/01/17 16:56:00.242405703 Configuring packrat to use available credentials for private repository access.
## 2025/01/17 16:56:00.242473645 # 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_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/01/17 16:56:00.272320275 # 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/latest"
## - CRAN = "https://pkg.current.posit.team/cran/latest"
## Rewrote Posit Package Manager URLs to install binary packages:
## - Rewrote "RSPM" from "https://pkg.current.posit.team/cran/latest" to "https://pkg.current.posit.team/cran/__linux__/jammy/latest".
## - Rewrote "CRAN" 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.
## 2025/01/17 16:56:01.352528487 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)
## 2025/01/17 16:56:01.555066488 Installing MASS (7.3-61) ...
## OK (symlinked cache)
## Installing R6 (2.5.1) ...
## OK (symlinked cache)
## 2025/01/17 16:56:01.578618554 Installing RColorBrewer (1.1-3) ...
## OK (symlinked cache)
## Installing Rcpp (1.0.13) ...
## OK (symlinked cache)
## 2025/01/17 16:56:01.599421724 Installing SQUAREM (2021.1) ...
## OK (symlinked cache)
## 2025/01/17 16:56:01.610327638 Installing bit (4.5.0) ...
## OK (symlinked cache)
## Installing cli (3.6.3) ...
## OK (symlinked cache)
## Installing clipr (0.8.0) ...
## OK (symlinked cache)
## 2025/01/17 16:56:01.641394926 Installing codetools (0.2-20) ...
## OK (symlinked cache)
## 2025/01/17 16:56:01.652155020 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)
## 2025/01/17 16:56:01.692474143 Installing data.table (1.16.0) ...
## OK (symlinked cache)
## Installing digest (0.6.36) ...
## OK (symlinked cache)
## 2025/01/17 16:56:01.712601976 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)
## 2025/01/17 16:56:01.761109902 Installing glue (1.7.0) ...
## OK (symlinked cache)
## Installing gower (1.0.1) ...
## OK (symlinked cache)
## 2025/01/17 16:56:01.781792936 Installing isoband (0.2.7) ...
## OK (symlinked cache)
## 2025/01/17 16:56:01.792546976 Installing jsonlite (1.8.9) ...
## OK (symlinked cache)
## 2025/01/17 16:56:01.802498862 Installing labeling (0.4.3) ...
## OK (symlinked cache)
## 2025/01/17 16:56:01.812384404 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)
## 2025/01/17 16:56:01.852388197 Installing nnet (7.3-19) ...
## OK (symlinked cache)
## Installing numDeriv (2016.8-1.1) ...
## OK (symlinked cache)
## 2025/01/17 16:56:01.873738550 Installing parallelly (1.38.0) ...
## OK (symlinked cache)
## 2025/01/17 16:56:01.886526212 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/01/17 16:56:01.930800097 Installing rlang (1.1.4) ...
## OK (symlinked cache)
## 2025/01/17 16:56:01.940729050 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)
## 2025/01/17 16:56:01.994053406 Installing sys (3.4.2) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.004674412 Installing timeDate (4041.110) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.015480862 Installing utf8 (1.2.4) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.025658659 Installing viridisLite (0.4.2) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.036358476 Installing whisker (0.4.1) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.046945949 Installing withr (3.0.1) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.056400465 Installing yaml (2.3.10) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.066178336 Installing class (7.3-22) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.076669620 Installing RcppEigen (0.3.4.0.2) ...
## OK (symlinked cache)
## Installing bit64 (4.5.2) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.097376746 Installing globals (0.16.3) ...
## OK (symlinked cache)
## Installing munsell (0.5.1) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.118392000 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)
## 2025/01/17 16:56:02.170544426 Installing nlme (3.1-166) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.180917633 Installing ellipsis (0.3.2) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.190446183 Installing later (1.3.2) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.200775348 Installing lifecycle (1.0.4) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.211059659 Installing lobstr (1.1.2) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.221707468 Installing diagram (1.6.5) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.232092513 Installing askpass (1.2.0) ...
## OK (symlinked cache)
## Installing future (1.34.0) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.253258273 Installing lubridate (1.9.3) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.263129550 Installing ranger (0.16.0) ...
## OK (symlinked cache)
## Installing survival (3.7-0) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.284873821 Installing mgcv (1.9-1) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.295599363 Installing promises (1.3.0) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.305575657 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)
## 2025/01/17 16:56:02.421367019 Installing tidyselect (1.2.1) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.432013530 Installing httr (1.4.7) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.441676822 Installing lava (1.8.0) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.452694012 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)
## 2025/01/17 16:56:02.505052416 Installing butcher (0.3.4) ...
## OK (symlinked cache)
## Installing cereal (0.1.0) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.526680221 Installing dplyr (1.1.4) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.536932683 Installing ggplot2 (3.5.1) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.546832832 Installing hardhat (1.4.0) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.557481180 Installing modelenv (0.1.1) ...
## OK (symlinked cache)
## Installing pins (1.3.0) ...
## OK (symlinked cache)
## Installing vroom (1.6.5) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.589344069 Installing ipred (0.9-15) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.600293761 Installing tidyr (1.3.1) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.610071685 Installing readr (2.1.5) ...
## OK (symlinked cache)
## Installing parsnip (1.2.1) ...
## OK (symlinked cache)
## 2025/01/17 16:56:02.630533665 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-a8e1bed6-2796-4e8f-a34d-9e676de35b8b.posit-team:50734
## Launching Plumber API...
::dbDisconnect(con) DBI