【问题标题】:Not enough memory while using the Tokenizer in keras.preprocessing.text在 keras.preprocessing.text 中使用 Tokenizer 时内存不足
【发布时间】:2018-06-04 07:57:49
【问题描述】:

我想建立一个使用keras对句子进行分类的RNN模型。

我尝试了以下代码:

docs = []
with open('all_dga.txt', 'r') as f:
    for line in f.readlines():
        dga_domain, _ = line.split(' ')
        docs.append(dga_domain)

t = Tokenizer()
t.fit_on_texts(docs)
encoded_docs = t.texts_to_matrix(docs, mode='count')
print(encoded_docs)

但出现 MemoryError。似乎我无法将所有数据加载到内存中。这是输出:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    encoded_docs = t.texts_to_matrix(docs, mode='count')
  File "/home/yurzho/anaconda3/envs/deepdga/lib/python3.6/site-packages/keras/preprocessing/text.py", line 273, in texts_to_matrix
    return self.sequences_to_matrix(sequences, mode=mode)
  File "/home/yurzho/anaconda3/envs/deepdga/lib/python3.6/site-packages/keras/preprocessing/text.py", line 303, in sequences_to_matrix
    x = np.zeros((len(sequences), num_words))
MemoryError

如果有人熟悉 keras,请告诉我如何预处理数据集。

提前致谢!

【问题讨论】:

  • 尝试减少num_words。

标签: python nlp keras classification rnn


【解决方案1】:

我现在意识到这是一个较老的问题,但我自己也遇到了这个问题。我使用了上述 alvas 答案的组合,然后使用了 keras fit_generator() 方法。

alvas 提到的数据生成器和批处理方法的使用解决了内存使用问题。

【讨论】:

  • 您介意为您所做的工作提供一个工作示例吗?
【解决方案2】:

由于错误发生在t.texts_to_matrix(docs, mode='count') 上,您似乎没有问题拟合文档以从t.fit_on_texts(docs) 创建词汇表。

这样就可以批量转换文档了

from keras.preprocessing.text import Tokenizer

t = Tokenizer()

with open('/Users/liling.tan/test.txt') as fin:
    for line in fin:      
        t.fit_on_texts(line.split()) # Fitting the tokenizer line-by-line.

M = []

with open('/Users/liling.tan/test.txt') as fin:
    for line in fin:
        # Converting the lines into matrix, line-by-line.
        m = t.texts_to_matrix([line], mode='count')[0]
        M.append(m)

但是如果您的计算机无法处理内存中的数据量,您稍后会看到MemoryError。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    相关资源
    最近更新 更多