请原谅,如果我使用了错误的术语,但我想要的是训练一组数据(使用Scikit学习中的GaussianNB朴素贝叶斯),保存模型/分类器,然后在需要时加载它并预测一个类别。
from sklearn.externals import joblib
from sklearn.naive_bayes import GaussianNB
from sklearn.feature_extraction.text import TfidfVectorizer
self.vectorizer = TfidfVectorizer(decode_error='ignore')
self.X_train_tfidf = self.vectorizer.fit_transform(train_data)
# Fit the model to my training data
self.clf = self.gnb.fit(self.X_train_tfidf.toarray(), category)
# Save the classifier to file
joblib.dump(self.clf, 'trained/NB_Model.pkl')
# Save the vocabulary to file
joblib.dump(self.vectorizer.vocabulary_, 'trained/vectorizer_vocab.pkl')
#Next time, I read the saved classifier
self.clf = joblib.load('trained/NB_Model.pkl')
# Read the saved vocabulary
self.vocab =joblib.load('trained/vectorizer_vocab.pkl')
# Initializer the vectorizer
self.vectorizer = TfidfVectorizer(vocabulary=self.vocab, decode_error='ignore')
# Try to predict a category for new data
X_new_tfidf = self.vectorizer.transform(new_data)
print self.clf.predict(X_new_tfidf.toarray())
# After running the predict command above, I get the error
'idf vector is not fitted'
有人能告诉我我错过了什么吗?
注:保存模型、读取保存的模型和尝试预测新的类别都是类的不同方法。为了便于阅读,我把它们都折叠在一个屏幕上。
谢谢
发布于 2017-07-01 00:27:58
您需要对self.vectorizer
进行腌制并再次加载它。目前,您只保存了向量器学习的词汇表。
更改程序中的下列行:
joblib.dump(self.vectorizer.vocabulary_, 'trained/vectorizer_vocab.pkl')
至:
joblib.dump(self.vectorizer, 'trained/vectorizer.pkl')
以下一行:
self.vocab =joblib.load('trained/vectorizer_vocab.pkl')
至:
self.vectorizer =joblib.load('trained/vectorizer.pkl')
删除这一行:
self.vectorizer = TfidfVectorizer(vocabulary=self.vocab, decode_error='ignore')
问题解释
你的想法是正确的,只需保存所学的词汇,并重新使用它。但是scikit-learn也具有idf_
属性,该属性包含保存的词汇表的IDF。所以你也需要保存它。但是,即使您将两者都保存并加载到一个新的TfidfVectorizer实例中,也会得到"not_fitted“错误。因为这正是大多数科幻变压器和估值器的定义方式。因此,不做任何“黑客”保存整个矢量器是你最好的选择。如果您还想继续保存词汇表路径,那么请在这里看看如何正确地这样做:
上面的页面将vocabulary
保存到json中,idf_
保存到一个简单的数组中。您可以在那里使用泡菜,但是您将了解TfidfVectorizer的工作原理。
希望能帮上忙。
https://stackoverflow.com/questions/44855780
复制相似问题