【问题标题】:Bringing a classifier to production将分类器投入生产
【发布时间】:2014-11-05 10:39:38
【问题描述】:

我已经使用 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: Vocabulary was not compatible or is empty! 我想我应该从 te joblid 加载词汇,但我无法让它工作

【问题讨论】:

  • 在存储/加载矢量化器时遇到什么错误?
  • 我在加载时没有收到错误,现在问题已解决。谢谢你的帮助

标签: python scikit-learn joblib


【解决方案1】:

只需替换:

  #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 包含完整的管道,无需创建新的矢量化器实例。正如错误消息所说,您需要重用最初训练的矢量化器,因为从标记(字符串 ngram)到列索引的特征映射保存在矢量化器本身中。这种映射被命名为“词汇表”。

【讨论】:

  • 谢谢@ogrisel 工作得很好......此外刚刚发现这个关于优化我的分类器的有用博客link
猜你喜欢
  • 1970-01-01
  • 2013-04-24
  • 1970-01-01
  • 2018-03-25
  • 2020-11-02
  • 2015-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多