[JustForFunPython] Saving trained parameters using Joblib library

A Ydobon
2 min readJan 25, 2020

--

So, let’s say we want to build a web application to classify ianput data into some labels. Do we have to train each time when input is fed to the app? Definitely, not, as we can use ‘Joblib’ library in Python!

This is currently supported under Scikit Learn, but I recommend using it directly importing Joblib into your workspace since the support will be stopped soon and it would be deprecated inside Scikit Learn later.

So, let’s load our dependent libraries!

from sklearn import svm 
import joblib
import json

Remember the previous posting that we made a JSON file to prepare the dataset to feed the classifier? You can check quickly!

with open("freq.json", "r", encoding = 'utf-8) as f:
d = json.load(f)
data = d[0]

1–1. This time, as we are not writing a new file but to read an existing one, the variable will be ‘r’.

1–2. And, in the JSON file, we have two sets: train, and test. We will only load the first training set, that is why I added “[0]” to the loaded one.

Now, time to train the model and earn the parameters!

clf = svm.SVC(gamma = 'auto') 
clf.fit(data['freq'], data['labels'])

2–1. Simply making an classifier object by calling svm.SVC()

2–2. Train data using ‘fit()’ funciton!

Now, the main part of this time, saving the learned parameters in another pickle file!

joblib.dump(clf, "freq.pkl")

3–1. You can always change the file name and path, instead of “freq.pkl”.

3–2. dump() is to create a file. When we write a YAML or a JASON file, we also use this ‘dump()’ method.

Done!

Check out your working directory, and you will see the newly made pickle file containing the value!

Easy-Peasy!

Happy learning and see you around! 🏃 🚀 🍰

--

--

A Ydobon
A Ydobon

No responses yet