Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly load pretrained model in CatBoost in Python

I have trained CatBoostClassifier to solve my classification task. Now I need to save the model and use it in another app for prediction. In order to do so I have saved model via save_model method and restored it via load_model method.

However, every time I call predict in the restored model I get an error:

CatboostError: There is no trained model to use predict(). Use fit() to train model. Then use predict().

So it looks like I need to train my model again whereas I need to restore pretrained model and use it for predictions only.

What am I doing wrong here? Is there a special way I should use to load model for prediction?

My training process looks like this:

model = CatBoostClassifier(
    custom_loss=['Accuracy'],
    random_seed=42,
    logging_level='Silent',
    loss_function='MultiClass')

model.fit(
    x_train, 
    y_train,
    cat_features=None,
    eval_set=(x_validation, y_validation),
    plot=True)

...

model.save("model.cbm")

And I restore model using this code:

model = CatBoostClassifier(
    custom_loss=['Accuracy'],
    random_seed=42,
    logging_level='Silent',
    loss_function='MultiClass')
model.load_model("model.cbm")

...


predict = self.model.predict(inputs)
like image 649
NShiny Avatar asked Aug 17 '18 12:08

NShiny


1 Answers

# After you train the model using fit(), save like this - 
model.save_model('model_name')    # extension not required.

# And then, later load - 
from catboost import CatBoostClassifier
model = CatBoostClassifier()      # parameters not required.
model.load_model('model_name')

# Now, try predict().
like image 158
Vishal Gupta Avatar answered Oct 08 '22 14:10

Vishal Gupta