Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

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

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('
', ' ',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 pyhton

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...