对测试数据使用fit_transform后“尺寸不匹配”的说明

问题描述 投票:0回答:1

我正在阅读一些有关NLP的代码,发现分配给X_test时没有fit_transform(下面的代码最后一行)。

[当我尝试像fit_transform一样使用X_train并继续使用预测模型时,它返回:

ValueError:尺寸不匹配

此问题与该情况有关:SciPy and scikit-learn - ValueError: Dimension mismatch

我想简单解释一下它为什么会发生,因为我不清楚。

下面是我的代码:

from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score

categories = ['alt.atheism', 'comp.graphics']
newsgroups_train = fetch_20newsgroups(subset='train', categories=categories,  
                                      remove=('headers', 'footers', 'quotes'))
newsgroups_test = fetch_20newsgroups(subset='test', categories=categories,  
                                     remove=('headers', 'footers', 'quotes'))
y_train = newsgroups_train.target
y_test = newsgroups_test.target
vectorizer = TfidfVectorizer()
X_train = vectorizer.fit_transform(newsgroups_train.data)
X_test = vectorizer.transform(newsgroups_test.data) #here is the cause of the error if it had 'fit_transform' instead
python scikit-learn tf-idf
1个回答
0
投票

使用TfidfVectorizer().fit_transform()时,它首先计算数据中唯一词汇(特征)的数量,然后计算其频率。您的训练和测试数据没有相同数量的唯一词汇。因此,如果您在每个火车和测试数据上都选择X_test,则X_train.fit_transform()的尺寸将不匹配。因此,您的预测模型会迷失,并给您带来尺寸不匹配错误。

© www.soinside.com 2019 - 2024. All rights reserved.