sklearn模型数据转换错误:CountVectorizer – 词汇表未拟合

我已经训练了一个用于主题分类的模型。然后当我准备将新数据转换为向量进行预测时,出现了问题。它显示”NotFittedError: CountVectorizer – Vocabulary wasn’t fitted.” 但当我在训练模型中将训练数据分割成测试数据进行预测时,它是正常工作的。以下是代码:

from sklearn.externals import joblibfrom sklearn.feature_extraction.text import CountVectorizerimport pandas as pdimport numpy as np# 读取新数据集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 1799Data columns (total 2 columns):keywords    1800 non-null objecttopics      1800 non-null int64dtypes: int64(1), object(1)memory usage: 28.2+ KB# 读取列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化,并在推理/测试时加载它。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注