【问题标题】:How to stop memory memory leak from Flask and NLTK如何阻止 Flask 和 NLTK 的内存泄漏
【发布时间】:2013-03-02 01:05:54
【问题描述】:

我正在使用 NLTK 和 Flask 构建一个 Web 应用程序。这只是一个简单的 RESTful 应用程序,我将它部署在 heroku 上,一切顺利。但是,当服务器开始收到更多请求时,我达到了 heroku 的内存限制,即 1.5GB。所以,我猜这是因为每次请求到来时我都在加载nltk.RegexpParser。

这是非常简单的代码。

@app.route('/get_keywords', methods=['POST']) def get_keywords(): data_json = json.loads(request.data) text = urllib.unquote(data_json["sentence"]) keywords = KeywordExtraction().extract(text) return ','.join(keywords)

这是关键字提取位。

import re import nltk nltk.data.path.append('./nltk_data/') from nltk.corpus import stopwords class KeywordExtraction: def extract(self, text): sentences = nltk.sent_tokenize(text) sentences = [nltk.word_tokenize(sent) for sent in sentences] sentences = [nltk.pos_tag(sent) for sent in sentences] grammar = "NP: {}" cp = nltk.RegexpParser(grammar) tree = cp.parse(sentences[0]) keywords = [subtree.leaves()[0][0] for subtree in tree.subtrees(filter=lambda t: t.node == 'NP')] keywords_without_stopwords = [w for w in keywords if not w in stopwords.words('english')] return list(set(keywords_without_stopwords + tags))

我不确定这是我的代码、Flask 还是 NLTK 的问题。我对 Python 很陌生。任何建议将不胜感激。

我通过 blitz.io 对此进行了测试,仅在 250 个请求之后,服务器就炸毁并开始抛出 R15。

【问题讨论】:

  • 您可以将cp 设为静态类变量(请参阅stackoverflow.com/questions/68645/…)。我怀疑这会解决你的问题。你也可以用 stopwords.words('english') 试试这个,这样你就不会创建很多该列表的实例。那么你应该只创建一个 KeywordExtractor 并一直使用它,而不是为每个请求创建一个。

标签: python performance memory-leaks nltk


【解决方案1】:

从缓存东西开始:

# Move these outside of the class declaration or make them class variables

stopwords = set(stopwords.words('english'))
grammar = "NP: {}"
cp = nltk.RegexpParser(grammar)

这也可以加快一点:

from itertools import ifilterfalse

...

keywords_without_stopwords = ifilterfalse(stopwords.__contains__, keywords)

return list(keywords_without_stopwords + set(tags))  # Can you cache `set(tags`)?

我还想看看 Flask-Cache,以便尽可能多地记忆和缓存函数和视图。

【讨论】:

    猜你喜欢
    • 2016-01-01
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 2015-09-14
    • 1970-01-01
    • 2011-05-22
    相关资源
    最近更新 更多