Search code examples
pythonmachine-learningmodeldata-sciencepickle

How to save and reuse model in python


I have build a model and saved it using pickle library but I wanna use it again by changing the values of my input variables and for that I don't have any output.

Here is the code :

# Save Model Using Pickle
import pandas
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
import pickle
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians- 
diabetes.data.csv"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = pandas.read_csv(url, names=names)
array = dataframe.values 
X = array[:,0:8]
Y = array[:,8]
test_size = 0.33
seed = 7
X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size, 
random_state=seed)
# Fit the model on training set
model = LogisticRegression()
model.fit(X_train, Y_train)
# save the model to disk
filename = 'finalized_model.sav'
pickle.dump(model, open(filename, 'wb'))

# some time later...

# load the model from disk
loaded_model = pickle.load(open(filename, 'rb'))
result = loaded_model.score(X_test, Y_test)
print(result)

Now, I have only data for my X_test. I don't have any data point for my Y_test. In such case how I can use it again and pass only X_test and it gives me Y. Please help!!


Solution

  • This shall work:

    loaded_model.predict(X_test)