在将Linear SVC模型应用于测试集时,我遇到了ValueError: X has 5851 features per sample; expecting 2754

我在尝试使用Linear SVC对文本进行分类时遇到了一个错误。

我按照下面的代码将模型应用于测试集。在这段代码中,我创建了Tfidf,并对训练集进行了过采样处理。

#Import datasetstrain = pd.read_csv('train_labeled.csv')test = pd.read_csv('test.csv')#Clean datasetscustom_pipeline = [preprocessing.fillna,                   preprocessing.lowercase,                   preprocessing.remove_whitespace,                   preprocessing.remove_punctuation,                   preprocessing.remove_urls,                   preprocessing.remove_digits,                   preprocessing.stem                     ]train["clean_text"] = train["text"].pipe(hero.clean, custom_pipeline)test["clean_text"] = test["text"].pipe(hero.clean, custom_pipeline)#Create Tfidfcount_vect = CountVectorizer()X_train_counts = count_vect.fit_transform(train["clean_text"])tfidf_transformer = TfidfTransformer()X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)X_test_counts = count_vect.fit_transform(test["clean_text"])X_test_tfidf = tfidf_transformer.fit_transform(X_test_counts)#Oversampling of trainig setover = RandomOverSampler(sampling_strategy='minority')X_os, y_os = over.fit_resample(X_train_tfidf, train["label"])#Modelclf = svm.LinearSVC(C=1.0, penalty='l2', loss='squared_hinge', dual=True, tol=1e-3)clf.fit(X_os, y_os)pred = clf.predict(X_test_tfidf)

然后我得到了如下错误。我认为这是因为测试集有5851个样本,而训练集只有2754个样本。

ValueError: X has 5851 features per sample; expecting 2754

在这种情况下,我应该怎么做?


回答:

不要在测试数据上调用fit_transform(),因为转换器会学习一个新的词汇表,并且不会以与训练数据相同的方式转换测试数据。要使用与训练数据相同的词汇表,请在测试数据上仅使用transform()

# initialize transformerscount_vect = CountVectorizer()tfidf_transformer = TfidfTransformer()# fit and transform train dataX_train_counts = count_vect.fit_transform(train["clean_text"])X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)# transform test dataX_test_counts = count_vect.transform(test["clean_text"])X_test_tfidf = tfidf_transformer.transform(X_test_counts)

注意

如果您不需要CountVectorizer的输出,可以使用TfidfVectorizer来减少需要编写的代码量:

tfidf_vect = TfidfVectorizer()X_train_tfidf = tfidf_vect.fit_transform(train["clean_text"])X_test_tfidf = tfidf_vect.transform(test["clean_text"])

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中创建了一个多类分类项目。该项目可以对…

发表回复

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