Save classifier to disk in scikit-learn #shorts
If you have trained a classifier using scikit-learn and you want to save it to disk for future use, you can easily do so using the joblib library. Here’s how:
- First, make sure you have joblib installed. You can do this by running the following command:
- Next, import the necessary libraries in your Python script:
- Train your classifier using scikit-learn, for example:
- Save the classifier to disk using joblib:
pip install joblib
import joblib
from sklearn import svm
clf = svm.SVC()
X = [[0, 0], [1, 1]]
y = [0, 1]
clf.fit(X, y)
joblib.dump(clf, 'classifier_model.pkl')
Now your classifier has been saved to a file called ‘classifier_model.pkl’ in the current directory. You can load it back into memory at any time by using the following code:
clf = joblib.load('classifier_model.pkl')
That’s it! You now know how to save a classifier to disk in scikit-learn using joblib. This can be useful for saving time and resources when working with large datasets or complex models. Happy coding!