简体   繁体   中英

How to pickle sklearn Pipeline object?

I'm trying to save a pipeline. I can't. Here's my class object, which I've tried pickling.

class SentimentModel():

    def __init__(self,model_instance,x_train,x_test,y_train,y_test):
        import string
        from nltk import ngrams
        self.ngrams = ngrams
        self.string = string
        self.model = model_instance
        self.x_train = x_train
        self.x_test = x_test
        self.y_train = y_train
        self.y_test = y_test       
        self._fit()


    def _fit(self):
        from sklearn.pipeline import Pipeline
        from sklearn.feature_extraction.text import TfidfTransformer
        from sklearn.feature_extraction.text import CountVectorizer      

        self.pipeline = Pipeline([
            ('bow', CountVectorizer(analyzer=self._text_process)), 
            ('tfidf', TfidfTransformer()), 
            ('classifier', self.model), 
        ])
        self.pipeline.fit(self.x_train,self.y_train)
        self.preds = self.pipeline.predict(self.x_test)     

    def _text_process(self,text):
        def remove_non_ascii(text):
            return ''.join(i for i in text if ord(i)<128)        

        text = remove_non_ascii(text)
        text = [char.lower() for char in text if char not in self.string.punctuation]
        text = ''.join(text)
        unigrams = [word for word in text.split()]
        bigrams = [' '.join(g) for g in self.ngrams(unigrams,2)]
        trigrams = [' '.join(g) for g in self.ngrams(unigrams,3)]
        tokens = []
        tokens.extend(unigrams+bigrams+trigrams)
        return tokens        

    def predict(self,observation):
        return self.pipeline.predict(observation)

And I get these errors:

from sklearn.naive_bayes import MultinomialNB
nb = MultinomialNB()
nb_model = SentimentModel(nb,X_train,X_test,y_train,y_test)

import pickle
with open('nb_model1.pkl','wb') as f:
    pickle.dump(nb_model,f)

>>>
TypeError: can't pickle module objects

Likewise:

with open('nb_model1.pkl','wb') as f:
    pickle.dump(nb_model.pipeline,f)

TypeError: can't pickle module objects

I can however, save nb_model.model . But not the pipeline object. What's the explanation? How do I make my whole pipeline persist?

I've seen How to pickle individual steps in sklearn's Pipeline? , but the problem is, it can't pickle the bow attribute.

joblib.dump(nb_model.pipeline.get_params()['tfidf'], 'nb_tfidf.pkl') # pass
joblib.dump(nb_model.pipeline.get_params()['bow'], 'nb_bow.pkl') # fail
joblib.dump(nb_model.pipeline.get_params()['classifier'], 'nb_classifier.pkl') #pass

>>>
TypeError: can't pickle module objects

What should I do?

Try it again without importing modules inside your class definition. It's not a good practice because when you import something such as import string , you bring a whole set of third-party code to your code that may even not be installed on another other machine that wants to use this pickle; it's not a good practice. Maybe pickle is protecting you to do this kind of thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM