Search code examples
pythonmachine-learningscikit-learnpickle

Saving the preprocessing steps in the end model


I'm trying to save my text classification model as a pickle file. I have a specific set of preprocessing steps that I wanted to save in my end model to apply it on unseen data for prediction. Currently I tried using a sklearn pipeline which includes preprocessing, applying count vectorizer and applying the algorithm. My question is if this is a right way to save the preprocessing steps in the end model or should I save it as a seperate file. Below is my code

from sklearn import model_selection
X_train, X_test, y_train, y_test = model_selection.train_test_split(df_train.data, df_train.label, test_size=0.2)
vect = CountVectorizer(stop_words='english', max_features=10000, , ngram_range=(1,2))
X_train_dtm = vect.fit_transform(X_train)
X_test_dtm = vect.transform(X_test)

from sklearn import metrics
from sklearn.ensemble import RandomForestClassifier
rf_classifier = RandomForestClassifier(n_estimators=100)
rf_classifier.fit(X_train_dtm, y_train)
rf_predictions = rf_classifier.predict(X_test_dtm)
print("RF Accuracy:")
metrics.accuracy_score(y_test, rf_predictions)


import pickle
from sklearn.pipeline import Pipeline
pipe = Pipeline([("prep", prep),("CV", vect), ("RF", rf_classifier)])
with open('PII_model.pickle', 'wb') as picklefile:
    pickle.dump(pipe, picklefile)

I have a method for preprocessing which I invoke it and I've included this in my sklearn pipeline

prep = prep(df_train)

Solution

  • Generally, it is the right approach. But you can improve it put everything in the pipeline from the very beginning:

    vect = CountVectorizer(stop_words='english', 
                           max_features=10000, 
                           ngram_range=(1,2))
    rf_classifier = RandomForestClassifier(n_estimators=100)
    pipe = Pipeline([("prep", prep),("CV", vect), ("RF", rf_classifier)])    
    pipe.fit(X_train_dtm, y_train)
    
    rf_predictions = pipe.predict(X_test_dtm)
    print("RF Accuracy:")
    metrics.accuracy_score(y_test, rf_predictions)
    
    with open('PII_model.pickle', 'wb') as picklefile:
        pickle.dump(pipe, picklefile)
    

    One more benefit to putting everything in the one pipeline - you can easily use GridSearch to tune parameters of the model.

    Here is you can also find official documentation on how to organize a pipeline with mixed types.