sk中的TfidfVectorizer学习如何具体包括单词

2024-05-18 19:14:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些关于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

Tags: 对象方法文本功能include特性单词method
1条回答
网友
1楼 · 发布于 2024-05-18 19:14:39

你在问几个不同的问题。让我分别回答:

“我不清楚单词是如何选择的。”

documentation

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.

所有的特征(在你的例子中是unigrams,bigrams和trigrams)在整个语料库中按频率排序,然后选择顶部10000。不寻常的话被扔掉了。

“如果我们说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)

这将返回一个<Nx3 sparse matrix of type '<class 'numpy.int64'>' with M stored elements in Compressed Sparse Row format>]。注意,只有3列,每个功能一列。

如果希望词汇表包含表情符号和最常见的功能,可以先计算最常见的功能,然后将它们与表情符号合并并重新矢量化,如下所示:

# 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)

相关问题 更多 >

    热门问题