测量 Keras 层执行时间的正确方法

Correct way of measuring execution time of Keras layers

我正在尝试检查 Keras 模型不同层的执行速度(使用来自 tensorflow 2.3.0 v 的 keras)

我从 repo 中获取了代码并对其进行了修改,以使用 from timeit import default_timer

中的 timer() 来计算时间
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from timeit import default_timer as timer

def time_per_layer(model):
    new_model = model
    times = np.zeros((len(model.layers), 2))
    inp = np.ones((70, 140, 1))
    for i in range(1, len(model.layers)):
        new_model = tf.keras.models.Model(inputs=[model.input], outputs=[model.layers[-i].output])
        # new_model.summary()
        new_model.predict(inp[None, :, :, :])
        t_s = timer()
        new_model.predict(inp[None, :, :, :])
        t_e2 = timer() - t_s
        times[i, 1] = t_e2
        del new_model
    for i in range(0, len(model.layers) - 1):
        times[i, 0] = abs(times[i + 1, 1] - times[i, 1])
    times[-1, 0] = times[-1, 1]
    return times


times = time_per_layer(model)
plt.style.use('ggplot')
x = [model.layers[-i].name for i in range(1,len(model.layers))]
#x = [i for i in range(1,len(model.layers))]
g = [times[i,0] for i in range(1,len(times))]
x_pos = np.arange(len(x))
plt.bar(x, g, color='#7ed6df')
plt.xlabel("Layers")
plt.ylabel("Processing Time")
plt.title("Processing Time of each Layer")
plt.xticks(x_pos, x,rotation=90)

plt.show()

这是测量不同层执行时间的正确方法吗?

我会说没有正确的方法来测量不同层的执行时间,因为

  1. 神经网络作为一个整体工作(整体大于部分之和)。你不能在不破坏系统的情况下从训练有素的网络中间拔出一个层,因此测量它处理某事的时间并不是特别有用。

  2. 一层的执行时间还取决于上一层。如果将前面的层从具有 1 个神经元更改为具有 [插入大量] 神经元,即使层本身保持不变,下一层的执行时间也会发生变化。所以基本上不可能测量一个层在日照下的执行时间。

一个合理的衡量标准是,如果添加额外的层,执行时间会发生多少变化 - 比较具有该层的网络与没有该层的网络的总体执行时间。但这将需要您重新训练模型。

您可以测量的另一件事是,当您将附加层添加到网络的底部时,执行时间会发生多少变化(类似于您正在做的事情,但仅将前 N 层的总执行时间与执行时间进行比较N + 1层)。当您考虑在进行迁移学习时要保留多少基础层时(假设 NN 架构允许这样做),这可能会有点用处,但即便如此,准确性也可能成为决定性因素,所以...