【问题标题】:TfidfVectorizer in sklearn how to specifically INCLUDE wordssklearn中的TfidfVectorizer如何专门包含单词
【发布时间】:2013-11-14 06:12:07
【问题描述】:

我对@9​​87654321@ 有一些疑问。

我不清楚这些词是如何选择的。我们可以提供最低限度的支持,但在那之后,将决定选择哪些功能(例如,更高的支持更多的机会)?如果我们说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

【问题讨论】:

    标签: python machine-learning nlp scikit-learn


    【解决方案1】:

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

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

    来自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.
    

    所有特征(在你的例子中是一元、二元和三元)在整个语料库中按频率排序,然后选择顶部的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)
    

    这将返回一个&lt;Nx3 sparse matrix of type '&lt;class 'numpy.int64'&gt;' with M stored elements in Compressed Sparse Row format&gt;]。请注意,只有 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)
    

    【讨论】:

    • 感谢您的完整回答!
    • 虽然这不考虑":-)"不是一个词的事实?据我所知,这些将被过滤掉(0个存储元素)。
    • 与我的怀疑相反,如果有人感兴趣,analyzer 需要一个不同的功能,而不是查看与“token(ize)”相关的任何内容。
    猜你喜欢
    • 1970-01-01
    • 2019-07-29
    • 2021-03-09
    • 2015-01-05
    • 2021-02-13
    • 2014-12-14
    • 2017-11-20
    • 2019-08-05
    • 2015-10-13
    相关资源
    最近更新 更多