python - 每次重复后,keras 模型的训练都会变慢

标签 python tensorflow keras

我正在编写一些代码来优化神经网络架构,因此有一个 python 函数 create_nn(parms) 来创建和初始化 keras 模型。 然而,我遇到的问题是,经过较少的迭代后,模型的训练时间比平时要长得多(最初一个时期需要 10 秒,然后大约在第 14 个模型之后(每个模型训练 20 个时期)需要 60 秒/时代)。 我知道这不是因为不断发展的架构,因为如果我重新启动脚本并开始它结束的情况,它就会恢复到正常速度。

我正在运行

from keras import backend as K

然后是

K.clear_session()

训练任何给定的新模型后。

一些其他详细信息:

  • 对于前 12 个模型,每个时期的训练时间大致保持在 10 秒/时期。然后,在第 13 个模型中,每个 epoch 的训练时间稳步攀升至 60 秒。然后每个 epoch 的训练时间徘徊在 60 秒/epoch 左右。

  • 我正在运行 keras,并以 Tensorflow 作为后端

  • 我正在使用 Amazon EC2 t2.xlarge 实例

  • 有足够的可用 RAM(7GB 可用,带有 5GB 大小的数据集)

我删除了一堆层和参数,但基本上 create_nn 看起来像:

def create_nn(features, timesteps, number_of_filters):
    inputs = Input(shape = (timesteps, features))
    x = GaussianNoise(stddev=0.005)(inputs)
    #Layer 1.1
    x = Convolution1D(number_of_filters, 3, padding='valid')(x)
    x = Activation('relu')(x)
    x = Flatten()(x)
    x = Dense(10)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = Dropout(0.5)(x)
    # Output layer
    outputs = Dense(1, activation='sigmoid')(x)
    model = Model(inputs=inputs, outputs=outputs)

    # Compile and Return
    model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
    print('CNN model built succesfully.')
    return model

请注意,虽然Sequential 模型可以在这个虚拟示例中工作,但实际用例需要功能性 API。

如何解决这个问题?

最佳答案

为什么每次运行后我的训练时间都会增加?

简短回答:您需要在创建每个新模型之前使用tf.keras.backend.clear_session()

此问题似乎仅在关闭急切执行时才会发生。

好吧,让我们在使用和不使用clear_session 的情况下进行实验。 make_model 的代码位于此响应的末尾。

首先,我们看一下使用clear session时的训练时间。我们将运行此实验 10 次并打印结果

使用 tf.keras.backend.clear_session()

non_seq_time = [ make_model(clear_session=True) for _ in range(10)]

使用clear_session=True

non sequential
Elapse =  1.06039
Elapse =  1.20795
Elapse =  1.04357
Elapse =  1.03374
Elapse =  1.02445
Elapse =  1.00673
Elapse =  1.01712
Elapse =    1.021
Elapse =  1.17026
Elapse =  1.04961

如您所见,训练时间保持不变

现在让我们在不使用清晰 session 的情况下重新运行实验并查看训练时间

不要使用 tf.keras.backend.clear_session()

non_seq_time = [ make_model(clear_session=False) for _ in range(10)]

使用clear_session=False

non sequential
Elapse =  1.10954
Elapse =  1.13042
Elapse =  1.12863
Elapse =   1.1772
Elapse =   1.2013
Elapse =  1.31054
Elapse =  1.27734
Elapse =  1.32465
Elapse =  1.32387
Elapse =  1.33252

如您所见,没有clear_session,训练时间会增加

完整代码示例

# Training time increases - and how to fix it

# Setup and imports

# %tensorflow_version 2.x

import tensorflow as tf
import tensorflow.keras.layers as layers
import tensorflow.keras.models as models
from time import time

# if you comment this out, the problem doesn't happen
# it only happens when eager execution is disabled !!
tf.compat.v1.disable_eager_execution()


(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()


# Let's build that network
def make_model(activation="relu", hidden=2, units=100, clear_session=False):
    # -----------------------------------
    # .     HERE WE CAN TOGGLE CLEAR SESSION
    # -----------------------------------
    if clear_session:
        tf.keras.backend.clear_session()

    start = time()
    inputs = layers.Input(shape=[784])
    x = inputs

    for num in range(hidden) :
        x = layers.Dense(units=units, activation=activation)(x)

    outputs = layers.Dense(units=10, activation="softmax")(x)
    model = tf.keras.Model(inputs=inputs, outputs=outputs)
    model.compile(optimizer='sgd', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

    results = model.fit(x_train, y_train, validation_data=(x_test, y_test), batch_size=200, verbose=0)
    elapse = time()-start
    print(f"Elapse = {elapse:8.6}")
    return elapse

# Let's try it out and time it

# prime it first
make_model()

print("Use clear session")
non_seq_time = [ make_model(clear_session=True) for _ in range(10)]

print("Don't use clear session")
non_seq_time = [ make_model(clear_session=False) for _ in range(10)]

关于python - 每次重复后,keras 模型的训练都会变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45796167/

相关文章:

python - tensorflow_hub 在 Windows 机器上拉出 BERT 嵌入 - 扩展到 albert

python - 洗牌如何与机器学习中的 ImageDataGenerator 一起工作?

python - 我如何知道我的神经网络模型是否过拟合(Keras)

python - 如何将文件 key 传递给在 S3 Put 上触发的 AWS-ECS 容器?

python - 为什么我的时间替换正则表达式不起作用?

python - 在 Tkinter 应用程序关闭时执行任务

python - 具有离散 Action 空间的软 Actor 评论家

python - 为什么自动编码器与编码器 + 解码器的预测不同?

python - 子进程不等待并导致 PhantomJS 崩溃

python - 将 Tensor 作为输入传递给 Keras api 功能模型