繁体   English   中英

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

[英]Correct way of measuring execution time of Keras layers

我正在尝试检查 Keras model 不同层的执行速度(使用 keras 来自 Z2C39BC19B701AC36FDC04D vv 的 keras)。

我从这个repo中获取了代码并对其进行了修改,以使用from timeit import default_timertimer()计算时间

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 个神经元更改为具有 [插入大量] 神经元,则即使该层本身保持不变,下一层的执行时间也会发生变化。 所以基本上不可能测量一个层在日照中的执行时间。

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

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

暂无
暂无

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

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