【问题标题】:AttributeError: Can't get attribute 'NaiveBayesSentiment' on <module '__main__' from 'app.py'>AttributeError:无法从 'app.py'> 获取 <module '__main__' 上的属性 'NaiveBayesSentiment'
【发布时间】:2020-12-25 00:19:11
【问题描述】:

我已经运行我的代码来加载我由 pickle 保存的变量。这是我的代码

import pickle

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

这是一个对象

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)

我得到这样的错误:

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

这是我在 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())

我该怎么办,请帮帮我

【问题讨论】:

    标签: python pickle


    【解决方案1】:

    Python 的pickle 序列化数据,但不序列化类或函数。他们只保存了他们的名字,所以反序列化时不存在同名的类或函数,出现上述错误。因此,同样要加载腌制对象,必须存在相同的定义。

    添加:

    这意味着在调用pickle.load 时必须定义NaiveBayesSentiment。换句话说,导入一个具有NaiveBayesSentiment 的模块。

    【讨论】:

    • 那我该怎么办你能帮我吗?
    • 朴素贝叶斯类没有导入模块,这只是我的假设,以便泡菜可以运行但结果是错误,我该怎么办你能帮我提供一些代码也许
    • nb_model = pickle.load(open('model_pickle.pkl', 'rb'))class NaiveBayesSentiment(): 是分开的吗?如果没有,它就不能正常工作。
    • 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()) 这就是我使用 naivebayerssentimen 我在 pickle 中声明的方式
    猜你喜欢
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 2022-06-20
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多