我已经训练了一个用于主题分类的模型。然后,当我要将新数据转换为向量以进行预测时,它就出错了。它显示“ NotFittedError:CountVectorizer-词汇不正确。”但是,当我通过将训练数据分成训练模型中的测试数据进行预测时,它可以工作。代码如下:

from sklearn.externals import joblib
from sklearn.feature_extraction.text import CountVectorizer

import pandas as pd
import numpy as np

# read new dataset
testdf = pd.read_csv('C://Users/KW198/Documents/topic_model/training_data/testdata.csv', encoding='cp950')

testdf.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1800 entries, 0 to 1799
Data columns (total 2 columns):
keywords    1800 non-null object
topics      1800 non-null int64
dtypes: int64(1), object(1)
memory usage: 28.2+ KB

# read columns
kw = testdf['keywords']
label = testdf['topics']

# 將預測資料轉為向量
vectorizer = CountVectorizer(min_df=1, stop_words='english')
x_testkw_vec = vectorizer.transform(kw)


这是一个错误

---------------------------------------------------------------------------
NotFittedError                            Traceback (most recent call last)
<ipython-input-93-cfcc7201e0f8> in <module>()
      1 # 將預測資料轉為向量
      2 vectorizer = CountVectorizer(min_df=1, stop_words='english')
----> 3 x_testkw_vec = vectorizer.transform(kw)

~\Anaconda3\envs\ztdl\lib\site-packages\sklearn\feature_extraction\text.py in transform(self, raw_documents)
    918             self._validate_vocabulary()
    919
--> 920         self._check_vocabulary()
    921
    922         # use the same matrix-building strategy as fit_transform

~\Anaconda3\envs\ztdl\lib\site-packages\sklearn\feature_extraction\text.py in _check_vocabulary(self)
    301         """Check if vocabulary is empty or missing (not fit-ed)"""
    302         msg = "%(name)s - Vocabulary wasn't fitted."
--> 303         check_is_fitted(self, 'vocabulary_', msg=msg),
    304
    305         if len(self.vocabulary_) == 0:

~\Anaconda3\envs\ztdl\lib\site-packages\sklearn\utils\validation.py in check_is_fitted(estimator, attributes, msg, all_or_any)
    766
    767     if not all_or_any([hasattr(estimator, attr) for attr in attributes]):
--> 768         raise NotFittedError(msg % {'name': type(estimator).__name__})
    769
    770

NotFittedError: CountVectorizer - Vocabulary wasn't fitted.

最佳答案

您需要在调用vectorizer.fit()之前调用vectorizer.transform()来使计数矢量化器构建单词词典。您也可以只调用结合了两者的vectorizer.fit_transform()

但是您不应该使用新的矢量化程序进行测试或任何推理。您需要使用与训练模型时相同的方法,否则由于词汇不同(缺少某些单词,对齐方式不同等),结果将是随机的。

为此,您只需pickle训练中使用的矢量化器,然后将其加载到推理/测试时间即可。

08-25 00:48