# How to save a knn model?

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?

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)

# load the model from disk


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')


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


prediction = modelscorev2.predict_proba(y)


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!

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