簡體   English   中英

每次重復后,keras 模型的訓練變慢

[英]Training of keras model get's slower after each repetition

我正在編寫一些代碼來優化神經網絡架構,因此有一個 python 函數create_nn(parms)來創建和初始化 keras 模型。 然而,我遇到的問題是,在較少的迭代之后,模型需要比平時更長的時間來訓練(最初一個時期需要 10 秒,然后大約在第 14 個模型之后(每個模型訓練 20 個時期)需要 60 秒/時代)。 我知道這不是因為不斷發展的架構,因為如果我重新啟動腳本並開始它結束,它會恢復正常速度。

我目前正在跑步

from keras import backend as K

然后一個

K.clear_session()

在訓練任何給定的新模型之后。

一些額外的細節:

  • 對於前 12 個模型,每個時期的訓練時間大致保持在 10 秒/時期不變。 然后在第 13 個模型訓練時間每 epoch 穩步攀升至 60 秒。 然后每個時期的訓練時間徘徊在 60 秒/時期左右。

  • 我正在使用 Tensorflow 作為后端運行 keras

  • 我使用的是 Amazon EC2 t2.xlarge 實例

  • 有足夠的可用內存(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

如您所見,訓練時間保持不變

現在讓我們在不使用 clear 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)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM