Peter Stephensen
Peter Stephensen

Reputation: 957

Save LightGbm model in R and load it in C#

I would like to:

  1. train my model in R
  2. Save the model in a file
  3. Load the model in C# and use it to predict

The problem is that the file format in R (json) is not the same as in C# (zip)

Upvotes: 0

Views: 456

Answers (1)

James Lamb
James Lamb

Reputation: 2732

The problem is that the file format in R (json)

{lightgbm}, the official R package for LightGBM, supports other options besides JSON.

Use the following code in {lightgbm} >= 3.3.3 to train a model and save it to the official LightGBM text model representation.

library(lightgbm)

data(EuStockMarkets)
stockDF <- as.data.frame(EuStockMarkets)

# create a Dataset
feature_names <- c("SMI", "CAC", "FTSE")
target_name <- "DAX"
X_train <- data.matrix(stockDF[, feature_names])
y_train <- stockDF[[target_name]]
dtrain <- lightgbm::lgb.Dataset(
    data = X_train
    , label = y_train
    , colnames = feature_names
)

# train
model <- lightgbm::lgb.train(
    obj = "regression"
    , data = dtrain
    , verbose= 1
    , nrounds = 10
)

# save to a text file
lightgbm::lgb.save(
    booster = model
    , filename = "regression-model.txt"
)

That text file can be read by public entrypoint LGBM_BoosterCreateFromModelfile() in LightGBM's C API (code link), and therefore by any C# bindings that call that entrypoint.

For example, see Booster.CreateFromModelfile() in LightGBMSharp, a C# interface to LightGBM (code link).

Upvotes: 1

Related Questions