首页 > 解决方案 > Tensorflow Keras 神经网络模型清除 GPU 内存

问题描述

我正在尝试使用 keras 构建神经网络。我正在使用Windows 10并安装tensorflow在我的 GPU 上,NVIDA GeForce 1060因此我使用的是 CUDA :10.0和 tensorflow 2.3.0

基本上,如果我单独运行一次,这可以工作,但我现在想为这个网络找到最佳配置,因此我每次都尝试构建模型,然后找到最好的。我打算在 for 循环中这样做。
但我的模型完全取决于参数数据,模型看起来像:

model_heightmap = Sequential(
        [
            # Input(shape=(140, 150)),
            # Reshape(target_shape=(140 * 150,), input_shape=(140, 150)),
            Flatten(input_shape=(140, 150)),
            Dense(8000, activation='relu'),
            Dense(5000, activation='relu'),
            Dense(3000, activation='relu'),
            Dense(500, activation='relu'),
            Dense(200, activation='relu'),
            Dense(5, activation='softmax'),
            Dense(df_max_cat + 1, activation='softmax')
        ]
    )

所以这里是df_max_cat变化的因素。
但是当 for 循环进行第二次迭代时,它会出现以下错误: 2020-10-03 13:45:29.899409: I tensorflow/stream_executor/cuda/cuda_driver.cc:775] failed to allocate 818.20M (857944832 bytes) from device: CUDA_ERROR_OUT_OF_MEMORY: out of memory
我知道这个错误的发生是因为我的内存不足,这是因为我每次都创建新模型。
我不需要旧模型,所以我如何清理旧的 GPU 内存空间以供下次运行???
我已经尝试过:

del model_heightmap  # for avoid any trace on aigen
tf.keras.backend.clear_session()  # removing session, it will instance another

有人对如何解决这个问题有任何想法吗?

标签: pythontensorflowkerasgputensorflow2.0

解决方案


推荐阅读