Introduction

Sagemaker is great for training, but sometimes you don’t want the overhead (cost and time) of predict.sagemaker or batch_predict.

Luckily, AWS Sagemaker saves every model in S3, and you can download and use it locally with the right configuration.

For xgboost models (more to come in the future), I’ve written sagemaker_load_model, which loads the trained Sagemaker model into your current R session.

Data

Let’s use the sagemaker::abalone dataset once again, but this time let’s try classification instead of regression.

First we’ll identify the classes with the highest frequency, so we can eliminate the low-variance ones.

We’ll use recipes to transform the dataset into the proper format for xgboost. We must ensure that:

  1. classes are integers
  2. classes are labeled 0 to number of classes - 1.
  3. outcome is the first column
rec <- recipe(rings ~ ., data = sagemaker::abalone) %>%
  step_filter(rings %in% top_rings$rings) %>%
  step_integer(all_outcomes(), zero_based = TRUE) %>%
  prep(training = sagemaker::abalone, retain = TRUE)

abalone_class <- juice(rec) %>%
  select(rings, everything())

abalone_class %>%
  group_by(rings) %>%
  summarise(n = n()) %>%
  arrange(n)
#> # A tibble: 10 x 2
#>    rings     n
#>    <dbl> <int>
#>  1     0   115
#>  2     9   126
#>  3     8   203
#>  4     1   259
#>  5     7   267
#>  6     2   391
#>  7     6   487
#>  8     3   568
#>  9     5   634
#> 10     4   689

Then we’ll split into test/validation and upload to S3 for training.

split <- initial_split(abalone_class)

train_path <- s3(s3_bucket(), "abalone-class-train.csv")
validation_path <- s3(s3_bucket(), "abalone-class-test.csv")
write_s3(analysis(split), train_path)
write_s3(assessment(split), validation_path)

Training

Frist, we need to set the xgboost hyperparameters for multiclassification. See here for the official list of xgboost parameters.

objective = "multi:softmax" will return the predicted class, while objective = "multi:softprob" returns a tibble with probabilities for each class1.

Next, we’ll set some ranges to tune over and start training.

tune <- sagemaker_hyperparameter_tuner(
  xgb_estimator, s3_split(train_path, validation_path), ranges, max_jobs = 5
)

Loading the model

Now we can download the Sagemaker model artifact from S3 and load it into the R session.

For xgboost Sagemaker models, sagemaker_load_model loads a Booster object from the xgboost Python package:

To use this feature, you must have the xgboost Python package installed. You can download and install it with

The Sagemaker R package loads the Booster object into the R session with reticulate. Therefore, all methods and attributes are available in R.

#>  [1] "_validate_features"        "attr"                     
#>  [3] "attributes"                "best_iteration"           
#>  [5] "best_ntree_limit"          "best_score"               
#>  [7] "boost"                     "booster"                  
#>  [9] "copy"                      "dump_model"               
#> [11] "eval"                      "eval_set"                 
#> [13] "feature_names"             "feature_types"            
#> [15] "get_dump"                  "get_fscore"               
#> [17] "get_score"                 "get_split_value_histogram"
#> [19] "handle"                    "load_model"               
#> [21] "load_rabit_checkpoint"     "predict"                  
#> [23] "save_model"                "save_rabit_checkpoint"    
#> [25] "save_raw"                  "set_attr"                 
#> [27] "set_param"                 "trees_to_dataframe"       
#> [29] "update"

Predictions

However, you need to know the xgboost Python package to work with the local model.

The sagemaker R package also includes predict.xgboost.core.Booster to help you easily make predictions on this object:

This method returns predictions in tibbles, and it attempts to conform to the tidymodel standard.

Unfortunately, at the moment type ("class" or "prob") cannot be supported.

If you want both probability and class predictions, I recommend you default to objective = "multi:softprob" or objective = "binary:logistic" for probabilities and convert to outcomes after the predictions are returned.

Analysis

Next, we can map the data and predictions back to the true values:

ring_map <- tidy(rec, 2) %>%
  unnest(value) %>%
  select(rings_integer = integer, rings_actual = value)

rings_actual <- abalone_class %>%
  left_join(ring_map, by = c("rings" = "rings_integer")) 
rings_pred <- pred %>%
  left_join(ring_map, by = c(".pred" = "rings_integer"))

And calculate the confusion matrix:

We can also see the model fit:

Multiclass probability

Let’s also train a model using objective = "multi:softprob" to compare the output.

tune2 <- sagemaker_hyperparameter_tuner(
  xgb_estimator2, s3_split(train_path, validation_path), ranges, max_jobs = 5
)

In this case, the outcome is a tibble with an associated probability for each class.

Then we can derive the predicted class by finding the class with the highest probability for each row (variable) of the tibble.


  1. You can also use eval_metric = "merror", although "mlogloss" is usually better in practice.