【问题标题】:Optimizing memory usage - Pandas/Python优化内存使用 - Pandas/Python
【发布时间】:2018-02-28 13:46:17
【问题描述】:

我目前正在处理一个包含原始文本的数据集,我应该对其进行预处理:

from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize 
from nltk.stem import SnowballStemmer
from nltk.stem.wordnet import WordNetLemmatizer

stop_words = set(stopwords.words('english'))
stemmer = SnowballStemmer('english')
lemma = WordNetLemmatizer()

from autocorrect import spell

for df in [train_df, test_df]:
    df['comment_text'] = df['comment_text'].apply(lambda x: word_tokenize(str(x)))
    df['comment_text'] = df['comment_text'].apply(lambda x: [lemma.lemmatize(spell(word)) for word in x])
    df['comment_text'] = df['comment_text'].apply(lambda x: ' '.join(x))

但是,包含spell 函数会增加内存使用量,直到出现“内存错误”。如果不使用此类功能,就不会发生这种情况。我想知道是否有办法优化这个过程,保持spell 函数(数据集有很多拼写错误的单词)。

【问题讨论】:

    标签: python pandas memory-management out-of-memory


    【解决方案1】:

    我无法访问您的数据框,所以这有点推测,但这里是...

    DataFrame.apply 将在整个列上一次运行lambda 函数,因此它可能会在内存中保存进度。相反,您可以将 lambda 函数转换为预定义函数,并改用 DataFrame.map,这将按元素应用函数。

    def spellcheck_string(input_str):
        return [lemma.lemmatize(spell(word)) for word in x]
    
    for df in [train_df, test_df]:
       # ...
        df['comment_text'] = df['comment_text'].map(spellcheck_string)
       # ...
    

    你可以试试看是否有帮助?

    【讨论】:

    • 哦,太好了,不知道这个!我会尝试一下!谢谢。
    • 内存再次达到 11 GB。现在13。我试过一次,我的电脑死机了。
    • 你的数据集有多大?列中的大约项目数以及 ["comment_text"] 字段的典型大小?我很乐意根据一些虚拟数据提供帮助。可能对数据进行批量操作是前进的方向。
    • 我正在使用这个数据集:kaggle.com/c/jigsaw-toxic-comment-classification-challenge。谢谢你的好意。我正在再次运行代码,我可以在不中断的情况下检查行。
    • *无法检查行数。我现在的方法是并行化它。
    【解决方案2】:

    无论如何,我会使用 dask,您可以将数据框分成块(分区),然后您可以检索每个部分并使用它。

    https://dask.pydata.org/en/latest/dataframe.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-02
      • 2014-10-02
      • 2016-09-01
      相关资源
      最近更新 更多