我已经使用joblib:保存了我的分类器管道
vec = TfidfVectorizer(sublinear_tf=True, max_df=0.5, ngram_range=(1, 3))
pac_clf = PassiveAggressiveClassifier(C=1)
vec_clf = Pipeline([('vectorizer', vec), ('pac', pac_clf)])
vec_clf.fit(X_train,y_train)
joblib.dump(vec_clf, 'class.pkl', compress=9)
现在我正试图在生产环境中使用它:
def classify(title):
#load classifier and predict
classifier = joblib.load('class.pkl')
#vectorize/transform the new title then predict
vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, ngram_range=(1, 3))
X_test = vectorizer.transform(title)
predict = classifier.predict(X_test)
return predict
我得到的错误是:ValueError:词汇不合适或为空!我想我应该从te joblid加载词汇,但我无法使其工作
只需替换:
#load classifier and predict
classifier = joblib.load('class.pkl')
#vectorize/transform the new title then predict
vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, ngram_range=(1, 3))
X_test = vectorizer.transform(title)
predict = classifier.predict(X_test)
return predict
发件人:
# load the saved pipeline that includes both the vectorizer
# and the classifier and predict
classifier = joblib.load('class.pkl')
predict = classifier.predict(X_test)
return predict
class.pkl
包含完整的管道,不需要创建新的矢量器实例。正如错误消息所说,您需要重用最初训练的矢量器,因为从标记(字符串ngrams)到列索引的特征映射保存在矢量器本身中。这种映射被命名为"词汇表"。