【发布时间】:2017-07-23 14:16:24
【问题描述】:
我有一个清除一组停用词文本的功能:
def clean_text(raw_text, stopwords_set):
# removing everything which is not a letter
letters_only = re.sub("[^a-zA-Z]", " ", raw_text)
# lower case + split --> list of words
words = letters_only.lower().split()
# now remove the stop words
meaningful_words = [w for w in words if not w in stopwords_set]
# join the remaining words together to get the cleaned tweet
return " ".join(meaningful_words)
还有一个包含 160 万条推特推文的数据集,位于 pandas 数据框中。如果我只是简单地将apply这个函数添加到这样的数据帧中:
dataframe['clean_text'] = dataframe.apply(
lambda text: clean_text(text, set(stopwords.words('english'))),
axis = 1)
计算需要 2 分钟才能完成(大约)。但是,当我像这样使用np.vectorize 时:
dataframe['clean_text'] = np.vectorize(clean_text)(
dataframe['text'], set(stopwords.words('english')))
计算在 10 秒后完成(大约)。
这本身并不奇怪,如果不是这两种方法都只在我的机器上使用了一个内核。我假设,使用矢量化,它会自动使用多个内核来更快地完成,从而获得更快的速度,但它似乎做了一些不同的事情。
numpy 的 ´vectorize` 有什么“魔力”?
【问题讨论】:
-
再次,您是否阅读过
np.vectorize上的文档?它声明 -"The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.". -
@Divakar 那如何解释加速?即使有知识,我也看不出这是如何解释加速的,所以这对我没有帮助。请保持建设性,谢谢。
-
你能根据 for-loop 版本计时吗?
-
与 numpy 数组上的显式循环相比,
vectorize通常显示出小的加速 (20%)。但是您将其与 pandas apply 进行比较。像这样使用可能会非常慢。 -
确保矢量化工作正常。它可能一次向您的功能提供一个停用词。检查输出的形状。
标签: pandas numpy vectorization stop-words