python - Keras - 如何获得训练中每一层所花费的时间?

标签 python tensorflow keras

我已经使用 Tensorflow 后端为图像分类任务实现了 Keras 顺序模型。它有一些自定义层来替换 Keras 层,如 conv2d、max-pooling 等。但是在添加这些层之后,虽然保留了准确性,但训练时间增加了数倍。因此,我需要查看这些层是否在前向或反向传播(通过反向传播)或两者都需要时间,以及这些操作中的哪些可能需要优化(使用 Eigen 等)。

但是,我找不到任何方法来了解模型中每个层/操作所花费的时间。检查了 Tensorboard 和回调的功能,但无法了解它们如何帮助计时训练细节。有什么方法可以做到这一点?感谢您的帮助。

最佳答案

这并不简单,因为每一层都在每个时期接受训练。您可以使用回调来获得整个网络的纪元训练时间,但是您必须进行某种拼凑才能获得所需的东西(每层的近似训练时间)。

步骤-

  1. 创建一个回调来记录每个 epoch 的运行时间
  2. 将网络中的每一层都设置为不可训练,只有一个层可训练。
  3. 在少量 epoch 上训练模型并获得平均运行时间
  4. 为网络中的每个独立层循环执行步骤 2 到 3
  5. 返回结果

这不是实际的运行时间,但是,您可以对哪一层比另一层花费的时间比例更高进行相对分析。

#Callback class for time history (picked up this solution directly from StackOverflow)

class TimeHistory(Callback):
    def on_train_begin(self, logs={}):
        self.times = []

    def on_epoch_begin(self, batch, logs={}):
        self.epoch_time_start = time.time()

    def on_epoch_end(self, batch, logs={}):
        self.times.append(time.time() - self.epoch_time_start)
        
time_callback = TimeHistory()

# Model definition

inp = Input((inp_dims,))
embed_out = Embedding(vocab_size, 256, input_length=inp_dims)(inp)

x = Conv1D(filters=32, kernel_size=3, activation='relu')(embed_out)
x = MaxPooling1D(pool_size=2)(x)
x = Flatten()(x)

x = Dense(64, activation='relu')(x)
x = Dropout(0.5)(x)
x = Dense(32, activation='relu')(x)
x = Dropout(0.5)(x)
out = Dense(out_dims, activation='softmax')(x)

model = Model(inp, out)
model.summary()

# Function for approximate training time with each layer independently trained

def get_average_layer_train_time(epochs):
    
    #Loop through each layer setting it Trainable and others as non trainable
    results = []
    for i in range(len(model.layers)):
        
        layer_name = model.layers[i].name    #storing name of layer for printing layer
        
        #Setting all layers as non-Trainable
        for layer in model.layers:
            layer.trainable = False
            
        #Setting ith layers as trainable
        model.layers[i].trainable = True
        
        #Compile
        model.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['acc'])
        
        #Fit on a small number of epochs with callback that records time for each epoch
        model.fit(X_train_pad, y_train_lbl,      
              epochs=epochs, 
              batch_size=128, 
              validation_split=0.2, 
              verbose=0,
              callbacks = [time_callback])
        
        results.append(np.average(time_callback.times))
        #Print average of the time for each layer
        print(f"{layer_name}: Approx (avg) train time for {epochs} epochs = ", np.average(time_callback.times))
    return results

runtimes = get_average_layer_train_time(5)
plt.plot(runtimes)

#input_2: Approx (avg) train time for 5 epochs =  0.4942781925201416
#embedding_2: Approx (avg) train time for 5 epochs =  0.9014601230621337
#conv1d_2: Approx (avg) train time for 5 epochs =  0.822748851776123
#max_pooling1d_2: Approx (avg) train time for 5 epochs =  0.479401683807373
#flatten_2: Approx (avg) train time for 5 epochs =  0.47864508628845215
#dense_4: Approx (avg) train time for 5 epochs =  0.5149370670318604
#dropout_3: Approx (avg) train time for 5 epochs =  0.48329877853393555
#dense_5: Approx (avg) train time for 5 epochs =  0.4966880321502686
#dropout_4: Approx (avg) train time for 5 epochs =  0.48073616027832033
#dense_6: Approx (avg) train time for 5 epochs =  0.49605698585510255

enter image description here

关于python - Keras - 如何获得训练中每一层所花费的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55491846/

相关文章:

python - 带有字符串变量字段的 Django 过滤器

python - 如何使用查询集更新 django auth_user?

python - 将 struct.unpack 从 python 2.7 移植到 3

python - .get_rect() 和 .move 在 pygame 中

machine-learning - 使用神经网络学习方波函数

python - 如何在 Keras 中调整(插值)张量?

python - 来自形状为 [32,1] 的张量的 Keras 有状态 LSTM 错误 : Specified a list with shape [4, 1]

keras - CNN 最后一层使用哪些设置进行回归

python - 如何减少VGG16中间层瓶颈特征的大小?

python - Tensorflow 中的 Dice/Jaccard 系数优化