【问题标题】:How to speed up computation time for stopword removal and lemmatization in NLP如何加快 NLP 中停用词删除和词形还原的计算时间
【发布时间】:2021-11-30 23:41:24
【问题描述】:

作为文本分类模型预处理的一部分,我使用 NLTK 库添加了停用词删除和词形还原步骤。代码如下:

import pandas as pd
import nltk; nltk.download("all")
from nltk.corpus import stopwords; stop = set(stopwords.words('english'))
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet

# Stopwords removal


def remove_stopwords(entry):
  sentence_list = [word for word in entry.split() if word not in stopwords.words("english")]
  return " ".join(sentence_list)

df["Description_no_stopwords"] = df.loc[:, "Description"].apply(lambda x: remove_stopwords(x))

# Lemmatization

lemmatizer = WordNetLemmatizer()

def punct_strip(string):
  s = re.sub(r'[^\w\s]',' ',string)
  return s

def get_wordnet_pos(word):
    """Map POS tag to first character lemmatize() accepts"""
    tag = nltk.pos_tag([word])[0][1][0].upper()
    tag_dict = {"J": wordnet.ADJ,
                "N": wordnet.NOUN,
                "V": wordnet.VERB,
                "R": wordnet.ADV}

    return tag_dict.get(tag, wordnet.NOUN)

def lemmatize_rows(entry):
  sentence_list = [lemmatizer.lemmatize(word, get_wordnet_pos(word)) for word in punct_strip(entry).split()]
  return " ".join(sentence_list)

df["Description - lemmatized"] = df.loc[:, "Description_no_stopwords"].apply(lambda x: lemmatize_rows(x))

问题在于,当我预处理包含 27k 个条目的数据集(我的测试集)时,移除停用词需要 40-45 秒,而词形还原则需要同样长的时间。相比之下,模型评估只需要 2-3 秒。

如何重写函数以优化计算速度?我读过一些关于矢量化的东西,但是示例函数比我报告的要简单得多,在这种情况下我不知道该怎么做。

【问题讨论】:

    标签: python pandas performance nlp


    【解决方案1】:

    here 提出了类似的问题,并建议您尝试缓存 stopwords.words("english") 对象。在您的方法remove_stopwords 中,您每次评估条目时都会创建对象。所以,你绝对可以改进它。关于您的lemmatizer,如here 所述,您还可以缓存您的结果以提高性能。我可以想象您的pandas 操作也相当昂贵。您可以考虑将数据框转换为数组或字典,然后对其进行迭代。如果您以后需要数据框,您可以轻松地将其转换回来。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 2018-10-13
      • 1970-01-01
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多