AttributeError: Can't get attribute 'NaiveBayesSentiment' on <module '__main__' from 'app.py'>

Viewed 89

I already run my code to load my variable saved by pickle. This my code

import pickle

app = Flask(__name__)
nb_model = pickle.load(open('model_pickle.pkl', 'rb'))

this is a object

class NaiveBayesSentiment():

def __init__(self, datasentimen, stopword, norm, datatest):
    self.datasentimen = datasentimen
    self.stop_word = stopword.T.values
    self.norm_words =  pd.Series(norm['kata kbbi'].values,index=norm['kata singkatan']).to_dict()
    self.datatest = pd.DataFrame([datatest], columns=['comment'])
def cleansing_data(self, datasentimen):
            datasentimen = datasentimen.replace('\n', ' ',regex = True)
            datasentimen = datasentimen.str.replace("[^a-zA-Z]+", " ", regex = True)
            datasentimen = datasentimen.str.replace('\s{2,}', ' ', regex=True)
            datasentimen = datasentimen.str.lower()
            return datasentimen
            cleanposdata = cleansing_data(datasentimen[datasentimen['class sentiment'] == 'positif']['comment'])
            cleannegdata = cleansing_data(datasentimen[datasentimen['class sentiment'] == 'negatif']['comment'])  

if __name__ == "__main__":
  app.run(debug=True)

and i get error like this :

nb_model = pickle.load(open('model_pickle.pkl', 'rb'))
AttributeError: Can't get attribute 'NaiveBayesSentiment' on <module '__main__' from 'app.py'>

this is code when I do pickle in python

nb_model = NaiveBayesSentiment(datasentimen, stopword, norm, datatest)

with open('model_pickle.pkl', 'wb') as pickle_out:
pickle.dump(nb_model, pickle_out)

with open('model_pickle.pkl', 'rb') as pickle_in:
unpickled_nb_model = pickle.load(pickle_in)

print(unpickled_nb_model.finalclassification())

what should i do please helpme

1 Answers

Python's pickle serializes data but not classes nor functions. They saved their names only, so classes or functions have same name don't exists when deserialize, occurs error as above. Therefore, also to load pickled objects, same definitions must exist.

Add:

This means that NaiveBayesSentiment must be defined when call pickle.load. In other words, import a module which has NaiveBayesSentiment.

Related