Recipe: How to save trained model in Python?
MACHINE LEARNING RECIPES

How to save trained model in Python?

This recipe helps you save trained model in Python
In [1]:
## How to save trained model in Python
## DataSet: skleran.datasets.load_breast_cancer()
def Snippet_185():
    print()
    print(format('How to save trained model in Python','*^82'))
    import warnings
    warnings.filterwarnings("ignore")
    # load libraries
    from sklearn import model_selection, datasets
    from sklearn.tree import DecisionTreeClassifier
    from sklearn.externals import joblib
    import pickle
    # load dataset
    dataset = datasets.load_breast_cancer()
    X = dataset.data; y = dataset.target
    X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.25)
    # Fit the model on 33%
    model = DecisionTreeClassifier()
    model.fit(X_train, y_train)

    # save the model to disk using Pickle
    filename = 'trained_model.pickle'
    pickle.dump(model, open(filename, 'wb'))
    # load the model from disk
    loaded_model = pickle.load(open(filename, 'rb'))
    result = loaded_model.score(X_test, y_test)
    print(); print(result)

    # save the model to disk using Joblib
    filename = 'trained_model.joblib'
    joblib.dump(model, filename)

    # load the model from disk
    loaded_model = joblib.load(filename)
    result = loaded_model.score(X_test, y_test)
    print(); print(result)
Snippet_185()
***********************How to save trained model in Python************************

0.916083916083916

0.916083916083916


Stuck at work?
Can't find the recipe you are looking for. Let us know and we will find an expert to create the recipe for you. Click here
Companies using this Recipe