使用保存的分类器/模型时出现“idf 向量未拟合”错误

N.P*_*N.P 2 python-2.7 scikit-learn naivebayes

如果我使用了错误的术语,请原谅我,但我想要的是训练一组数据(使用来自 Scikit Learn 的 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'
Run Code Online (Sandbox Code Playgroud)

谁能告诉我我错过了什么?

注意:模型的保存、保存模型的读取和尝试预测一个新的类别都是一个类的不同方法。我已将它们全部折叠到一个屏幕中,以便于阅读。

谢谢

Viv*_*mar 6

您需要腌制self.vectorizer并再次加载。目前您只保存向量化器学习的词汇。

更改程序中的以下行:

joblib.dump(self.vectorizer.vocabulary_, 'trained/vectorizer_vocab.pkl')
Run Code Online (Sandbox Code Playgroud)

到:

joblib.dump(self.vectorizer, 'trained/vectorizer.pkl')
Run Code Online (Sandbox Code Playgroud)

以及以下行:

self.vocab =joblib.load('trained/vectorizer_vocab.pkl')
Run Code Online (Sandbox Code Playgroud)

到:

self.vectorizer =joblib.load('trained/vectorizer.pkl')
Run Code Online (Sandbox Code Playgroud)

删除这一行:

self.vectorizer = TfidfVectorizer(vocabulary=self.vocab, decode_error='ignore')
Run Code Online (Sandbox Code Playgroud)

问题说明

你的想法是正确的,只是保存所学的词汇并重新使用它。但是 scikit-learn TfidfVectorizer 也有idf_包含保存词汇的 IDF的属性。所以你也需要保存它。但是,即使您保存两者并将它们都加载到新的 TfidfVectorizer 实例中,您也会收到“not_fitted”错误。因为这就是大多数 scikit 转换器和估计器的定义方式。所以不做任何“hacky”保存整个矢量化器是你最好的选择。如果您仍想继续保存词汇路径,请在此处查看如何正确执行此操作:

上面的页面保存vocabulary到 json 和idf_一个简单的数组中。您可以在那里使用泡菜,但您将了解 TfidfVectorizer 的工作原理。

希望能帮助到你。