【问题标题】:MemoryError when calling to_categorical in keras在 keras 中调用 to_categorical 时出现 MemoryError
【发布时间】:2019-03-02 18:25:49
【问题描述】:

我尝试运行语言建模程序。当我使用文档中包含 15000 句的数据序列时,程序运行正常。但是,当我尝试用更大的数据(大 10 倍)更改数据时,遇到如下错误:

Traceback (most recent call last):

  File "<ipython-input-2-aa5ef9098286>", line 1, in <module>
    runfile('C:/Users/cerdas/Documents/Bil/Lat/lstm-plato-lm/platolm.py', wdir='C:/Users/cerdas/Documents/Bil/Lat/lstm-plato-lm')

  File "C:\Users\cerdas\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

  File "C:\Users\cerdas\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/cerdas/Documents/Bil/Lat/lstm-plato-lm/platolm.py", line 35, in <module>
    y = to_categorical(y, num_classes=vocab_size)

  File "C:\Users\cerdas\Anaconda3\lib\site-packages\keras\utils\np_utils.py", line 30, in to_categorical
    categorical = np.zeros((n, num_classes), dtype=np.float32)

MemoryError

这是可疑的错误代码行:

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

还有np.utils

categorical = np.zeros((n, num_classes), dtype=np.float64)

我试图搜索类似问题的解决方案,我发现我必须将categorical_crossentropy 更改为sparse_categorical_crossentropy。我已经这样做了,但是使用相同的回溯仍然是错误的。

谢谢

【问题讨论】:

    标签: python numpy memory keras cross-entropy


    【解决方案1】:

    我认为这个错误是意料之中的。这里真正的问题是您没有足够的空间来分配 1) 决策层的参数矩阵和/或 2) 中间张量。

    参数矩阵的形状为input_feat_dim x output_num_classes。可以看到,这个矩阵在词汇量很大的时候会消耗大量的内存。 为了训练一个网络,我们还需要为 BP 保留中间张量,它会更大——batch_size x input_feat_dim x output_num_classes

    因此,您可以快速尝试的一件事是将您的 batch_size 减少到 1/10。当然,您不能将批量大小设置得太小。在这种情况下,您可能希望累积梯度,直到看到足够的样本。

    【讨论】:

      【解决方案2】:

      如果您切换到稀疏分类交叉熵损失,那么您不需要to_categorical 调用,这实际上是给出错误的那个。稀疏分类交叉熵应该适用于此。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 2017-11-14
      • 2019-05-26
      • 1970-01-01
      • 2019-03-26
      • 2010-11-14
      相关资源
      最近更新 更多