在 keras 中调用 to_categorical 时出现 MemoryError

MemoryError when calling to_categorical in keras

我尝试运行 语言建模程序。当我在文档中使用包含 15000 个句子的数据序列时,程序 运行ning 正常。但是,当我尝试用更大的数据(大 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。我已经这样做了,但是同样的回溯仍然是错误的。

谢谢

我认为这个错误是预料之中的。这里真正的问题是你没有足够的 space 来分配 1) 决策层的参数矩阵,and/or 2) 中间张量。

参数矩阵的形状为input_feat_dim x output_num_classes。正如你所看到的,当词汇量很大时,这个矩阵会消耗大量的内存。 为了训练网络,我们还需要为 BP 保留中间张量,它会更大 -- batch_size x input_feat_dim x output_num_classes

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

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