Recent Posts

Saving a ML Model using pickle

 


Import Packages and Build the ML model:-

from sklearn.linear_model import LogisticRegression from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split # Load the data Iris_data = load_iris() # Split data Xtrain, Xtest, Ytrain, Ytest = train_test_split(Iris_data.data, Iris_data.target, test_size=0.3, random_state=4) # Define the Model LR_Model = LogisticRegression(C=0.1, max_iter=20, fit_intercept=True, n_jobs=3, solver='liblinear') # Train the Model LR_Model.fit(Xtrain, Ytrain)

After you train the model and fit the model

Import Pickle Package

* Install pickle if you're running this on your local system
         $ pip install pickle

import pickle


Save the model

pickle.dump(LR_Model, open('model.pkl''wb'))

Load the model

pickled_model = pickle.load(open('model.pkl''rb'))
pickled_model.predict(Xtrain)

array([0, 0, 1, 1, 2, 0, 1, 2, 2, 1, 1, 0, 1, 2, 2, 0, 1, 0, 1, 2, 2, 2, 2, 0, 2, 2, 0, 1, 2, 0, 2, 1, 2, 2, 0, 2, 1, 2, 0, 2, 1, 2, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 0, 2, 0, 1, 0, 2, 1, 1, 1, 0, 2, 2, 1, 1, 1, 0, 0, 2, 2, 0, 0, 0, 2, 0, 0, 2, 2, 2, 0, 0, 0, 2, 2, 0, 0, 2, 1, 2, 0, 0, 2, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 2])


No comments

If you have any doubts, Please let me know