繁体   English   中英

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

[英]Keras - How to get time taken by each layer in training?

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

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

这并不简单,因为每一层都在每个 epoch 中得到训练。 您可以使用回调来获取整个网络的 epoch 训练时间,但是您必须进行某种拼凑才能获得所需的内容(每层的近似训练时间)。

步骤 -

  1. 创建一个回调来记录每个 epoch 的运行时间
  2. 将网络中的每一层设置为不可训练,只有一层设置为可训练。
  3. 在少量时期训练模型并获得平均运行时间
  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

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM