How to save/load a Model (Pickle) with a specific path/directory

I seems like a very basic think but I couldnt find an answer to it.

I want to save my model to a specific directory using pickle. The two algorithms below work fine for saving it in the same directory as the code itself but I want to save all my models in a dedicated folder. I tried to just change the "filename" to "filepath" and well, make it a path but the world isnt that easy it seems.

  • Example Path: C:\Learning\Python\Data Science\02_TrainedModels

.

# save the model to disk 
filename = 'Father_Son_Height_Model.pckl' 
pickle.dump(lm, open(filename, 'wb'))

filename = 'Father_Son_Height_Model.pckl' 
loaded_model =    pickle.load(open(filename, 'rb'))

With This Code:

# save the model to disk
filepath = r'H:\99_Lernen\Python\Data Science\02_Trained Models\Father_Son_Height_Model.pckl'
pickle.dump(lm, open(filepath, 'wb'))

I get this Error: FileNotFoundError: [Errno 2] No such file or directory: 'H:\99_Lernen\Python\Data Science\02_Trained Models\Father_Son_Height_Model.pckl'

In this line of code:

pickle.dump(lm, open(filepath, 'wb'))

Topic pickle machine-learning

Category Data Science


The "\" escapes the following sign when parsed, so the path cannot be read.

Use "/" instead and it should work. Also this question was probably more of a SO question ;)

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.