EuRBamarth
EuRBamarth

Reputation: 974

Save LGBM model in `.cpp` format from Python

If I run

from sklearn.datasets import load_breast_cancer
import lightgbm as lgb

breast_cancer = load_breast_cancer()
data = breast_cancer.data
target = breast_cancer.target

params = {
    "task": "convert_model",
    "convert_model_language": "cpp",
    "convert_model": "test.cpp",
}

gbm = lgb.train(params, lgb.Dataset(data, target))

then I was expecting that a file called test.cpp would be created, with the model saved in c++ format.

However, nothing appears in my current directory.

I have read the documentation (https://lightgbm.readthedocs.io/en/latest/Parameters.html#io-parameters), but can't tell what I'm doing wrong.

Upvotes: 0

Views: 2431

Answers (2)

EuRBamarth
EuRBamarth

Reputation: 974

Here's a real 'for dummies' answer:

  1. Install the CLI version of lightgbm: https://lightgbm.readthedocs.io/en/latest/Installation-Guide.html

  2. Make note of your installation path, and find the executable. For example, for me, this was ~/LightGBM/lightgbm.

  3. Run the following in a Jupyter notebook:

from sklearn.datasets import load_breast_cancer
import pandas as pd

breast_cancer = load_breast_cancer()
data = pd.DataFrame(breast_cancer.data)
target = pd.DataFrame(breast_cancer.target)

pd.concat([target, data], axis=1).to_csv("regression.train", header=False, index=False)

train_conf = """
task = train
objective = binary
metric = auc
data = regression.train
output_model = trained_model.txt
"""

with open("train.conf", "w") as f:
    f.write(train_conf)

conf_convert = """
task = convert_model
input_model= trained_model.txt
"""

with open("convert.conf", "w") as f:
    f.write(conf_convert)
! ~/LightGBM/lightgbm config=train.conf
! ~/LightGBM/lightgbm config=convert.conf

Your model with be saved in your current directory.

Upvotes: 5

Florian Mutel
Florian Mutel

Reputation: 1084

In the doc they say:

Note: can be used only in CLI version

under the convert_model and convert_model_language parameters.

That means that you should probably use the CLI (Command Line Interfarce) of LGBM instead of the python wrapper to do this.

Link to Quick Start CLI version.

Upvotes: 2

Related Questions