Search code examples
python-3.xgoogle-colaboratoryoptuna

Saving optuna study.pkl in Google Colab


I'm tuning my ML model on Google Colab but I don't know how to save that model to pkl.

import time
import optuna

study_name = "/gdrive/MyDrive/Colab Notebooks/test/params_{}".format(time.strftime("%Y%m%d-%H%M%S"))
study=optuna.create_study(study_name, direction='maximize')

The codes show me this error:

Could not parse rfc1738 URL from string '/gdrive/MyDrive/Colab Notebooks/test/params_20220217-181559'

What should I do to save this model?


Solution

  • You mean save the study ?

    https://optuna.readthedocs.io/en/stable/faq.html#how-can-i-save-and-resume-studies

    I use this :

    install joblib
    import joblib
    
    # Let's say I want to save study to savepath + "xgb_optuna_study_batch.pkl"
    
    joblib.dump(study, f"{savepath}xgb_optuna_study_batch.pkl")   # save study
    
    # to load it:
    jl = joblib.load(f"{savepath}xgb_optuna_study_batch.pkl")
    
    print(jl.best_trial.params)
    
    # output, for example:
    {'lambda': 1.4556073038174557, 'alpha': 0.007250895998233471, 'colsample_bytree': 0.7, 'subsample': 0.8, 'learning_rate': 0.01, 'max_depth': 20, 'random_state': 48, 'min_child_weight': 1}