【问题标题】:What does the default sklearn TfidfVectorizer preprocessor do?默认的 sklearn TfidfVectorizer 预处理器有什么作用?
【发布时间】:2019-04-18 18:14:45
【问题描述】:

我正在查看 sklearn 的 TfidfVectorizer,特别是 preprocessor 输入参数,其中包含以下文档:

“覆盖预处理(字符串转换)阶段,同时保留标记化和 n-gram 生成步骤。”

我想弄清楚当我不覆盖预处理阶段时,它到底做了什么(如果有的话)?

我有一个实验,我正在使用以下代码查看生成的稀疏矩阵中存储元素的数量:

vectorizer = TfidfVectorizer(stop_words=words, preprocessor=process, ngram_range=(1,1), strip_accents='unicode')
vect = vectorizer.fit_transform(twenty_train.data)
items_stored = vect.nnz
  • 当我不重写预处理器时,生成的矩阵会存储 1278323 个元素。
  • 当我使用空方法覆盖预处理器时,生成的矩阵会存储 1441372 个元素。
  • 当我使用包含s = re.sub("[^a-zA-Z]", " ", s) 的方法覆盖预处理器时,生成的矩阵将存储1331597 个元素。
  • 我无法通过任何其他处理步骤影响稀疏矩阵的大小(或用于分类时的准确性)。

显然,与默认的 sklearn 结果、没有预处理以及我尝试复制预处理步骤存在差异。我正在努力寻找有关预处理器在默认情况下具体做什么的文档。

我还检查了source code 中的TfidfVectorizer - 但是我也无法从这里弄清楚预处理器在做什么。

有没有人碰巧知道 sklearn 的默认预处理器执行了哪些代码或采取了哪些预处理步骤?

【问题讨论】:

  • 你看过this吗?
  • 如果你不覆盖它,它最终会在这里调用build_preprocessor方法:github.com/scikit-learn/scikit-learn/blob/master/sklearn/…
  • 默认情况下预处理器只是改变字符串的大小写(取决于其他参数是否也保持默认)。因此,您在其中传递一个空方法的第二种情况将产生更多标记,因为现在相同的字符串将根据它们的大小写被视为不同。
  • 至于你的第三点和第四点,你需要展示你所做的实际代码。

标签: python machine-learning scikit-learn


【解决方案1】:

你在找这个吗?

def build_preprocessor(self):
    """Return a function to preprocess the text before tokenization"""
    if self.preprocessor is not None:
        return self.preprocessor

    # unfortunately python functools package does not have an efficient
    # `compose` function that would have allowed us to chain a dynamic
    # number of functions. However the cost of a lambda call is a few
    # hundreds of nanoseconds which is negligible when compared to the
    # cost of tokenizing a string of 1000 chars for instance.
    noop = lambda x: x

    # accent stripping
    if not self.strip_accents:
        strip_accents = noop
    elif callable(self.strip_accents):
        strip_accents = self.strip_accents
    elif self.strip_accents == 'ascii':
        strip_accents = strip_accents_ascii
    elif self.strip_accents == 'unicode':
        strip_accents = strip_accents_unicode
    else:
        raise ValueError('Invalid value for "strip_accents": %s' %
                         self.strip_accents)

    if self.lowercase:
        return lambda x: strip_accents(x.lower())
    else:
        return strip_accents

从这里:https://github.com/scikit-learn/scikit-learn/blob/bac89c2/sklearn/feature_extraction/text.py#L230

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 2019-11-18
    • 1970-01-01
    • 2017-06-03
    • 2017-08-24
    相关资源
    最近更新 更多