如何在scikit-learn中将数字特征与文本(词袋)正确组合?

Phe*_*Kai 8 python classification scikit-learn text-classification

我正在为网页编写分类器,所以我有多种数字特征,我也想对文本进行分类.我正在使用词袋方法将文本转换为(大)数字向量.代码最终是这样的:

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
import numpy as np

numerical_features = [
  [1, 0],
  [1, 1],
  [0, 0],
  [0, 1]
]
corpus = [
  'This is the first document.',
  'This is the second second document.',
  'And the third one',
  'Is this the first document?',
]
bag_of_words_vectorizer = CountVectorizer(min_df=1)
X = bag_of_words_vectorizer.fit_transform(corpus)
words_counts = X.toarray()
tfidf_transformer = TfidfTransformer()
tfidf = tfidf_transformer.fit_transform(words_counts)

bag_of_words_vectorizer.get_feature_names()
combinedFeatures = np.hstack([numerical_features, tfidf.toarray()])
Run Code Online (Sandbox Code Playgroud)

这有效,但我很关心准确性.请注意,有4个对象,只有两个数字特征.即使是最简单的文本也会产生具有九个特征的向量(因为语料库中有九个不同的单词).显然,对于真实文本,将会有数百个或数千个不同的单词,因此最终的特征向量将是<10个数字特征但是> 1000个单词的特征向量.

因此,分类器(SVM)不会将数字特征上的单词加权100到1倍吗?如果是这样,我该如何补偿以确保单词包的数量与数字特征的权重相等?

gre*_*ess 1

我认为你的担忧是完全正确的,因为稀疏文本标记以一种天真的方式(作为多热向量)产生了更高的维度。您至少可以通过以下两种方法来解决这个问题。它们都会从文本中生成一个低维向量(例如 100 维)。当你的词汇量增加时,维度不会增加。