在sklearn的TfidfVectorizer中如何明确包含词语?

8

我有关于 TfidfVectorizer 的一些问题。

我不清楚这些词是如何被选出来的。我们可以给定一个最小支持度,但之后,是什么决定了哪些特征会被选中(例如,更高的支持度有更大的机会)?如果我们说max_features = 10000,我们总是得到相同的结果吗?如果我们说max_features = 12000,我们会得到相同的10000个特征,再加上额外的2000个吗?

此外,是否有一种方法可以扩展这些特征,比如说max_features=20000的特征?我将其用于一些文本,但我知道一些词语肯定应该包括在内,还有一些表情符号“:-)”等。如何将它们添加到TfidfVectorizer对象中,以便能够使用该对象进行fitpredict操作?

to_include = [":-)", ":-P"]
method = TfidfVectorizer(max_features=20000, ngram_range=(1, 3),
                      # I know stopwords, but how about include words?
                      stop_words=test.stoplist[:100], 
                      # include words ??
                      analyzer='word',
                      min_df=5)
method.fit(traindata)

所需结果:


X = method.transform(traindata)
X
<Nx20002 sparse matrix of type '<class 'numpy.int64'>'
 with 1135520 stored elements in Compressed Sparse Row format>], 
 where N is sample size
1个回答

26

您提出了几个不同的问题。让我分别回答:

"我不明白是如何选择单词的。"

根据文档

max_features : optional, None by default
    If not None, build a vocabulary that only consider the top
    max_features ordered by term frequency across the corpus.
在整个语料库中,所有特征(在您的情况下为单元、二元和三元组)按频率排序,然后选择前10000个。不常见的词将被删除。
“If我们说max_features = 10000,我们总是会得到相同的结果吗?如果我们说max_features = 12000,我们会得到相同的10000个特征,但会额外增加2000个吗?”
是的。这个过程是确定性的:对于给定的语料库和给定的max_features,您将始终获得相同的特征。
我对一些文本进行了拟合,但我知道肯定应该包括一些词[...]如何将它们添加到TfidfVectorizer对象中?
您可以使用vocabulary参数指定应使用哪些特征。例如,如果您只想提取表情符号,您可以执行以下操作:
emoticons = {":)":0, ":P":1, ":(":2}
vect = TfidfVectorizer(vocabulary=emoticons)
matrix = vect.fit_transform(traindata)

这将返回一个类型为' ',压缩稀疏行格式,包含M个存储元素的。请注意,只有3列,每个特征一列。

如果您希望词汇表包括表情符号以及N个最常见的特征,您可以首先计算最常见的特征,然后将它们与表情符号合并,并重新进行向量化,如下所示:

# calculate the most frequent features first
vect = TfidfVectorizer(vocabulary=emoticons, max_features=10)
matrix = vect.fit_transform(traindata)
top_features = vect.vocabulary_
n = len(top_features)

# insert the emoticons into the vocabulary of common features
emoticons = {":)":0, ":P":1, ":(":2)}
for feature, index in emoticons.items():
    top_features[feature] = n + index

# re-vectorize using both sets of features
# at this point len(top_features) == 13
vect = TfidfVectorizer(vocabulary=top_features)
matrix = vect.fit_transform(traindata)

感谢您提供完整的答案! - PascalVKooten
虽然这并没有考虑 “:-)” 不是一个单词的事实?就我所看到的,这些将被过滤掉(存储元素为0)。 - PascalVKooten
与我所怀疑的相反,如果有人感兴趣,analyzer需要一个不同的函数,而不是查看任何与“token(ize)”相关的内容。 - PascalVKooten

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接