如何保存并稍后加载NLTK分类器?

时间:2019-03-28 14:36:23

标签: python nltk pickle

我正在尝试对电影评论进行情感分析。

以下代码位于函数内部:

classifier = nltk.classify.SklearnClassifier(LinearSVC())

classifier.train(train_set)

稍后使用时,如何保存并加载它?我应该在代码中的位置放置pickle函数吗? 谢谢您的时间!

3 个答案:

答案 0 :(得分:0)

运行pickle后,在保存和阅读文档时可以使用nltk。 首先,您需要导入模块。

import pickle

classifier = nltk.classify.SklearnClassifier(LinearSVC())
classifier = classifier.train(train_set)

要保存:

with open("filename", "wb") as infile:
    pickle.dump(classifier, infile)

阅读:

with open("filename","rb") as outfile:
    docs = pickle.load(outfile)

答案 1 :(得分:0)

您可以使用pickle

写作:

import pickle as pkl
clf = nltk.classify.SklearnClassifier(LinearSVC())
clf.train(X_train,y_train)
with open('clf.pkl','wb') as myfile:
    pkl.dump(clf,myfile)

阅读:

import pickle as pkl
with open('clf.pkl','wb') as myfile:
    clf = pkl.load(myfile)

答案 2 :(得分:0)

保存:

def save(name,data,type='.dat'):
    name+=type
    pickle.dump(data,open(name,'wb'))#will create file if doesn't exist,will update file if there is such file

加载:

def load(name):
    return pickle.load(open(name,'rb'))#will raise error if no such file exists

示例:

save('myFile','foo')
print(load('myfile.dat'))#remember .dat !
#will prints 'foo'

您需要先导入泡菜,然后才能保存任何内容