如何使用 nlp.pipe 模式加速 spacy 管道?

How to speed up a spacy pipeline with the nlp.pipe pattern?

在 spacy 的 pipeline documentation 之后,我一直在尝试使用 nlp.pipe 模式来加快我的管道。我发现的是,无论我设置 batch_size 与顺序 运行.

相比,都没有加速

我想知道问题出在我这边还是批处理不起作用?

我正在对平均长度为 1500 个字符的 30000 条文本测试此行为,我已经测试了 5,50,500,5000 的批处理大小,但无济于事。

所以我计时:

for text in texts:
   doc = nlp(text)

VS

doc_gen = nlp.pipe(texts, batch_size, n_threads)

有n_threads -1 & 2 测试批量大小 5、50、500、5000 texts 包含 30000 个文档,平均长度为 1500 个字符

我的计时结果没有显示使用和不使用管道模式之间的任何显着差异。

我运行宁Python 3 spacy 2.0.12

The batch size is parameter specific to nlp.pipe, and again, a good value depends on the data being worked on. For reasonably long-sized text such as news articles, it makes sense to keep the batch size reasonably small (so that each batch doesn't contain really long texts), so in this case 20 was chosen for the batch size. For other cases (e.g. Tweets) where each document is much shorter in length, a larger batch size can be used.

-Prashanth Rao, https://prrao87.github.io/blog/spacy/nlp/performance/2020/05/02/spacy-multiprocess.html#Option-1:-Sequentially-process-DataFrame-column

除了包括上面这个有用的引用之外,我在上面链接的文章还讨论了使用 SpaCy 加速文本预处理的 3 种不同方法。

如果使用管道不能加快流程,我建议使用 .apply 函数代替,如下文和该网站上所述!我已经看到它缩短了一个过程,从 9 个多小时缩短到 47 分钟。

上面链接的页面提供了以下代码:

def lemmatize(text):
    """Perform lemmatization and stopword removal in the clean text
       Returns a list of lemmas
    """
    doc = nlp(text)
    lemma_list = [str(tok.lemma_).lower() for tok in doc
                  if tok.is_alpha and tok.text.lower() not in stopwords]
    return lemma_list

生成的引理作为列表存储在单独的预处理列中,如下所示。

%%time
df_preproc['preproc'] = df_preproc['clean'].apply(lemmatize)
df_preproc[['date', 'content', 'preproc']].head(3)