5
$\begingroup$

I need to save the results of a fit of the SKlearn NearestNeighbors model:

knn = NearestNeighbors(10)
knn.fit(my_data)

How do you save to disk the traied knn using Python?

$\endgroup$

4 Answers 4

10
$\begingroup$
import pickle 

knn = NearestNeighbors(10)
knn.fit(my_data)

# Its important to use binary mode 
knnPickle = open('knnpickle_file', 'wb') 
      
# source, destination 
pickle.dump(knn, knnPickle)  

# close the file
knnPickle.close()
                
      
# load the model from disk
loaded_model = pickle.load(open('knnpickle_file', 'rb'))
result = loaded_model.predict(X_test) 

refer: https://www.geeksforgeeks.org/saving-a-machine-learning-model/

$\endgroup$
2
  • $\begingroup$ do not forget to close the pickle file knnPickle.close() $\endgroup$
    – M farooqui
    Apr 5, 2022 at 3:28
  • $\begingroup$ Thanks for reminding. Edited the code $\endgroup$ Jul 29, 2022 at 7:36
3
$\begingroup$

Importing the library

from sklearn.externals import joblib

Saving your model after fitting the parameters

clf.fit(X_train,Y_train)
joblib.dump(clf, 'scoreregression.pkl')

Loading my model into the memory ( Web Service )

modelscorev2 = joblib.load('scoreregression.pkl' , mmap_mode ='r')

Using the loaded object

prediction = modelscorev2.predict_proba(y)
$\endgroup$
1
$\begingroup$

Pickle is the standard way of serializing objects in Python.

You can use the pickle operation to serialize your machine learning algorithms and save the serialized format to a file.

Later you can load this file to deserialize your model and use it to make new predictions.

Try this it works!

Thank you!

$\endgroup$
1
$\begingroup$

According to https://machinelearningmastery.com/save-load-machine-learning-models-python-scikit-learn/

model = knn() # put yours model
model.fit(X_train, Y_train)

# save the model to disk
filename = 'finalized_model.sav'
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(result)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.