python - Keras:进行超参数网格搜索时内存不足

标签 python memory-management out-of-memory keras grid-search

我正在运行多个嵌套循环来进行超参数网格搜索。每个嵌套循环都运行一个超参数值列表,在最内层的循环中,每次使用生成器构建和评估 Keras 顺序模型。 (我没有做任何训练,我只是随机初始化然后多次评估模型,然后检索平均损失)。

我的问题是,在此过程中,Keras 似乎正在填满我的 GPU 内存,因此我最终遇到了 OOM 错误。

有人知道如何解决这个问题并在每次评估模型后释放 GPU 内存吗?

在对模型进行评估后,我就不再需要它了,每次在内循环的下一轮构建新模型之前,我都可以将其完全丢弃。

我正在使用 Tensorflow 后端。

这是代码,尽管其中大部分与一般问题无关。该模型建立在第四个循环内,

for fsize in fsizes:

我想模型构建的细节并不重要,但这里就是全部:

model_losses = []
model_names = []

for activation in activations:
    for i in range(len(layer_structures)):
        for width in layer_widths[i]:
            for fsize in fsizes:

                model_name = "test_{}_struc-{}_width-{}_fsize-{}".format(activation,i,np.array_str(np.array(width)),fsize)
                model_names.append(model_name)
                print("Testing new model: ", model_name)

                #Structure for this network
                structure = layer_structures[i]

                row, col, ch = 80, 160, 3  # Input image format

                model = Sequential()

                model.add(Lambda(lambda x: x/127.5 - 1.,
                          input_shape=(row, col, ch),
                          output_shape=(row, col, ch)))

                for j in range(len(structure)):
                    if structure[j] == 'conv':
                        model.add(Convolution2D(width[j], fsize, fsize))
                        model.add(BatchNormalization(axis=3, momentum=0.99))
                        if activation == 'relu':
                            model.add(Activation('relu'))
                        if activation == 'elu':
                            model.add(ELU())
                            model.add(MaxPooling2D())
                    elif structure[j] == 'dense':
                        if structure[j-1] == 'dense':
                            model.add(Dense(width[j]))
                            model.add(BatchNormalization(axis=1, momentum=0.99))
                            if activation == 'relu':
                                model.add(Activation('relu'))
                            elif activation == 'elu':
                                model.add(ELU())
                        else:
                            model.add(Flatten())
                            model.add(Dense(width[j]))
                            model.add(BatchNormalization(axis=1, momentum=0.99))
                            if activation == 'relu':
                                model.add(Activation('relu'))
                            elif activation == 'elu':
                                model.add(ELU())

                model.add(Dense(1))

                average_loss = 0
                for k in range(5):
                    model.compile(optimizer="adam", loss="mse")
                    val_generator = generate_batch(X_val, y_val, resize=(160,80))
                    loss = model.evaluate_generator(val_generator, len(y_val))
                    average_loss += loss

                average_loss /= 5

                model_losses.append(average_loss)

                print("Average loss after 5 initializations: {:.3f}".format(average_loss))
                print()

最佳答案

如前所述,使用的后端是 Tensorflow。使用 Tensorflow 后端时,当前模型不会被销毁,因此您需要清除 session 。

在使用模型之后:

if K.backend() == 'tensorflow':
    K.clear_session()

包括后端:

from keras import backend as K

您还可以使用 sklearn wrapper 进行网格搜索。检查此示例:here .此外,对于更高级的超参数搜索,您可以使用 hyperas .

关于python - Keras:进行超参数网格搜索时内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42047497/

相关文章:

c - 安全地使用 realloc

iphone - 内存问题还是其他什么问题?

php - Azure SDK for php blob 下载导致内存不足

java - 什么是堆栈溢出错误?

python - 将 Python 序列(时间序列/数组)拆分为重叠的子序列

python - 在 Python 中更改函数的关键字默认值

python - Redis blpop 有时返回元组,有时不返回?

python - Tensorflow 和 Keras 如何从单热编码输出到类别预测以计算准确性?

iphone - iPad 应用程序被抛弃,而 Allocations Instrument 显示没有异常的内存使用情况

java - 大 XML 文件和 OutOfMemoryError