【发布时间】: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