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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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