将分类器投入生产

6 投票
1 回答
3563 浏览
提问于 2025-04-21 02:26

我用 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: 词汇表没有被训练或者是空的!我想我应该从 joblib 中加载词汇表,但我就是搞不定。

1 个回答

9

只需要把:

  #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 文件里包含了整个处理流程,所以不需要再创建一个新的向量化实例。正如错误信息所说,你需要重新使用最开始训练的向量化器,因为从单词(字符串 n-grams)到列索引的特征映射是保存在向量化器里的。这个映射叫做“词汇表”。

撰写回答