用于多标签分类问题的tf-idf矢量化器

时间:2019-02-13 00:49:14

标签: python nlp tf-idf multilabel-classification tfidfvectorizer

我有一个用于大量文本的多标签分类项目。 我在文本(train_v ['doc_text'])上使用了tf-Idf矢量化器,如下所示:

tfidf_transformer = TfidfTransformer()
X_counts = count_vect.fit_transform(train_v['doc_text']) 
X_tfidf = tfidf_transformer.fit_transform(X_counts) 
x_train_tfidf, x_test_tfidf, y_train_tfidf, y_test_tfidf = train_test_split(X_tfidf_r, label_vs, test_size=0.33, random_state=9000)
sgd = SGDClassifier(loss='hinge', penalty='l2', random_state=42, max_iter=25, tol=None, fit_intercept=True, alpha = 0.000009  )

现在,我需要对一组功能(test_v ['doc_text'])使用相同的矢量化器来预测标签。 但是,当我使用以下

X_counts_test = count_vect.fit_transform(test_v['doc_text']) 
X_tfidf_test = tfidf_transformer.fit_transform(X_counts_test) 
predictions_test = clf.predict(X_tfidf_test)

我收到一条错误消息

ValueError: X has 388894 features per sample; expecting 330204

关于如何处理此问题的任何想法?

谢谢。

1 个答案:

答案 0 :(得分:0)

问题是您在这里使用fit_transform,使TfidfTransform()适合test data,然后对其进行转换。

在其上使用transform方法。

此外,您应该使用TfidfVectorizer

我认为代码应为:

from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_transformer = TfidfVectorizer()
# X_counts = count_vect.fit_transform(train_v['doc_text']) 
X_tfidf = tfidf_transformer.fit_transform(train_v['doc_text']) 
x_train_tfidf, x_test_tfidf, y_train_tfidf, y_test_tfidf = train_test_split(X_tfidf, label_vs, test_size=0.33, random_state=9000)
sgd = SGDClassifier(loss='hinge', penalty='l2', random_state=42, max_iter=25, tol=None, fit_intercept=True, alpha = 0.000009  )

# X_counts_test = count_vect.fit_transform(test_v['doc_text']) 
X_tfidf_test = tfidf_transformer.transform(test_v['doc_text']) 
predictions_test = clf.predict(X_tfidf_test)

此外,为什么要使用count_vect,但我认为这里没有可用性,而在train_test_split中,您使用的是X_tfidf_r,在任何地方都没有提及。