Working with the classifyr Package

posit::conf 2025

Supporting material for the talk “Building Governable ML Models with R.”

Author
Affiliation

Tom Shafer,
Principal Data Scientist

Use the example package, even without installing

We use export_all = FALSE to simulate how R behaves when calling library.

devtools::load_all("classifyr", export_all = FALSE)
ℹ Loading classifyr

Train the model

We have a simple function to “train” a two-stage model:

model <- train_classifyr(iris, target = "Species")
Training classifyr model
Bundling models into a single object

This object is a list with a custom class attribute tacked onto the front:

attr(model, which = "class")
[1] "classifyr_model" "list"           

Because we’ve defined a custom print method, though—print.classifyr_model()—we can control how the object is printed or displayed in settings where a string representation is needed:

model
Classifyr model
- Target: Species 
- Features: Sepal.Length, Sepal.Width, Petal.Length, Petal.Width 

Generate predictions

We have defined a predict method as well, so we can use the model just like any other in R:

preds <- predict(model, iris)
Making predictions for classifyr model
head(preds, n = 3)
[1] 0.6735518 0.2844811 0.3473449

Explain the model

Finally, maybe we’d like to add other functionality. Here we’ve (1) created and (2) defined a new explain method:

explns <- explain(model, preds, iris)
head(explns, n = 5)
Explaining model predictions
       pred letter number                                          message
1 0.6735518      D     28 Brought to you by the letter D and the number 28
2 0.2844811      F     76 Brought to you by the letter F and the number 76
3 0.3473449      L     51 Brought to you by the letter L and the number 51
4 0.4975344      I     51 Brought to you by the letter I and the number 51
5 0.2418792      S     88 Brought to you by the letter S and the number 88